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

18 SWIG and Allegro Common Lisp

+

18 SWIG and Allegro Common Lisp

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

    -

    18.1 Basics

    +

    18.1 Basics

    -

    18.1.1 Running SWIG

    +

    18.1.1 Running SWIG

    @@ -280,39 +280,39 @@ actual function.

    example_wrap.i
    -   ... lots of SWIG internals ...
    +  ... lots of SWIG internals ...
     
     EXPORT int ACL___fact__SWIG_0 (char *larg1) {
    -    int lresult = (int)0 ;
    -    char *arg1 = (char *) 0 ;
    -    int result;
    -    
    -    arg1 = larg1;
    -    try {
    -        result = (int)fact(arg1);
    -        
    -        lresult = result;
    -        return lresult;
    -    } catch (...) {
    -        return (int)0;
    -    }
    +  int lresult = (int)0 ;
    +  char *arg1 = (char *) 0 ;
    +  int result;
    +
    +  arg1 = larg1;
    +  try {
    +    result = (int)fact(arg1);
    +
    +    lresult = result;
    +    return lresult;
    +  } catch (...) {
    +    return (int)0;
    +  }
     }
     
     
     EXPORT int ACL___fact__SWIG_1 (int larg1) {
    -    int lresult = (int)0 ;
    -    int arg1 ;
    -    int result;
    -    
    -    arg1 = larg1;
    -    try {
    -        result = (int)fact(arg1);
    -        
    -        lresult = result;
    -        return lresult;
    -    } catch (...) {
    -        return (int)0;
    -    }
    +  int lresult = (int)0 ;
    +  int arg1 ;
    +  int result;
    +
    +  arg1 = larg1;
    +  try {
    +    result = (int)fact(arg1);
    +
    +    lresult = result;
    +    return lresult;
    +  } catch (...) {
    +    return (int)0;
    +  }
     }
     
    @@ -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.
     

    -

    18.1.2 Command Line Options

    +

    18.1.2 Command Line Options

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

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

    -

    18.1.3 Inserting user code into generated files

    +

    18.1.3 Inserting user code into generated files

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

    -

    18.2 Wrapping Overview

    +

    18.2 Wrapping Overview

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

    -

    18.2.1 Function Wrapping

    +

    18.2.1 Function Wrapping

    @@ -472,7 +472,7 @@ interested in generating an interface to C++. | Foreign Code | What we're generating an interface to. |______________| | - | + | _______v______ | | (foreign side) | Wrapper code | extern "C" wrappers calling C++ @@ -484,22 +484,22 @@ interested in generating an interface to C++. | FFI Layer | Low level lisp interface. ff:def-foreign-call, |______________| ff:def-foreign-variable | - +---------------------------- + +---------------------------- _______v______ _______v______ | | | | (lisp side) | Defuns | | Defmethods | wrapper for overloaded |______________| |______________| functions or those with (lisp side) | defaulted arguments - Wrapper for non-overloaded | - functions and methods _______v______ - | | (lisp side) - | Defuns | dispatch function - |______________| to overloads based - on arity + Wrapper for non-overloaded | + functions and methods _______v______ + | | (lisp side) + | Defuns | dispatch function + |______________| to overloads based + on arity

-

18.2.2 Foreign Wrappers

+

18.2.2 Foreign Wrappers

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

-

18.2.3 FFI Wrappers

+

18.2.3 FFI Wrappers

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

-

18.2.4 Non-overloaded Defuns

+

18.2.4 Non-overloaded Defuns

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

-

18.2.5 Overloaded Defuns

+

18.2.5 Overloaded Defuns

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

-

18.2.6 What about constant and variable access?

+

18.2.6 What about constant and variable access?

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

-

18.2.7 Object Wrapping

+

18.2.7 Object Wrapping

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

-

18.3 Wrapping Details

+

18.3 Wrapping Details

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

-

18.3.1 Namespaces

+

18.3.1 Namespaces

@@ -688,10 +688,10 @@ char *xxx(); %include "foo.h" namespace car { - ... - namespace tires { - int do_something(int n); - } + ... + namespace tires { + int do_something(int n); + } } @@ -742,7 +742,7 @@ namespace car { function such as (car '(1 2 3).

-

18.3.2 Constants

+

18.3.2 Constants

@@ -799,11 +799,11 @@ namespace car {

- Users are cautioned to get to know their constants before use, or - not use the -nocwrap command-line option. + Users are cautioned to get to know their constants before use, or + not use the -nocwrap command-line option.

-

18.3.3 Variables

+

18.3.3 Variables

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

18.3.4 Enumerations

+

18.3.4 Enumerations

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

For example, the following header file

enum.h:
-enum COL { RED, GREEN, BLUE };	
+enum COL { RED, GREEN, BLUE };
 enum FOO { FOO1 = 10, FOO2, FOO3 };
       
@@ -957,7 +957,7 @@ EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3; -

18.3.5 Arrays

+

18.3.5 Arrays

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

18.3.6 Classes and Structs and Unions (oh my!)

+

18.3.6 Classes and Structs and Unions (oh my!)

-

18.3.6.1 CLOS wrapping of

+

18.3.6.1 CLOS wrapping of

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

-

18.3.6.2 CLOS Inheritance

+

18.3.6.2 CLOS Inheritance

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

-

18.3.6.3 Member fields and functions

+

18.3.6.3 Member fields and functions

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

-

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

+

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

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

-

18.3.7 Templates

+

18.3.7 Templates

-

18.3.7.1 Generating wrapper code for templates

+

18.3.7.1 Generating wrapper code for templates

-

- SWIG provides support for dealing with templates, but by - default, it will not generate any member variable or function - wrappers for templated classes. In order to create these - wrappers, you need to explicitly tell SWIG to instantiate - them. This is done via the - %template - directive. -

+

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

-

18.3.7.2 Implicit Template instantiation

+

18.3.7.2 Implicit Template instantiation

-

- While no wrapper code is generated for accessing member - variables, or calling member functions, type code is generated - to include these templated classes in the foreign-type and CLOS - class schema. -

+

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

-

18.3.8 Typedef, Templates, and Synonym Types

+

18.3.8 Typedef, Templates, and Synonym Types

@@ -1209,8 +1209,8 @@ namespace BAR {

synonyms.h
 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:
     

- (setf (find-class <synonym>) <primary>) + (setf (find-class <synonym>) <primary>)

The result is that all references to synonym types in foreign @@ -1277,7 +1277,7 @@ synonym>

-

18.3.8.1 Choosing a primary type

+

18.3.8.1 Choosing a primary type

@@ -1285,20 +1285,20 @@ synonym> criteria from a set of synonym types.

    -
  • - If a synonym type has a class definition, it is the primary type. -
  • -
  • - If a synonym type is a class template and has been explicitly - instantiated via %template, it is the primary type. -
  • -
  • - For all other sets of synonymous types, the synonym which is - parsed first becomes the primary type. -
  • +
  • + If a synonym type has a class definition, it is the primary type. +
  • +
  • + If a synonym type is a class template and has been explicitly + instantiated via %template, it is the primary type. +
  • +
  • + For all other sets of synonymous types, the synonym which is + parsed first becomes the primary type. +
-

18.3.9 Function overloading/Parameter defaulting

+

18.3.9 Function overloading/Parameter defaulting

@@ -1336,70 +1336,70 @@ float xxx(A *inst, int x); /* return x + A->x + A->y */

overload_wrap.cxx
 EXPORT void ACL___delete_A__SWIG_0 (A *larg1) {
-    A *arg1 = (A *) 0 ;
-    
-    arg1 = larg1;
-    try {
-        delete arg1;
-        
-    } catch (...) {
-        
-    }
+  A *arg1 = (A *) 0 ;
+
+  arg1 = larg1;
+  try {
+    delete arg1;
+
+  } catch (...) {
+
+  }
 }
 
 
 EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
-    float lresult = (float)0 ;
-    int arg1 ;
-    int arg2 ;
-    float result;
-    
-    arg1 = larg1;
-    arg2 = larg2;
-    try {
-        result = (float)xxx(arg1,arg2);
-        
-        lresult = result;
-        return lresult;
-    } catch (...) {
-        return (float)0;
-    }
+  float lresult = (float)0 ;
+  int arg1 ;
+  int arg2 ;
+  float result;
+
+  arg1 = larg1;
+  arg2 = larg2;
+  try {
+    result = (float)xxx(arg1,arg2);
+
+    lresult = result;
+    return lresult;
+  } catch (...) {
+    return (float)0;
+  }
 }
 
 
 EXPORT float ACL___xxx__SWIG_1 (int larg1) {
-    float lresult = (float)0 ;
-    int arg1 ;
-    float result;
-    
-    arg1 = larg1;
-    try {
-        result = (float)xxx(arg1);
-        
-        lresult = result;
-        return lresult;
-    } catch (...) {
-        return (float)0;
-    }
+  float lresult = (float)0 ;
+  int arg1 ;
+  float result;
+
+  arg1 = larg1;
+  try {
+    result = (float)xxx(arg1);
+
+    lresult = result;
+    return lresult;
+  } catch (...) {
+    return (float)0;
+  }
 }
 
 
 EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
-    float lresult = (float)0 ;
-    A *arg1 = (A *) 0 ;
-    int arg2 ;
-    float result;
-    
-    arg1 = larg1;
-    arg2 = larg2;
-    try {
-        result = (float)xxx(arg1,arg2);
-        
-        lresult = result;
-        return lresult;
-    } catch (...) {
-        return (float)0;
-    }
+  float lresult = (float)0 ;
+  A *arg1 = (A *) 0 ;
+  int arg2 ;
+  float result;
+
+  arg1 = larg1;
+  arg2 = larg2;
+  try {
+    result = (float)xxx(arg1,arg2);
+
+    lresult = result;
+    return lresult;
+  } catch (...) {
+    return (float)0;
+  }
 }
     
@@ -1461,7 +1461,7 @@ overload> -

18.3.10 Operator wrapping and Operator overloading

+

18.3.10 Operator wrapping and Operator overloading

@@ -1472,68 +1472,68 @@ overload>

 /* name conversion for overloaded operators. */
 #ifdef __cplusplus
-%rename(__add__)	     *::operator+;
-%rename(__pos__)	     *::operator+();
-%rename(__pos__)	     *::operator+() const;
+%rename(__add__)             *::operator+;
+%rename(__pos__)             *::operator+();
+%rename(__pos__)             *::operator+() const;
 
-%rename(__sub__)	     *::operator-;
-%rename(__neg__)	     *::operator-() const;
-%rename(__neg__)	     *::operator-();
+%rename(__sub__)             *::operator-;
+%rename(__neg__)             *::operator-() const;
+%rename(__neg__)             *::operator-();
 
-%rename(__mul__)	     *::operator*;
-%rename(__deref__)	     *::operator*();
-%rename(__deref__)	     *::operator*() const;
+%rename(__mul__)             *::operator*;
+%rename(__deref__)           *::operator*();
+%rename(__deref__)           *::operator*() const;
 
-%rename(__div__)	     *::operator/;
-%rename(__mod__)	     *::operator%;
-%rename(__logxor__)	     *::operator^;
-%rename(__logand__)	     *::operator&;
-%rename(__logior__)	     *::operator|;
-%rename(__lognot__)	     *::operator~();
-%rename(__lognot__)	     *::operator~() const;
+%rename(__div__)             *::operator/;
+%rename(__mod__)             *::operator%;
+%rename(__logxor__)          *::operator^;
+%rename(__logand__)          *::operator&;
+%rename(__logior__)          *::operator|;
+%rename(__lognot__)          *::operator~();
+%rename(__lognot__)          *::operator~() const;
 
-%rename(__not__)	     *::operator!();
-%rename(__not__)	     *::operator!() const;
+%rename(__not__)             *::operator!();
+%rename(__not__)             *::operator!() const;
 
-%rename(__assign__)	     *::operator=;
+%rename(__assign__)          *::operator=;
 
 %rename(__add_assign__)      *::operator+=;
-%rename(__sub_assign__)	     *::operator-=;
-%rename(__mul_assign__)	     *::operator*=;
-%rename(__div_assign__)	     *::operator/=;
-%rename(__mod_assign__)	     *::operator%=;
+%rename(__sub_assign__)      *::operator-=;
+%rename(__mul_assign__)      *::operator*=;
+%rename(__div_assign__)      *::operator/=;
+%rename(__mod_assign__)      *::operator%=;
 %rename(__logxor_assign__)   *::operator^=;
 %rename(__logand_assign__)   *::operator&=;
 %rename(__logior_assign__)   *::operator|=;
 
-%rename(__lshift__)	     *::operator<<;
+%rename(__lshift__)          *::operator<<;
 %rename(__lshift_assign__)   *::operator<<=;
-%rename(__rshift__)	     *::operator>>;
+%rename(__rshift__)          *::operator>>;
 %rename(__rshift_assign__)   *::operator>>=;
 
-%rename(__eq__)		     *::operator==;
-%rename(__ne__)		     *::operator!=;
-%rename(__lt__)		     *::operator<;
-%rename(__gt__)		     *::operator>;
-%rename(__lte__)	     *::operator<=;
-%rename(__gte__)	     *::operator>=;
+%rename(__eq__)              *::operator==;
+%rename(__ne__)              *::operator!=;
+%rename(__lt__)              *::operator<;
+%rename(__gt__)              *::operator>;
+%rename(__lte__)             *::operator<=;
+%rename(__gte__)             *::operator>=;
 
-%rename(__and__)	     *::operator&&;
-%rename(__or__)		     *::operator||;
+%rename(__and__)             *::operator&&;
+%rename(__or__)              *::operator||;
 
-%rename(__preincr__)	     *::operator++();
-%rename(__postincr__)	     *::operator++(int);
-%rename(__predecr__)	     *::operator--();
-%rename(__postdecr__)	     *::operator--(int);
+%rename(__preincr__)         *::operator++();
+%rename(__postincr__)        *::operator++(int);
+%rename(__predecr__)         *::operator--();
+%rename(__postdecr__)        *::operator--(int);
 
-%rename(__comma__)	     *::operator,();
-%rename(__comma__)	     *::operator,() const;
+%rename(__comma__)           *::operator,();
+%rename(__comma__)           *::operator,() const;
 
 %rename(__member_ref__)      *::operator->;
 %rename(__member_func_ref__) *::operator->*;
 
-%rename(__funcall__)	     *::operator();
-%rename(__aref__)	     *::operator[];
+%rename(__funcall__)         *::operator();
+%rename(__aref__)            *::operator[];
     
@@ -1607,7 +1607,7 @@ opoverload> -

18.3.11 Varargs

+

18.3.11 Varargs

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

-

18.3.12 C++ Exceptions

+

18.3.12 C++ Exceptions

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

-

18.3.13 Pass by value, pass by reference

+

18.3.13 Pass by value, pass by reference

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

-

18.4 Typemaps

+

18.4 Typemaps

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

-

18.4.1 Code Generation in the C++ Wrapper

+

18.4.1 Code Generation in the C++ Wrapper

@@ -1675,25 +1675,25 @@ opoverload>
 return-val wrapper-name(parm0, parm1, ..., parmN)
 {
-   return-val lresult;   /* return value from wrapper */
-   <local-declaration>
-   ... results;          /* return value from function call */
+  return-val lresult;   /* return value from wrapper */
+  <local-declaration>
+  ... results;          /* return value from function call */
 
-   <binding locals to parameters>
+  <binding locals to parameters>
 
-   try {
-      result = function-name(local0, local1, ..., localN);
+  try {
+    result = function-name(local0, local1, ..., localN);
 
-      <convert and bind result to lresult>
+    <convert and bind result to lresult>
 
-      return lresult;
-   catch (...) {
-      return (int)0;
-   }
+    return lresult;
+  catch (...) {
+    return (int)0;
+  }
     
-

18.4.1.1 IN Typemap

+

18.4.1.1 IN Typemap

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

18.4.1.2 OUT Typemap

+

18.4.1.2 OUT Typemap

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

18.4.1.3 CTYPE Typemap

+

18.4.1.3 CTYPE Typemap

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

-

18.4.2 Code generation in Lisp wrappers

+

18.4.2 Code generation in Lisp wrappers

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

-

18.4.2.1 LIN Typemap

+

18.4.2.1 LIN Typemap

@@ -1821,32 +1821,32 @@ return-val wrapper-name(parm0, parm1, ..., parmN)

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. +
-%typemap(lin)	SWIGTYPE 	"(cl:let (($out $in))\n  $body)";
+%typemap(lin) SWIGTYPE "(cl:let (($out $in))\n  $body)";
     
-

18.4.2.2 LOUT Typemap

+

18.4.2.2 LOUT Typemap

@@ -1858,17 +1858,17 @@ return-val wrapper-name(parm0, parm1, ..., parmN)

The LOUT typemap uses the following $variable

    -
  • $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). +
@@ -1889,7 +1889,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN)
-

18.4.2.3 FFITYPE Typemap

+

18.4.2.3 FFITYPE Typemap

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

18.4.2.4 LISPTYPE Typemap

+

18.4.2.4 LISPTYPE Typemap

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

18.4.2.5 LISPCLASS Typemap

+

18.4.2.5 LISPCLASS Typemap

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

18.4.3 Modifying SWIG behavior using typemaps

+

18.4.3 Modifying SWIG behavior using typemaps

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

18.5 Identifier Converter functions

+

18.5 Identifier Converter functions

-

18.5.1 Creating symbols in the lisp environment

+

18.5.1 Creating symbols in the lisp environment

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

-

18.5.2 Existing identifier-converter functions

+

18.5.2 Existing identifier-converter functions

Two basic identifier routines have been defined. -

18.5.2.1 identifier-convert-null

+

18.5.2.1 identifier-convert-null

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

-

18.5.2.2 identifier-convert-lispify

+

18.5.2.2 identifier-convert-lispify

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

-

18.5.2.3 Default identifier to symbol conversions

+

18.5.2.3 Default identifier to symbol conversions

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

-

18.5.3 Defining your own identifier-converter

+

18.5.3 Defining your own identifier-converter

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

-

18.5.4 Instructing SWIG to use a particular identifier-converter

+

18.5.4 Instructing SWIG to use a particular identifier-converter

diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html index 2890e2415..8838e67a9 100644 --- a/Doc/Manual/Android.html +++ b/Doc/Manual/Android.html @@ -1,11 +1,12 @@ - + SWIG and Android + -

19 SWIG and Android

+

19 SWIG and Android

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

    19.1 Overview

    +

    19.1 Overview

    The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is used to call from Android Java into C or C++ compiled code. -Everything in the 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.

    -

    19.2 Android examples

    +

    19.2 Android examples

    -

    19.2.1 Examples introduction

    +

    19.2.1 Examples introduction

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

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

    -

    19.2.2 Simple C example

    +

    19.2.2 Simple C example

    @@ -209,7 +210,7 @@ When complete your device should be listed in those attached, something like:

     $ adb devices
     List of devices attached 
    -A32-6DBE0001-9FF80000-015D62C3-02018028	device
    +A32-6DBE0001-9FF80000-015D62C3-02018028 device
     
@@ -221,7 +222,7 @@ This means you are now ready to install the application...
 $ adb install bin/SwigSimple-debug.apk 
 95 KB/s (4834 bytes in 0.049s)
-	pkg: /data/local/tmp/SwigSimple-debug.apk
+        pkg: /data/local/tmp/SwigSimple-debug.apk
 Success
 
@@ -398,7 +399,7 @@ Run the app again and this time you will see the output pictured below, showing
Android screenshot of SwigSimple example
-

19.2.3 C++ class example

+

19.2.3 C++ class example

@@ -746,7 +747,7 @@ Run the app to see the result of calling the C++ code from Java:

Android screenshot of SwigClass example
-

19.2.4 Other examples

+

19.2.4 Other examples

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

-

19.3 C++ STL

+

19.3 C++ STL

diff --git a/Doc/Manual/Arguments.html b/Doc/Manual/Arguments.html index 3b7713686..48ec5c629 100644 --- a/Doc/Manual/Arguments.html +++ b/Doc/Manual/Arguments.html @@ -1,12 +1,13 @@ - + Argument Handling + -

10 Argument Handling

+

10 Argument Handling

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

    -

    10.1 The typemaps.i library

    +

    10.1 The typemaps.i library

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

    -

    10.1.1 Introduction

    +

    10.1.1 Introduction

    @@ -59,7 +60,7 @@ Suppose you had a C function like this:

     void add(double a, double b, double *result) {
    -	*result = a + b;
    +  *result = a + b;
     }
     
    @@ -194,7 +195,7 @@ else. To clear a typemap, the %clear directive should be used. For e
-

10.1.2 Input parameters

+

10.1.2 Input parameters

@@ -203,7 +204,7 @@ input value:

-int *INPUT		
+int *INPUT
 short *INPUT
 long *INPUT
 unsigned int *INPUT
@@ -220,7 +221,7 @@ function:
 
 
 double add(double *a, double *b) {
-	return *a+*b;
+  return *a+*b;
 }
 
@@ -247,7 +248,7 @@ When the function is used in the scripting language interpreter, it will work li result = add(3,4)
-

10.1.3 Output parameters

+

10.1.3 Output parameters

@@ -272,7 +273,7 @@ These methods can be used as shown in an earlier example. For example, if you ha

 void add(double a, double b, double *c) {
-	*c = a+b;
+  *c = a+b;
 }
 
@@ -314,7 +315,7 @@ iresult, dresult = foo(3.5, 2) -

10.1.4 Input/Output parameters

+

10.1.4 Input/Output parameters

@@ -338,7 +339,7 @@ A C function that uses this might be something like this:

 void negate(double *x) {
-	*x = -(*x);
+  *x = -(*x);
 }
 
 
@@ -379,7 +380,7 @@ rather than directly overwriting the value of the original input object. SWIG. Backwards compatibility is preserved, but deprecated.

-

10.1.5 Using different names

+

10.1.5 Using different names

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

-

10.2 Applying constraints to input values

+

10.2 Applying constraints to input values

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

-

10.2.1 Simple constraint example

+

10.2.1 Simple constraint example

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

-

10.2.2 Constraint methods

+

10.2.2 Constraint methods

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

10.2.3 Applying constraints to new datatypes

+

10.2.3 Applying constraints to new datatypes

diff --git a/Doc/Manual/CCache.html b/Doc/Manual/CCache.html new file mode 100644 index 000000000..d23b0cb2f --- /dev/null +++ b/Doc/Manual/CCache.html @@ -0,0 +1,474 @@ + + + +ccache-swig(1) manpage + + + + + +

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

+ + + + + + +

+

17.1 NAME

+ + +

+ +ccache-swig - a fast compiler cache + +

+

17.2 SYNOPSIS

+ + +

+ccache-swig [OPTION] +

+ccache-swig <compiler> [COMPILER OPTIONS] +

+<compiler> [COMPILER OPTIONS] +

+

17.3 DESCRIPTION

+ + +

+ccache-swig is a compiler cache. It speeds up re-compilation of C/C++/SWIG code +by caching previous compiles and detecting when the same compile is +being done again. ccache-swig is ccache plus support for SWIG. ccache +and ccache-swig are used interchangeably in this document. +

+

17.4 OPTIONS SUMMARY

+ + +

+Here is a summary of the options to ccache-swig. +

+

+
+-s                      show statistics summary
+-z                      zero statistics
+-c                      run a cache cleanup
+-C                      clear the cache completely
+-F <n>                  set maximum files in cache
+-M <n>                  set maximum size of cache (use G, M or K)
+-h                      this help page
+-V                      print version number
+
+
+ +

+

17.5 OPTIONS

+ + +

+These options only apply when you invoke ccache as "ccache-swig". When +invoked as a compiler none of these options apply. In that case your +normal compiler options apply and you should refer to your compilers +documentation. +

+

+

-h
Print a options summary page +

+

-s
Print the current statistics summary for the cache. The +statistics are stored spread across the subdirectories of the +cache. Using "ccache-swig -s" adds up the statistics across all +subdirectories and prints the totals. +

+

-z
Zero the cache statistics. +

+

-V
Print the ccache version number +

+

-c
Clean the cache and re-calculate the cache file count and +size totals. Normally the -c option should not be necessary as ccache +keeps the cache below the specified limits at runtime and keeps +statistics up to date on each compile. This option is mostly useful +if you manually modify the cache contents or believe that the cache +size statistics may be inaccurate. +

+

-C
Clear the entire cache, removing all cached files. +

+

-F <maxfiles>
This sets the maximum number of files allowed in +the cache. The value is stored inside the cache directory and applies +to all future compiles. Due to the way the value is stored the actual +value used is always rounded down to the nearest multiple of 16. +

+

-M <maxsize>
This sets the maximum cache size. You can specify +a value in gigabytes, megabytes or kilobytes by appending a G, M or K +to the value. The default is gigabytes. The actual value stored is +rounded down to the nearest multiple of 16 kilobytes. +

+

+

+

17.6 INSTALLATION

+ + +

+There are two ways to use ccache. You can either prefix your compile +commands with "ccache-swig" or you can create a symbolic link between +ccache-swig and the names of your compilers. The first method is most +convenient if you just want to try out ccache or wish to use it for +some specific projects. The second method is most useful for when you +wish to use ccache for all your compiles. +

+To install for usage by the first method just copy ccache-swig to somewhere +in your path. +

+To install for the second method do something like this: +

+
+  cp ccache-swig /usr/local/bin/
+  ln -s /usr/local/bin/ccache-swig /usr/local/bin/gcc
+  ln -s /usr/local/bin/ccache-swig /usr/local/bin/g++
+  ln -s /usr/local/bin/ccache-swig /usr/local/bin/cc
+  ln -s /usr/local/bin/ccache-swig /usr/local/bin/swig
+
+
+ +This will work as long as /usr/local/bin comes before the path to gcc +(which is usually in /usr/bin). After installing you may wish to run +"which gcc" to make sure that the correct link is being used. +

+Note! Do not use a hard link, use a symbolic link. A hardlink will +cause "interesting" problems. +

+

17.7 EXTRA OPTIONS

+ + +

+When run as a compiler front end ccache usually just takes the same +command line options as the compiler you are using. The only exception +to this is the option '--ccache-skip'. That option can be used to tell +ccache that the next option is definitely not a input filename, and +should be passed along to the compiler as-is. +

+The reason this can be important is that ccache does need to parse the +command line and determine what is an input filename and what is a +compiler option, as it needs the input filename to determine the name +of the resulting object file (among other things). The heuristic +ccache uses in this parse is that any string on the command line that +exists as a file is treated as an input file name (usually a C +file). By using --ccache-skip you can force an option to not be +treated as an input file name and instead be passed along to the +compiler as a command line option. +

+

17.8 ENVIRONMENT VARIABLES

+ + +

+ccache uses a number of environment variables to control operation. In +most cases you won't need any of these as the defaults will be fine. +

+

+

+

CCACHE_DIR
the CCACHE_DIR environment variable specifies +where ccache will keep its cached compiler output. The default is +"$HOME/.ccache". +

+

CCACHE_TEMPDIR
the CCACHE_TEMPDIR environment variable specifies +where ccache will put temporary files. The default is the same as +CCACHE_DIR. Note that the CCACHE_TEMPDIR path must be on the same +filesystem as the CCACHE_DIR path, so that renames of files between +the two directories can work. +

+

CCACHE_LOGFILE
If you set the CCACHE_LOGFILE environment +variable then ccache will write some log information on cache hits +and misses in that file. This is useful for tracking down problems. +

+

CCACHE_VERBOSE
If you set the CCACHE_VERBOSE environment +variable then ccache will display on stdout all the compiler invocations +that it makes. This can useful for debugging unexpected problems. +

+

CCACHE_PATH
You can optionally set CCACHE_PATH to a colon +separated path where ccache will look for the real compilers. If you +don't do this then ccache will look for the first executable matching +the compiler name in the normal PATH that isn't a symbolic link to +ccache itself. +

+

CCACHE_CC
You can optionally set CCACHE_CC to force the name +of the compiler to use. If you don't do this then ccache works it out +from the command line. +

+

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

+

+

+

17.9 CACHE SIZE MANAGEMENT

+ + +

+By default ccache has a one gigabyte limit on the cache size and no +maximum number of files. You can set a different limit using the +"ccache -M" and "ccache -F" options, which set the size and number of +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. +

+

17.10 CACHE COMPRESSION

+ + +

+By default on most platforms ccache will compress all files it puts +into the cache +using the zlib compression. While this involves a negligible +performance slowdown, it significantly increases the number of files +that fit in the cache. You can turn off compression setting the +CCACHE_NOCOMPRESS environment variable. +

+

17.11 HOW IT WORKS

+ + +

+The basic idea is to detect when you are compiling exactly the same +code a 2nd time and use the previously compiled output. You detect +that it is the same code by forming a hash of: +

+

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

+

17.12 USING CCACHE WITH DISTCC

+ + +

+distcc is a very useful program for distributing compilation across a +range of compiler servers. It is often useful to combine distcc with +ccache, so that compiles that are done are sped up by distcc, but that +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'. +

+

17.13 SHARING A CACHE

+ + +

+A group of developers can increase the cache hit rate by sharing a +cache directory. The hard links however cause unwanted side effects, +as all links to a cached file share the file's modification timestamp. +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. +
+

+

17.14 HISTORY

+ + +

+ccache was inspired by the compilercache shell script script written +by Erik Thiele and I would like to thank him for an excellent piece of +work. See +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. +

+

17.15 DIFFERENCES FROM COMPILERCACHE

+ + +

+The biggest differences between Erik's compilercache script and ccache +are: +

    +
  • ccache is written in C, which makes it a bit faster (calling out to + external programs is mostly what slowed down the scripts). +
  • ccache can automatically find the real compiler +
  • ccache keeps statistics on hits/misses +
  • ccache can do automatic cache management +
  • ccache can cache compiler output that includes warnings. In many + cases this gives ccache a much higher cache hit rate. +
  • ccache can handle a much wider ranger of compiler options +
  • ccache avoids a double call to cpp on a cache miss +
+

+

17.16 CREDITS

+ + +

+Thanks to the following people for their contributions to ccache +

    +
  • Erik Thiele for the original compilercache script +
  • Luciano Rocha for the idea of compiling the pre-processor output + to avoid a 2nd cpp pass +
  • Paul Russell for many suggestions and the debian packaging +
+

+

17.17 AUTHOR

+ + +

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

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

+ + + + diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index b7e1d638c..bfac7aa5b 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -1,12 +1,13 @@ - + SWIG and C++11 + -

7 SWIG and C++11

+

7 SWIG and C++11

@@ -61,7 +62,7 @@ -

7.1 Introduction

+

7.1 Introduction

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.

-

7.2 Core language changes

+

7.2 Core language changes

-

7.2.1 Rvalue reference and move semantics

+

7.2.1 Rvalue reference and move semantics

@@ -121,7 +122,7 @@ example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid ide

-

7.2.2 Generalized constant expressions

+

7.2.2 Generalized constant expressions

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.

-

7.2.3 Extern template

+

7.2.3 Extern template

SWIG correctly parses the keywords extern template. @@ -151,7 +152,7 @@ extern template class std::vector<int>; // C++11 explicit instantiation su %template(VectorInt) std::vector<int>; // SWIG instantiation -

7.2.4 Initializer lists

+

7.2.4 Initializer lists

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

-

7.2.5 Uniform initialization

+

7.2.5 Uniform initialization

The curly brackets {} for member initialization are fully @@ -316,7 +317,7 @@ AltStruct var2{2, 4.3}; // calls the constructor 142.15 -

7.2.6 Type inference

+

7.2.6 Type inference

SWIG supports decltype() with some limitations. Single @@ -333,13 +334,13 @@ int i; int j; decltype(i+j) k; // syntax error -

7.2.7 Range-based for-loop

+

7.2.7 Range-based for-loop

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

-

7.2.8 Lambda functions and expressions

+

7.2.8 Lambda functions and expressions

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

@@ -365,7 +366,7 @@ auto six = [](int x, int y) { return x+y; }(4, 2); Better support should be available in a later release.

-

7.2.9 Alternate function syntax

+

7.2.9 Alternate function syntax

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

@@ -400,7 +401,7 @@ auto SomeStruct::FuncName(int x, int y) -> int { auto square(float a, float b) -> decltype(a); -

7.2.10 Object construction improvement

+

7.2.10 Object construction improvement

@@ -456,14 +457,14 @@ This kind of initialization is handled by SWIG.

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

7.2.11 Explicit overrides and final

+

7.2.11 Explicit overrides and final

@@ -487,12 +488,12 @@ struct DerivedStruct : BaseStruct { -

7.2.12 Null pointer constant

+

7.2.12 Null pointer constant

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

-

7.2.13 Strongly typed enumerations

+

7.2.13 Strongly typed enumerations

SWIG supports strongly typed enumerations and parses the new enum class syntax and forward declarator for the enums, such as:

@@ -548,7 +549,7 @@ The equivalent in Java is: System.out.println(Color.RainbowColors.Red.swigValue() + " " + Color.WarmColors.Red.swigValue() + " " + Color.PrimeColors.Red.swigValue()); -

7.2.14 Double angle brackets

+

7.2.14 Double angle brackets

SWIG correctly parses the symbols >> as closing the @@ -559,7 +560,7 @@ shift operator >> otherwise.

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

7.2.15 Explicit conversion operators

+

7.2.15 Explicit conversion operators

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.

-

7.2.16 Alias templates

+

7.2.16 Type alias and alias templates

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

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

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

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

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

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

+SWIG supports both type aliasing and alias templates. +However, in order to use an alias template, two %template directives must be used: +

+ +
+%template(SomeTypeBool) SomeType<char*, bool, 5>;
+%template() TypedefName<bool>;
+
+ +

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

7.2.17 Unrestricted unions

SWIG fully supports any type inside a union even if it does not @@ -682,7 +678,7 @@ union P { } p1; -

7.2.18 Variadic templates

+

7.2.18 Variadic templates

SWIG supports the variadic templates syntax (inside the <> @@ -692,7 +688,7 @@ initializers) with some limitations. The following code is correctly parsed:

 template <typename... BaseClasses> class ClassName : public BaseClasses... {
 public:
-   ClassName (BaseClasses &&... baseClasses) : BaseClasses(baseClasses)... {}
+  ClassName (BaseClasses &&... baseClasses) : BaseClasses(baseClasses)... {}
 }
 
@@ -717,7 +713,7 @@ const int SIZE = sizeof...(ClassName<int, int>); In the above example SIZE is of course wrapped as a constant.

-

7.2.19 New string literals

+

7.2.19 New string literals

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

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

-

7.2.20 User-defined literals

+

7.2.20 User-defined literals

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

7.2.21 Thread-local storage

+

7.2.21 Thread-local storage

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

+

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

 struct NoInt {
-    void f(double i);
-    void f(int) = delete;
+  void f(double i);
+  void f(int) = delete;
 };
 
@@ -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.

-

7.2.23 Type long long int

+

7.2.23 Type long long int

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

-

7.2.24 Static assertions

+

7.2.24 Static assertions

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

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

+

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

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

7.2.26 Exception specifications and noexcept

+

7.2.26 Exception specifications and noexcept

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

7.2.27 Control and query object alignment

+

7.2.27 Control and query object alignment

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

7.2.28 Attributes

+

7.2.28 Attributes

@@ -974,10 +970,10 @@ int [[attr1]] i [[attr2, attr3]]; [[noreturn, nothrow]] void f [[noreturn]] (); -

7.3 Standard library changes

+

7.3 Standard library changes

-

7.3.1 Threading facilities

+

7.3.1 Threading facilities

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.

-

7.3.2 Tuple types

+

7.3.2 Tuple types

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

-

7.3.3 Hash tables

+

7.3.3 Hash tables

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

-

7.3.4 Regular expressions

+

7.3.4 Regular expressions

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

-

7.3.5 General-purpose smart pointers

+

7.3.5 General-purpose smart pointers

@@ -1017,12 +1013,12 @@ Please see the shared_ptr smart po There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr yet.

-

7.3.6 Extensible random number facility

+

7.3.6 Extensible random number facility

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

-

7.3.7 Wrapper reference

+

7.3.7 Wrapper reference

@@ -1033,7 +1029,7 @@ Users would need to write their own typemaps if wrapper references are being use

-

7.3.8 Polymorphous wrappers for function objects

+

7.3.8 Polymorphic wrappers for function objects

@@ -1064,7 +1060,7 @@ t = Test() b = t(1,2) # invoke C++ function object -

7.3.9 Type traits for metaprogramming

+

7.3.9 Type traits for metaprogramming

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

@@ -1114,7 +1110,7 @@ Then the appropriate algorithm can be called for the subset of types given by th 2 -

7.3.10 Uniform method for computing return type of function objects

+

7.3.10 Uniform method for computing return type of function objects

diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 18fc3037e..19ffb66d6 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -1,11 +1,12 @@ - + SWIG and C# + -

20 SWIG and C#

+

20 SWIG and C#

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

    20.1 Introduction

    +

    20.1 Introduction

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

    -

    20.1.1 SWIG 2 Compatibility

    +

    20.1.1 SWIG 2 Compatibility

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

    -

    20.1.2 Additional command line options

    +

    20.1.2 Additional command line options

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

    -

    20.2 Differences to the Java module

    +

    20.2 Differences to the Java module

    @@ -232,6 +233,7 @@ javabody -> csbody javafinalize -> csfinalize javadestruct -> csdestruct javadestruct_derived -> csdestruct_derived +javainterfacecode -> csinterfacecode

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

20.3 Void pointers

+

20.3 Void pointers

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

20.4 C# Arrays

+

20.4 C# Arrays

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

-

20.4.1 The SWIG C arrays library

+

20.4.1 The SWIG C arrays library

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

20.4.2 Managed arrays using P/Invoke default array marshalling

+

20.4.2 Managed arrays using P/Invoke default array marshalling

@@ -740,7 +749,7 @@ and intermediary class method -

20.4.3 Managed arrays using pinning

+

20.4.3 Managed arrays using pinning

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

20.5 C# Exceptions

+

20.5 C# Exceptions

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

-

20.5.1 C# exception example using "check" typemap

+

20.5.1 C# exception example using "check" typemap

@@ -1016,18 +1025,18 @@ Now let's analyse the generated code to gain a fuller understanding of the typem

 SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
-    int arg1 ;
-    
-    arg1 = (int)jarg1; 
-    
-    if (arg1 < 0) {
-        SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
-                                               "only positive numbers accepted", "number");
-        return ;
-    }
-    
-    positivesonly(arg1);
-    
+  int arg1 ;
+
+  arg1 = (int)jarg1;
+
+  if (arg1 < 0) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
+      "only positive numbers accepted", "number");
+    return ;
+  }
+
+  positivesonly(arg1);
+
 }
 
@@ -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.

-

20.5.2 C# exception example using %exception

+

20.5.2 C# exception example using %exception

@@ -1150,18 +1159,17 @@ The generated unmanaged code this time catches the C++ exception and converts it

 SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
-    int arg1 ;
-    
-    arg1 = (int)jarg1; 
-    
-    try {
-        negativesonly(arg1);
-        
-    } catch (std::out_of_range e) {
-        SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
-        return ;
-    }
-    
+  int arg1 ;
+
+  arg1 = (int)jarg1;
+
+  try {
+    negativesonly(arg1);
+
+  } catch (std::out_of_range e) {
+    SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
+    return ;
+  }
 }
 
@@ -1180,7 +1188,7 @@ The managed code generated does check for the pending exception as mentioned ear -

20.5.3 C# exception example using exception specifications

+

20.5.3 C# exception example using exception specifications

@@ -1216,19 +1224,18 @@ SWIG generates a try catch block with the throws typemap code in the catch handl

 SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
-    int arg1 ;
-    
-    arg1 = (int)jarg1; 
-    try {
-        evensonly(arg1);
+  int arg1 ;
+
+  arg1 = (int)jarg1;
+  try {
+    evensonly(arg1);
+  }
+  catch(std::out_of_range &_e) {
+    {
+      SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&_e)->what(), NULL);
+      return ;
     }
-    catch(std::out_of_range &_e) {
-      {
-          SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&_e)->what(), NULL);
-          return ;
-      }
-    }
-    
+  }
 }
 
@@ -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.

-

20.5.4 Custom C# ApplicationException example

+

20.5.4 Custom C# ApplicationException example

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

20.6 C# Directors

+

20.6 C# Directors

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

-

20.6.1 Directors example

+

20.6.1 Directors example

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

20.6.2 Directors implementation

+

20.6.2 Directors implementation

@@ -1638,20 +1645,20 @@ SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg, class SwigDirector_Base : public Base, public Swig::Director { public: - SwigDirector_Base(); - virtual unsigned int UIntMethod(unsigned int x); - virtual ~SwigDirector_Base(); - virtual void BaseBoolMethod(Base const &b, bool flag); + SwigDirector_Base(); + virtual unsigned int UIntMethod(unsigned int x); + virtual ~SwigDirector_Base(); + virtual void BaseBoolMethod(Base const &b, bool flag); - typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int); - typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int); - void swig_connect_director(SWIG_Callback0_t callbackUIntMethod, - SWIG_Callback1_t callbackBaseBoolMethod); + typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int); + typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int); + void swig_connect_director(SWIG_Callback0_t callbackUIntMethod, + SWIG_Callback1_t callbackBaseBoolMethod); private: - SWIG_Callback0_t swig_callbackUIntMethod; - SWIG_Callback1_t swig_callbackBaseBoolMethod; - void swig_init_callbacks(); + SWIG_Callback0_t swig_callbackUIntMethod; + SWIG_Callback1_t swig_callbackBaseBoolMethod; + void swig_init_callbacks(); }; void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod, @@ -1688,7 +1695,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) { -

20.6.3 Director caveats

+

20.6.3 Director caveats

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

-

20.7 Multiple modules

+

20.7 Multiple modules

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

-

20.8 C# Typemap examples

+

20.8 C# Typemap examples

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

+

20.8.1 Memory management when returning references to member variables

@@ -1903,7 +1910,7 @@ public class Bike : global::System.IDisposable { Note the addReference call.

-

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

+

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

@@ -1935,10 +1942,10 @@ and usage from C++

-    Container container;
-    Element element(20);
-    container.setElement(&element);
-    cout << "element.value: " << container.getElement()->value << endl;
+  Container container;
+  Element element(20);
+  container.setElement(&element);
+  cout << "element.value: " << container.getElement()->value << endl;
 
@@ -2022,7 +2029,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class. -

20.8.3 Date marshalling using the csin typemap and associated attributes

+

20.8.3 Date marshalling using the csin typemap and associated attributes

@@ -2308,7 +2315,7 @@ public class example { -

20.8.4 A date example demonstrating marshalling of C# properties

+

20.8.4 A date example demonstrating marshalling of C# properties

@@ -2408,7 +2415,7 @@ Some points to note:

  • The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and these are all ignored in the property set. The code in these attributes must instead be replicated within the 'csvarin' typemap. The line creating the temp$csinput variable is such an example; it is identical to what is in the 'pre' attribute. -

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

    +

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

    @@ -2470,7 +2477,7 @@ Pay special attention to the memory management issues, using these attributes.

    -

    20.8.6 Turning wrapped classes into partial classes

    +

    20.8.6 Turning wrapped classes into partial classes

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

    +

    20.8.7 Extending proxy classes with additional C# code

    @@ -2609,7 +2616,7 @@ public class ExtendMe : global::System.IDisposable { -

    20.8.8 Underlying type for enums

    +

    20.8.8 Underlying type for enums

    diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html index 82861c31c..820d01fde 100644 --- a/Doc/Manual/Chicken.html +++ b/Doc/Manual/Chicken.html @@ -1,14 +1,14 @@ - - + SWIG and Chicken + -

    21 SWIG and Chicken

    +

    21 SWIG and Chicken

      @@ -55,10 +55,10 @@

        -
      1. generates portable C code
      2. -
      3. includes a customizable interpreter
      4. -
      5. links to C libraries with a simple Foreign Function Interface
      6. -
      7. supports full tail-recursion and first-class continuations
      8. +
      9. generates portable C code
      10. +
      11. includes a customizable interpreter
      12. +
      13. links to C libraries with a simple Foreign Function Interface
      14. +
      15. supports full tail-recursion and first-class continuations

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

      -

      21.1 Preliminaries

      +

      21.1 Preliminaries

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

      -

      21.1.1 Running SWIG in C mode

      +

      21.1.1 Running SWIG in C mode

      @@ -98,7 +98,7 @@

      -
      % swig -chicken example.i
      +
      % swig -chicken example.i

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

      -

      21.1.2 Running SWIG in C++ mode

      +

      21.1.2 Running SWIG in C++ mode

      @@ -131,7 +131,7 @@

      -
      % swig -chicken -c++ example.i
      +
      % swig -chicken -c++ example.i

      @@ -142,7 +142,7 @@

      -
      % chicken example.scm -output-file oexample.c
      +
      % chicken example.scm -output-file oexample.c

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

      -

      21.2 Code Generation

      +

      21.2 Code Generation

      -

      21.2.1 Naming Conventions

      +

      21.2.1 Naming Conventions

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

      -

      21.2.2 Modules

      +

      21.2.2 Modules

      The name of the module must be declared one of two ways:

        -
      • Placing %module example in the SWIG interface - file.
      • -
      • Using -module example on the SWIG command - line.
      • +
      • Placing %module example in the SWIG interface + file.
      • +
      • Using -module example on the SWIG command + line.

      @@ -189,10 +189,10 @@

      CHICKEN will be able to access the module using the (declare - (uses modulename)) CHICKEN Scheme form. + (uses modulename)) CHICKEN Scheme form.

      -

      21.2.3 Constants and Variables

      +

      21.2.3 Constants and Variables

      @@ -200,10 +200,10 @@ the interface file:

        -
      1. #define MYCONSTANT1 ...
      2. -
      3. %constant int MYCONSTANT2 = ...
      4. -
      5. const int MYCONSTANT3 = ...
      6. -
      7. enum { MYCONSTANT4 = ... };
      8. +
      9. #define MYCONSTANT1 ...
      10. +
      11. %constant int MYCONSTANT2 = ...
      12. +
      13. const int MYCONSTANT3 = ...
      14. +
      15. enum { MYCONSTANT4 = ... };

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

      -

      21.2.4 Functions

      +

      21.2.4 Functions

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

      -

      21.2.5 Exceptions

      +

      21.2.5 Exceptions

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

    -

    21.3 TinyCLOS

    +

    21.3 TinyCLOS

    The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: - "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a - metaobject protocol. The implementation is even simpler than - the simple CLOS found in `The Art of the Metaobject Protocol,' - weighing in at around 850 lines of code, including (some) - comments and documentation." + "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a + metaobject protocol. The implementation is even simpler than + the simple CLOS found in `The Art of the Metaobject Protocol,' + weighing in at around 850 lines of code, including (some) + comments and documentation."

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

    -

    21.4 Linkage

    +

    21.4 Linkage

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

    -

    21.4.1 Static binary or shared library linked at compile time

    +

    21.4.1 Static binary or shared library linked at compile time

    We can easily use csc to build a static binary.

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

    -

    21.4.2 Building chicken extension libraries

    +

    21.4.2 Building chicken extension libraries

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

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

    -

    21.4.3 Linking multiple SWIG modules with TinyCLOS

    +

    21.4.3 Linking multiple SWIG modules with TinyCLOS

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

    -

    21.5 Typemaps

    +

    21.5 Typemaps

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

    Lib/chicken/chicken.swg.

    -

    21.6 Pointers

    +

    21.6 Pointers

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

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

    -

    21.6.1 Garbage collection

    +

    21.6.1 Garbage collection

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

    must be called manually.

    -

    21.7 Unsupported features and known problems

    +

    21.7 Unsupported features and known problems

    -

    21.7.1 TinyCLOS problems with Chicken version <= 1.92

    +

    21.7.1 TinyCLOS problems with Chicken version <= 1.92

    In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 839c0ec42..74d21960e 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -1,10 +1,12 @@ - + SWIG Users Manual + +

    SWIG Users Manual

    @@ -142,8 +144,8 @@

  • Basic Type Handling
  • Global Variables
  • Constants -
  • A brief word about const -
  • A cautionary tale of char * +
  • A brief word about const +
  • A cautionary tale of char *
  • Pointers and complex objects @@ -441,6 +443,8 @@
  • $descriptor(type)
  • $typemap(method, typepattern) +
  • Special variables and typemap attributes +
  • Special variables combined with special variable macros
  • Common typemap methods
  • Typemaps and overloading -
  • More about %apply and %clear +
  • More about %apply and %clear
  • Passing data between typemaps
  • C++ "this" pointer
  • Where to go for more information? @@ -819,13 +824,13 @@
  • Code injection typemaps
  • Special variable macros -
  • %features +
  • D and %feature
  • Pragmas
  • D Exceptions
  • D Directors
  • Other features
  • Further details on the generated Java classes +
  • Interfaces
  • Cross language polymorphism using directors
      @@ -1070,7 +1090,7 @@
  • Embedded Webkit
  • Creating Applications with node-webkit @@ -1273,10 +1293,10 @@
  • Overriding Methods in Ocaml
  • Director Usage Example
  • Creating director objects -
  • Typemaps for directors, directorin, directorout, directorargout -
  • directorin typemap -
  • directorout typemap -
  • directorargout typemap +
  • Typemaps for directors, directorin, directorout, directorargout +
  • typemap +
  • directorout typemap +
  • directorargout typemap
  • Exceptions @@ -1310,6 +1330,10 @@
  • Class extension with %extend
  • C++ templates
  • C++ Smart Pointers +
  • Directors (calling Octave from C++ code)
  • Threads
  • Memory management @@ -1415,7 +1439,7 @@
  • Pointers and References
  • Structures and C++ classes
  • Further details on the Python class interface @@ -1502,7 +1530,7 @@
  • Built-in Types
  • Memory management
  • Python 2.2 and classic classes @@ -1567,6 +1595,14 @@
  • Absolute and relative imports
  • Enforcing absolute import semantics
  • Importing from __init__.py +
  • Implicit Namespace Packages +
  • Searching for the wrapper module +
  • Python 3 Support @@ -1631,6 +1668,10 @@
  • C++ STL Functors
  • C++ STL Iterators
  • C++ Smart Pointers +
  • Cross-Language Polymorphism
    • Exception Unrolling @@ -1761,11 +1802,12 @@
    • Pointers
    • Structures
    • C++ classes
    • C++ inheritance +
    • C++ overloading
    • Pointers, references, values, and arrays
    • C++ templates
    • C++ operators @@ -1776,7 +1818,6 @@
    • Type mappings and libraries
      • Default primitive type mappings -
      • Default type mappings for non-primitive types
      • Arrays
      • Pointer-to-pointers
      • Matrices diff --git a/Doc/Manual/Contract.html b/Doc/Manual/Contract.html index 35bc874ef..c9bcd6f38 100644 --- a/Doc/Manual/Contract.html +++ b/Doc/Manual/Contract.html @@ -1,12 +1,13 @@ - + Contract Checking + -

        13 Contracts

        +

        13 Contracts

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

          -

          13.1 The %contract directive

          +

          13.1 The %contract directive

          @@ -50,9 +51,9 @@ is a simple example:

           %contract sqrt(double x) {
           require:
          -    x >= 0;
          +  x >= 0;
           ensure:
          -    sqrt >= 0;
          +  sqrt >= 0;
           }
           
           ...
          @@ -94,7 +95,7 @@ RuntimeError: Contract violation: require: (arg1>=0)
           
        -

        13.2 %contract and classes

        +

        13.2 %contract and classes

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

        -

        13.3 Constant aggregation and %aggregate_check

        +

        13.3 Constant aggregation and %aggregate_check

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

        -

        13.4 Notes

        +

        13.4 Notes

        diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index 8e26a7e8a..014b1a3c2 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -1,12 +1,13 @@ - + Customization Features + -

        12 Customization Features

        +

        12 Customization Features

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

          -

          12.1 Exception handling with %exception

          +

          12.1 Exception handling with %exception

          @@ -55,12 +56,12 @@ handler. For example, you can specify the following:

           %exception {
          -    try {
          -        $action
          -    }
          -    catch (RangeError) {
          -        ... handle error ...
          -    }
          +  try {
          +    $action
          +  }
          +  catch (RangeError) {
          +    ... handle error ...
          +  }
           }
           
          @@ -70,13 +71,13 @@ How the exception is handled depends on the target language, for example, Python
           %exception {
          -    try {
          -        $action
          -    }
          -    catch (RangeError) {
          -        PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
          -        SWIG_fail;
          -    }
          +  try {
          +    $action
          +  }
          +  catch (RangeError) {
          +    PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
          +    SWIG_fail;
          +  }
           }
           
          @@ -100,7 +101,7 @@ for exception handling. That directive is deprecated--%exception provides the same functionality, but is substantially more flexible.

          -

          12.1.1 Handling exceptions in C code

          +

          12.1.1 Handling exceptions in C code

          @@ -115,16 +116,18 @@ static char error_message[256]; static int error_status = 0; void throw_exception(char *msg) { - strncpy(error_message,msg,256); - error_status = 1; + strncpy(error_message,msg,256); + error_status = 1; } void clear_exception() { - error_status = 0; + error_status = 0; } char *check_exception() { - if (error_status) return error_message; - else return NULL; + if (error_status) + return error_message; + else + return NULL; }

        @@ -136,13 +139,13 @@ To use these functions, functions simply call
         double inv(double x) {
        -	if (x != 0) return 1.0/x;
        -	else {
        -		throw_exception("Division by zero");
        -		return 0;
        -	}
        +  if (x != 0)
        +    return 1.0/x;
        +  else {
        +    throw_exception("Division by zero");
        +    return 0;
        +  }
         }
        -
         

        @@ -151,12 +154,12 @@ as the following (shown for Perl5) :

         %exception {
        -    char *err;
        -    clear_exception();
        -    $action
        -    if ((err = check_exception())) {
        -       croak(err);
        -    }
        +  char *err;
        +  clear_exception();
        +  $action
        +  if ((err = check_exception())) {
        +    croak(err);
        +  }
         }
         
        @@ -166,7 +169,7 @@ Each target language has its own approach to creating a runtime error/exception and for Perl it is the croak method shown above.

        -

        12.1.2 Exception handling with longjmp()

        +

        12.1.2 Exception handling with longjmp()

        @@ -206,8 +209,10 @@ Now, within a C program, you can do the following :

         double inv(double x) {
        -	if (x) return 1.0/x;
        -	else throw(DivisionByZero);
        +  if (x)
        +    return 1.0/x;
        +  else
        +    throw(DivisionByZero);
         }
         
         
        @@ -221,17 +226,17 @@ Finally, to create a SWIG exception handler, write the following :

        %} %exception { - try { - $action - } catch(RangeError) { - croak("Range Error"); - } catch(DivisionByZero) { - croak("Division by zero"); - } catch(OutOfMemory) { - croak("Out of memory"); - } finally { - croak("Unknown exception"); - } + try { + $action + } catch(RangeError) { + croak("Range Error"); + } catch(DivisionByZero) { + croak("Division by zero"); + } catch(OutOfMemory) { + croak("Out of memory"); + } finally { + croak("Unknown exception"); + } } @@ -240,7 +245,7 @@ Note: This implementation is only intended to illustrate the general idea. To m modify it to handle nested try declarations.

        -

        12.1.3 Handling C++ exceptions

        +

        12.1.3 Handling C++ exceptions

        @@ -249,17 +254,17 @@ Handling C++ exceptions is also straightforward. For example:

         %exception {
        -	try {
        -		$action
        -	} catch(RangeError) {
        -		croak("Range Error");
        -	} catch(DivisionByZero) {
        -		croak("Division by zero");
        -	} catch(OutOfMemory) {
        -		croak("Out of memory");
        -	} catch(...) {
        -		croak("Unknown exception");
        -	}
        +  try {
        +    $action
        +  } catch(RangeError) {
        +    croak("Range Error");
        +  } catch(DivisionByZero) {
        +    croak("Division by zero");
        +  } catch(OutOfMemory) {
        +    croak("Out of memory");
        +  } catch(...) {
        +    croak("Unknown exception");
        +  }
         }
         
         
        @@ -275,7 +280,7 @@ class OutOfMemory {}; -

        12.1.4 Exception handlers for variables

        +

        12.1.4 Exception handlers for variables

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

        12.1.5 Defining different exception handlers

        +

        12.1.5 Defining different exception handlers

        @@ -319,7 +324,7 @@ critical pieces of code. For example:

         %exception {
        -	... your exception handler ...
        +  ... your exception handler ...
         }
         /* Define critical operations that can throw exceptions here */
         
        @@ -336,12 +341,12 @@ to specific declaration name. For example:
         
         %exception allocate {
        -    try {
        -        $action
        -    } 
        -    catch (MemoryError) {
        -        croak("Out of memory");
        -    }
        +  try {
        +    $action
        +  }
        +  catch (MemoryError) {
        +    croak("Out of memory");
        +  }
         }
         
        @@ -359,12 +364,12 @@ an exception handler for a specific class, you might write this:
         %exception Object::allocate {
        -    try {
        -        $action
        -    } 
        -    catch (MemoryError) {
        -        croak("Out of memory");
        -    }
        +  try {
        +    $action
        +  }
        +  catch (MemoryError) {
        +    croak("Out of memory");
        +  }
         }
         
        @@ -381,12 +386,12 @@ in the specified class as well as for identically named functions appearing in d
         %exception Object::allocate(int) {
        -    try {
        -        $action
        -    } 
        -    catch (MemoryError) {
        -        croak("Out of memory");
        -    }
        +  try {
        +    $action
        +  }
        +  catch (MemoryError) {
        +    croak("Out of memory");
        +  }
         }
         
        @@ -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.

        -

        12.1.6 Special variables for %exception

        +

        12.1.6 Special variables for %exception

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

        -

        12.1.7 Using The SWIG exception library

        +

        12.1.7 Using The SWIG exception library

        @@ -555,17 +560,17 @@ common scripting language exceptions in a portable manner. For example :

        %include exception.i %exception { - try { - $action - } catch(RangeError) { - SWIG_exception(SWIG_ValueError, "Range Error"); - } catch(DivisionByZero) { - SWIG_exception(SWIG_DivisionByZero, "Division by zero"); - } catch(OutOfMemory) { - SWIG_exception(SWIG_MemoryError, "Out of memory"); - } catch(...) { - SWIG_exception(SWIG_RuntimeError,"Unknown exception"); - } + try { + $action + } catch(RangeError) { + SWIG_exception(SWIG_ValueError, "Range Error"); + } catch(DivisionByZero) { + SWIG_exception(SWIG_DivisionByZero, "Division by zero"); + } catch(OutOfMemory) { + SWIG_exception(SWIG_MemoryError, "Out of memory"); + } catch(...) { + SWIG_exception(SWIG_RuntimeError,"Unknown exception"); + } } @@ -595,7 +600,7 @@ SWIG_NullReferenceError The SWIG_exception() function can also be used in typemaps.

        -

        12.2 Object ownership and %newobject

        +

        12.2 Object ownership and %newobject

        @@ -606,8 +611,8 @@ example, consider a function like this:

         Foo *blah() {
        -   Foo *f = new Foo();
        -   return f;
        +  Foo *f = new Foo();
        +  return f;
         }
         
        @@ -752,7 +757,7 @@ char *strdup(const char *s); The results might not be what you expect.

        -

        12.3 Features and the %feature directive

        +

        12.3 Features and the %feature directive

        @@ -766,12 +771,12 @@ using the %feature directive. For example:

         %feature("except") Object::allocate {
        -    try {
        -        $action
        -    } 
        -    catch (MemoryError) {
        -        croak("Out of memory");
        -    }
        +  try {
        +    $action
        +  }
        +  catch (MemoryError) {
        +    croak("Out of memory");
        +  }
         }
         
         %feature("new","1") *::copy;
        @@ -806,10 +811,10 @@ are defined.  For example:
         
         /* 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.
         

        -

        12.3.1 Feature attributes

        +

        12.3.1 Feature attributes

        @@ -862,11 +867,11 @@ In the following example, MyExceptionClass is the name of the Java clas

         %feature("except", throws="MyExceptionClass") Object::method { 
        -   try {
        -     $action
        -   } catch (...) {
        -     ... code to throw a MyExceptionClass Java exception ...
        -   }
        +  try {
        +    $action
        +  } catch (...) {
        +    ... code to throw a MyExceptionClass Java exception ...
        +  }
         };
         
        @@ -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.

        -

        12.3.2 Feature flags

        +

        12.3.2 Feature flags

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

        -

        12.3.3 Clearing features

        +

        12.3.3 Clearing features

        @@ -988,21 +993,21 @@ To clarify, let's consider the except feature again (%exception // Define global exception handler %feature("except") { - try { - $action - } catch (...) { - croak("Unknown C++ exception"); - } + try { + $action + } catch (...) { + croak("Unknown C++ exception"); + } } // Define exception handler for all clone methods to log the method calls %feature("except") *::clone() { - try { - logger.info("$action"); - $action - } catch (...) { - croak("Unknown C++ exception"); - } + try { + logger.info("$action"); + $action + } catch (...) { + croak("Unknown C++ exception"); + } } ... initial set of class declarations with clone methods ... @@ -1066,7 +1071,7 @@ The three macros below show this for the "except" feature:

        -

        12.3.4 Features and default arguments

        +

        12.3.4 Features and default arguments

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

        -

        12.3.5 Feature example

        +

        12.3.5 Feature example

        @@ -1160,14 +1165,14 @@ in the Python module. You might use %feature to rewrite proxy/shadow cl %feature("shadow") Foo::bar(int) %{ def bar(*args): if len(args) == 3: - return apply(examplec.Foo_bar_id,args) + return apply(examplec.Foo_bar_id,args) return apply(examplec.Foo_bar,args) %} class Foo { public: - int bar(int x); - int bar(int x, double y); + int bar(int x); + int bar(int x, double y); } diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html index 47dab50f1..318a9586f 100644 --- a/Doc/Manual/D.html +++ b/Doc/Manual/D.html @@ -1,4 +1,4 @@ - + SWIG and D @@ -6,7 +6,7 @@ -

        22 SWIG and D

        +

        22 SWIG and D

      • %features +
      • D and %feature
      • Pragmas
      • D Exceptions
      • D Directors
      • Other features
          -
        • Extended namespace support (nspace) +
        • Extended namespace support (nspace)
        • Native pointer support
        • Operator overloading
        • Running the test-suite @@ -41,7 +41,7 @@ -

          22.1 Introduction

          +

          22.1 Introduction

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

          @@ -50,10 +50,10 @@

          While these issues can be worked around relatively easy by hand-coding a thin wrapper layer around the C library in question, there is another issue where writing wrapper code per hand is not feasible: C++ libraries. D did not support interfacing to C++ in version 1 at all, and even if extern(C++) has been added to D2, the support is still very limited, and a custom wrapper layer is still required in many cases.

          -

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

          +

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

          -

          22.2 Command line invocation

          +

          22.2 Command line invocation

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

          @@ -64,7 +64,7 @@

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

          -
          -splitproxy
          +
          -splitproxy

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

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

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

          22.3 Typemaps

          +

          22.3 Typemaps

          -

          22.3.1 C# <-> D name comparison

          +

          22.3.1 C# <-> D name comparison

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

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

          22.3.2 ctype, imtype, dtype

          +

          22.3.2 ctype, imtype, dtype

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

          @@ -120,26 +120,26 @@

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

          -

          22.3.3 in, out, directorin, directorout

          +

          22.3.3 in, out, directorin, directorout

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

          -

          The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).

          +

          The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).

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

          -

          22.3.4 din, dout, ddirectorin, ddirectorout

          +

          22.3.4 din, dout, ddirectorin, ddirectorout

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

          -

          The din typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).

          +

          The din typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).

          -

          The dout typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).

          +

          The dout typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).

          -

          The code from the ddirectorin and ddirectorout typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).

          +

          The code from the ddirectorin and ddirectorout typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).

          The full chain of type conversions when a director callback is invoked looks like this:

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

          22.3.5 typecheck typemaps

          +

          22.3.5 typecheck typemaps

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

          -

          22.3.6 Code injection typemaps

          +

          22.3.6 Code injection typemaps

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

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

          -

          22.3.7 Special variable macros

          +

          22.3.7 Special variable macros

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

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

          For example, this input

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

          These variables are used in dout typemaps. $imcall contains the call to the intermediary module which provides the value to be used, and $owner signals if the caller is responsible for managing the object lifetime (that is, if the called method is a constructor or has been marked via %newobject).

          Consider the following example:

          @@ -229,8 +229,9 @@ void foo(SomeClass arg) { %newobject bar(); SomeClass *bar(); -%} -

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

          +%} + +

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

           SomeClass foo() {
             return new SomeClass(example_im.foo(), false);
          @@ -243,7 +244,7 @@ SomeClass bar() {
             
          $dcall and $winput (C#: $cscall, $iminput)
          -

          These variables are used in the director-specific typemaps ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be passed back to C++, $winput contains the parameter value from C++.

          +

          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.

          Consider the following code snippet:

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

          22.4 %features

          +

          22.4 D and %feature

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

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

          22.5 Pragmas

          +

          22.5 Pragmas

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

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

          22.6 D Exceptions

          +

          22.6 D Exceptions

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

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

          -

          22.7 D Directors

          +

          22.7 D Directors

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

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

          -

          22.8 Other features

          +

          22.8 Other features

          -

          22.8.1 Extended namespace support (nspace)

          +

          22.8.1 Extended namespace support (nspace)

          By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace feature is supported for D. If it is active, C++ namespaces are mapped to D packages/modules. Note, however, that like for the other languages, free variables and functions are not supported yet; currently, they are all allows written to the main proxy D module.

          -

          22.8.2 Native pointer support

          +

          22.8.2 Native pointer support

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

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

          -

          22.8.3 Operator overloading

          +

          22.8.3 Operator overloading

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

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

          -

          22.8.4 Running the test-suite

          +

          22.8.4 Running the test-suite

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

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

          -

          22.9 D Typemap examples

          +

          22.9 D Typemap examples

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

          -

          22.10 Work in progress and planned features

          +

          22.10 Work in progress and planned features

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

          diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index 59c63403d..798a1adb9 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -1,12 +1,13 @@ - + Extending SWIG to support new languages + -

          41 Extending SWIG to support new languages

          +

          41 Extending SWIG to support new languages

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

            41.1 Introduction

            +

            41.1 Introduction

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

            -

            41.2 Prerequisites

            +

            41.2 Prerequisites

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

            -

            41.3 The Big Picture

            +

            41.3 The Big Picture

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

            -

            41.4 Execution Model

            +

            41.4 Execution Model

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

            -

            41.4.1 Preprocessing

            +

            41.4.1 Preprocessing

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

            -

            41.4.2 Parsing

            +

            41.4.2 Parsing

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

            -

            41.4.3 Parse Trees

            +

            41.4.3 Parse Trees

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

          -

          41.4.4 Attribute namespaces

          +

          41.4.4 Attribute namespaces

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

          -

          41.4.5 Symbol Tables

          +

          41.4.5 Symbol Tables

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

          41.4.6 The %feature directive

          +

          41.4.6 The %feature directive

          @@ -771,8 +772,8 @@ low-level %feature directive. For example: ... class Foo { public: - Object *getitem(int index) throws(badindex); - ... + Object *getitem(int index) throws(badindex); + ... }; @@ -806,7 +807,7 @@ For example, the exception code above is simply stored without any modifications.

          -

          41.4.7 Code Generation

          +

          41.4.7 Code Generation

          @@ -825,7 +826,7 @@ transformed. For example, suppose you are wrapping a class like this:

           class Foo {
           public:
          -    virtual int *bar(int x);
          +  virtual int *bar(int x);
           };
           
          @@ -928,7 +929,7 @@ public : The role of these functions is described shortly.

          -

          41.4.8 SWIG and XML

          +

          41.4.8 SWIG and XML

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

          -

          41.5 Primitive Data Structures

          +

          41.5 Primitive Data Structures

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

          41.5.1 Strings

          +

          41.5.1 Strings

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

          41.5.2 Hashes

          +

          41.5.2 Hashes

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

          41.5.3 Lists

          +

          41.5.3 Lists

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

          41.5.4 Common operations

          +

          41.5.4 Common operations

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

          41.5.5 Iterating over Lists and Hashes

          +

          41.5.5 Iterating over Lists and Hashes

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

          41.5.6 I/O

          +

          41.5.6 I/O

          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.

          -

          41.6 Navigating and manipulating parse trees

          +

          41.6 Navigating and manipulating parse trees

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

          41.7 Working with attributes

          +

          41.7 Working with attributes

          @@ -1673,10 +1674,10 @@ Since parse tree nodes are just hash tables, attributes are accessed using the <

           int functionHandler(Node *n) {
          -    String *name    = Getattr(n,"name");
          -    String *symname = Getattr(n,"sym:name");
          -    SwigType *type  = Getattr(n,"type");
          -    ...
          +  String *name    = Getattr(n,"name");
          +  String *symname = Getattr(n,"sym:name");
          +  SwigType *type  = Getattr(n,"type");
          +  ...
           }
           
          @@ -1702,8 +1703,8 @@ A quick way to check the value of an attribute is to use the checkAttribute(
           if (checkAttribute(n,"storage","virtual")) {
          -   /* n is virtual */
          -   ...
          +  /* n is virtual */
          +  ...
           }
           
          @@ -1749,17 +1750,17 @@ Calls can be nested if necessary. Here is an example that shows how the functio
           int variableHandler(Node *n) {
          -    Swig_save("variableHandler",n,"type","sym:name",NIL);
          -    String *symname = Getattr(n,"sym:name");
          -    SwigType *type  = Getattr(n,"type");
          -    ...
          -    Append(symname,"_global");         // Change symbol name
          -    SwigType_add_pointer(type);        // Add pointer
          -    ...
          -    generate wrappers
          -    ...
          -    Swig_restore(n);                  // Restore original values
          -    return SWIG_OK;
          +  Swig_save("variableHandler",n,"type","sym:name",NIL);
          +  String *symname = Getattr(n,"sym:name");
          +  SwigType *type  = Getattr(n,"type");
          +  ...
          +  Append(symname,"_global");         // Change symbol name
          +  SwigType_add_pointer(type);        // Add pointer
          +  ...
          +  generate wrappers
          +  ...
          +  Swig_restore(n);                  // Restore original values
          +  return SWIG_OK;
           }
           
          @@ -1779,7 +1780,7 @@ the attribute is optional. Swig_restore() must always be called after function. -

          41.8 Type system

          +

          41.8 Type system

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

          -

          41.8.1 String encoding of types

          +

          41.8.1 String encoding of types

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

          -

          41.8.2 Type construction

          +

          41.8.2 Type construction

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

          41.8.3 Type tests

          +

          41.8.3 Type tests

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

          41.8.4 Typedef and inheritance

          +

          41.8.4 Typedef and inheritance

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

          41.8.5 Lvalues

          +

          41.8.5 Lvalues

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

          41.8.6 Output functions

          +

          41.8.6 Output functions

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

          41.9 Parameters

          +

          41.9 Parameters

          @@ -2374,10 +2375,10 @@ code like this: Parm *parms; Parm *p; for (p = parms; p; p = nextSibling(p)) { - SwigType *type = Getattr(p,"type"); - String *name = Getattr(p,"name"); - String *value = Getattr(p,"value"); - ... + SwigType *type = Getattr(p,"type"); + String *name = Getattr(p,"name"); + String *value = Getattr(p,"value"); + ... } @@ -2445,7 +2446,7 @@ included. Used to emit prototypes. Returns the number of required (non-optional) arguments in p. -

          41.10 Writing a Language Module

          +

          41.10 Writing a Language Module

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

          -

          41.10.1 Execution model

          +

          41.10.1 Execution model

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

          -

          41.10.2 Starting out

          +

          41.10.2 Starting out

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

          -

          41.10.3 Command line options

          +

          41.10.3 Command line options

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

          -

          41.10.4 Configuration and preprocessing

          +

          41.10.4 Configuration and preprocessing

          @@ -2649,19 +2650,19 @@ insert some code like this:

           void main(int argc, char *argv[]) {
          -   ... command line options ...
          +  ... command line options ...
           
          -   /* Set language-specific subdirectory in SWIG library */
          -   SWIG_library_directory("python");
          +  /* Set language-specific subdirectory in SWIG library */
          +  SWIG_library_directory("python");
           
          -   /* Set language-specific preprocessing symbol */
          -   Preprocessor_define("SWIGPYTHON 1", 0);
          +  /* Set language-specific preprocessing symbol */
          +  Preprocessor_define("SWIGPYTHON 1", 0);
           
          -   /* Set language-specific configuration file */
          -   SWIG_config_file("python.swg");
          +  /* Set language-specific configuration file */
          +  SWIG_config_file("python.swg");
           
          -   /* Set typemap language (historical) */
          -   SWIG_typemap_lang("python");
          +  /* Set typemap language (historical) */
          +  SWIG_typemap_lang("python");
           }
           
          @@ -2686,7 +2687,7 @@ an implementation file python.cxx and a configuration file python.swg.

          -

          41.10.5 Entry point to code generation

          +

          41.10.5 Entry point to code generation

          @@ -2720,31 +2721,31 @@ An outline of top() might be as follows:

           int Python::top(Node *n) {
           
          -   /* Get the module name */
          -   String *module = Getattr(n,"name");
          +  /* Get the module name */
          +  String *module = Getattr(n,"name");
           
          -   /* Get the output file name */
          -   String *outfile = Getattr(n,"outfile");
          +  /* Get the output file name */
          +  String *outfile = Getattr(n,"outfile");
           
          -   /* Initialize I/O (see next section) */
          -   ...
          +  /* Initialize I/O (see next section) */
          +  ...
           
          -   /* Output module initialization code */
          -   ...
          +  /* Output module initialization code */
          +  ...
           
          -   /* Emit code for children */
          -   Language::top(n);
          +  /* Emit code for children */
          +  Language::top(n);
           
          -   ...
          -   /* Cleanup files */
          -   ...
          +  ...
          +  /* Cleanup files */
          +  ...
           
          -   return SWIG_OK;
          +  return SWIG_OK;
           }
           
          -

          41.10.6 Module I/O and wrapper skeleton

          +

          41.10.6 Module I/O and wrapper skeleton

          @@ -2776,62 +2777,62 @@ such as:
           class PYTHON : public Language {
           protected:
          -   /* General DOH objects used for holding the strings */
          -   File *f_begin;
          -   File *f_runtime;
          -   File *f_header;
          -   File *f_wrappers;
          -   File *f_init;
          +  /* General DOH objects used for holding the strings */
          +  File *f_begin;
          +  File *f_runtime;
          +  File *f_header;
          +  File *f_wrappers;
          +  File *f_init;
           
           public:
          -   ...
          +  ...
           
           };
           
           int Python::top(Node *n) {
           
          -   ...
          +  ...
           
          -   /* Initialize I/O */
          -   f_begin = NewFile(outfile, "w", SWIG_output_files());
          -   if (!f_begin) {
          -      FileErrorDisplay(outfile);
          -      SWIG_exit(EXIT_FAILURE);
          -   }
          -   f_runtime = NewString("");
          -   f_init = NewString("");
          -   f_header = NewString("");
          -   f_wrappers = NewString("");
          +  /* Initialize I/O */
          +  f_begin = NewFile(outfile, "w", SWIG_output_files());
          +  if (!f_begin) {
          +    FileErrorDisplay(outfile);
          +    SWIG_exit(EXIT_FAILURE);
          +  }
          +  f_runtime = NewString("");
          +  f_init = NewString("");
          +  f_header = NewString("");
          +  f_wrappers = NewString("");
           
          -   /* Register file targets with the SWIG file handler */
          -   Swig_register_filebyname("begin", f_begin);
          -   Swig_register_filebyname("header", f_header);
          -   Swig_register_filebyname("wrapper", f_wrappers);
          -   Swig_register_filebyname("runtime", f_runtime);
          -   Swig_register_filebyname("init", f_init);
          +  /* Register file targets with the SWIG file handler */
          +  Swig_register_filebyname("begin", f_begin);
          +  Swig_register_filebyname("header", f_header);
          +  Swig_register_filebyname("wrapper", f_wrappers);
          +  Swig_register_filebyname("runtime", f_runtime);
          +  Swig_register_filebyname("init", f_init);
           
          -   /* Output module initialization code */
          -   Swig_banner(f_begin);
          -   ...
          +  /* Output module initialization code */
          +  Swig_banner(f_begin);
          +  ...
           
          -   /* Emit code for children */
          -   Language::top(n);
          +  /* Emit code for children */
          +  Language::top(n);
           
          -   ...
          -   /* Write all to the file */
          -   Dump(f_runtime, f_begin);
          -   Dump(f_header, f_begin);
          -   Dump(f_wrappers, f_begin);
          -   Wrapper_pretty_print(f_init, f_begin);
          +  ...
          +  /* Write all to the file */
          +  Dump(f_runtime, f_begin);
          +  Dump(f_header, f_begin);
          +  Dump(f_wrappers, f_begin);
          +  Wrapper_pretty_print(f_init, f_begin);
           
          -   /* Cleanup files */
          -   Delete(f_runtime);
          -   Delete(f_header);
          -   Delete(f_wrappers);
          -   Delete(f_init);
          -   Delete(f_begin);
          +  /* Cleanup files */
          +  Delete(f_runtime);
          +  Delete(f_header);
          +  Delete(f_wrappers);
          +  Delete(f_init);
          +  Delete(f_begin);
           
          -   return SWIG_OK;
          +  return SWIG_OK;
           }
           
          @@ -2892,7 +2893,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -

          41.10.7 Low-level code generators

          +

          41.10.7 Low-level code generators

          @@ -3046,7 +3047,7 @@ but without the typemaps, there is still work to do.

          -

          41.10.8 Configuration files

          +

          41.10.8 Configuration files

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

          41.10.9 Runtime support

          +

          41.10.9 Runtime support

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

          -

          41.10.10 Standard library files

          +

          41.10.10 Standard library files

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

          -

          41.10.11 User examples

          +

          41.10.11 User examples

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

          -

          41.10.12 Test driven development and the test-suite

          +

          41.10.12 Test driven development and the test-suite

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

          -

          41.10.12.1 Running the test-suite

          +

          41.10.12.1 Running the test-suite

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

          -

          41.10.13 Documentation

          +

          41.10.13 Documentation

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

        -

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

        +

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

        @@ -3587,7 +3588,7 @@ should be added should there be an area not already covered by the existing tests.

        -

        41.10.15 Coding style guidelines

        +

        41.10.15 Coding style guidelines

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

        -

        41.11 Debugging Options

        +

        41.11 Debugging Options

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

        -

        41.12 Guide to parse tree nodes

        +

        41.12 Guide to parse tree nodes

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

        41.13 Further Development Information

        +

        41.13 Further Development Information

        diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 20e923d19..f25e9850b 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -1,11 +1,12 @@ - + SWIG and Go + -

        23 SWIG and Go

        +

        23 SWIG and Go

          @@ -13,8 +14,8 @@
        • Examples
        • Running SWIG with Go
        • A tour of basic C/C++ wrapping
            @@ -29,6 +30,16 @@
        • Go Templates
        • Go Director Classes +
        • Default Go primitive type mappings
        • Output arguments
        • Adding additional go code @@ -46,55 +57,131 @@ the Go programming language see golang.org.

          -

          23.1 Overview

          +

          23.1 Overview

          -Go is a compiled language, not a scripting language. However, it does -not support direct calling of functions written in C/C++. The cgo -program may be used to generate wrappers to call C code from Go, but -there is no convenient way to call C++ code. SWIG fills this gap. +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.

          -

          23.2 Examples

          +

          23.2 Examples

          -Working examples can be found here: +Working examples can be found in the +SWIG source tree +.

          - +

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

          -

          23.3 Running SWIG with Go

          +

          23.3 Running SWIG with Go

          -To generate Go code, use the -go option with SWIG. By -default SWIG will generate code for the gc compilers. To generate -code for gccgo, you should also use the -gccgo option. +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
          +
          + + +

          23.3.1 Go-specific Commandline Options

          @@ -106,9 +193,9 @@ also be seen by using: swig -go -help

        - +
        - + @@ -134,7 +221,7 @@ swig -go -help + the Go compiler of the Go distribution. @@ -146,8 +233,8 @@ swig -go -help + 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 + 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. @@ -176,16 +263,17 @@ swig -go -help
        Go specific optionsGo-specific options
        -gccgo Generate code for gccgo. The default is to generate code for - the gc compiler.
        -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.
        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.
        -

        23.3.2 Go Output Files

        + +

        23.3.2 Generated Wrapper Files

        -

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

        23.4 A tour of basic C/C++ wrapping

        +

        23.4 A tour of basic C/C++ wrapping

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

        -

        23.4.1 Go Package Name

        +

        23.4.1 Go Package Name

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

        -

        23.4.2 Go Names

        +

        23.4.2 Go Names

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

        -

        23.4.3 Go Constants

        +

        23.4.3 Go Constants

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

        23.4.4 Go Enumerations

        +

        23.4.4 Go Enumerations

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

        -

        23.4.5 Go Classes

        +

        23.4.5 Go Classes

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

        -

        23.4.5.1 Go Class Memory Management

        +

        23.4.5.1 Go Class Memory Management

        @@ -453,10 +477,10 @@ objects and fits nicely C++'s RAII idiom. Example:

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

        23.4.5.2 Go Class Inheritance

        +

        23.4.5.2 Go Class Inheritance

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

        -

        23.4.6 Go Templates

        +

        23.4.6 Go Templates

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

        23.4.7 Go Director Classes

        + +

        23.4.7 Go Director Classes

        -SWIG's director feature permits a Go type to act as the subclass of a -C++ class with virtual methods. This is complicated by the fact that -C++ and Go define inheritance differently. In Go, structs can inherit -methods via anonymous field embedding. However, when a method is -called for an embedded struct, if that method calls any other methods, -they are called for the embedded struct, not for the original type. -Therefore, SWIG must use Go interfaces to represent C++ inheritance. +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. +

        + + +

        23.4.7.1 Example C++ code

        + + +

        +The step by step guide is based on two example C++ classes. FooBarAbstract is +an abstract C++ class and the FooBarCpp class inherits from it. This guide +explains how to implement a FooBarGo class similar to the FooBarCpp class.

        -For example: +FooBarAbstract abstract C++ class:

        -type GoClass struct { }
        -func (p *GoClass) VirtualFunction() { }
        -func MakeClass() ClassName {
        -	return NewDirectorClassName(&GoClass{})
        +class FooBarAbstract
        +{
        +public:
        +  FooBarAbstract() {};
        +  virtual ~FooBarAbstract() {};
        +
        +  std::string FooBar() {
        +          return this->Foo() + ", " + this->Bar();
        +  };
        +
        +protected:
        +  virtual std::string Foo() {
        +          return "Foo";
        +  };
        +
        +  virtual std::string Bar() = 0;
        +};
        +
        +
        + +

        +FooBarCpp C++ class: +

        + +
        +
        +class FooBarCpp : public FooBarAbstract
        +{
        +protected:
        +  virtual std::string Foo() {
        +    return "C++ " + FooBarAbstract::Foo();
        +  }
        +
        +  virtual std::string Bar() {
        +    return "C++ Bar";
        +  }
        +};
        +
        +
        + +

        +Returned string by the FooBarCpp::FooBar method is: +

        + +
        +
        +C++ Foo, C++ Bar
        +
        +
        + + +

        +The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. +

        + + +

        23.4.7.2 Enable director feature

        + + +

        +The director feature is disabled by default. To use directors you must make two +changes to the interface file. First, add the "directors" option to the %module +directive, like this: +

        + +
        +
        +%module(directors="1") modulename
        +
        +
        + +

        +Second, you must use the %feature("director") directive to tell SWIG which +classes should get directors. In the example the FooBarAbstract class needs the +director feature enabled so that the FooBarGo class can inherit from it, like +this: +

        + +
        +
        +%feature("director") FooBarAbstract;
        +
        +
        + +

        +For a more detailed documentation of the director feature and how to enable or +disable it for specific classes and virtual methods see SWIG's Java +documentation on directors. +

        + + +

        23.4.7.3 Constructor and destructor

        + + +

        +SWIG creates an additional set of constructor and destructor functions once the +director feature has been enabled for a C++ class. +NewDirectorClassName allows overriding virtual methods on the new +object instance and DeleteDirectorClassName needs to be used to free a +director object instance created with NewDirectorClassName. +More on overriding virtual methods follows later in this guide under +overriding virtual methods. +

        + +

        +The default constructor and destructor functions NewClassName and +DeleteClassName can still be used as before so that existing code +doesn't break just because the director feature has been enabled for a C++ +class. The behavior is undefined if the default and director constructor and +destructor functions get mixed and so great care needs to be taken that only one +of the constructor and destructor function pairs is used for any object +instance. Both constructor functions, the default and the director one, return +the same interface type. This makes it potentially hard to know which +destructor function, the default or the director one, needs to be called to +delete an object instance. +

        + +

        +In theory the DirectorInterface method could be used to +determine if an object instance was created via NewDirectorClassName: +

        + +
        +
        +if o.DirectorInterface() != nil {
        +  DeleteDirectorClassName(o)
        +} else {
        +  DeleteClassName(o)
         }
         

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

        -

        23.4.8 Default Go primitive type mappings

        + +

        23.4.7.4 Override virtual methods

        + + +

        +In order to override virtual methods on a C++ class with Go methods the +NewDirectorClassName constructor functions receives a +DirectorInterface argument. The methods in the +DirectorInterface are a subset of the public and protected virtual methods +of the C++ class. If the DirectorInterface contains a method with a +matching signature to a virtual method of the C++ class then the virtual C++ +method will be overwritten with the Go method. As Go doesn't support protected +methods all overriden protected virtual C++ methods will be public in Go. +

        + +

        +As an example see part of the FooBarGo class: +

        + +
        +
        +type overwrittenMethodsOnFooBarAbstract struct {
        +  fb FooBarAbstract
        +}
        +
        +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
        +  ...
        +}
        +
        +func (om *overwrittenMethodsOnFooBarAbstract) Bar() string {
        +  ...
        +}
        +
        +func NewFooBarGo() FooBarGo {
        +  om := &overwrittenMethodsOnFooBarAbstract{}
        +  fb := NewDirectorFooBarAbstract(om)
        +  om.fb = fb
        +  ...
        +}
        +
        +
        + +

        +The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. In +this part of the example the virtual methods FooBarAbstract::Foo and +FooBarAbstract::Bar have been overwritten with Go methods similarly to +how the FooBarAbstract virtual methods are overwritten by the +FooBarCpp class. +

        + +

        +The DirectorInterface in the example is implemented by the +overwrittenMethodsOnFooBarAbstract Go struct type. A pointer to a +overwrittenMethodsOnFooBarAbstract struct instance will be given to the +NewDirectorFooBarAbstract constructor function. The constructor return +value implements the FooBarAbstract interface. +overwrittenMethodsOnFooBarAbstract could in theory be any Go type but +in practice a struct is used as it typically contains at least a value of the +C++ class interface so that the overwritten methods can use the rest of the +C++ class. If the FooBarGo class would receive additional constructor +arguments then these would also typically be stored in the +overwrittenMethodsOnFooBarAbstract struct so that they can be used by +the Go methods. +

        + + +

        23.4.7.5 Call base methods

        + + +

        +Often a virtual method will be overwritten to extend the original behavior of +the method in the base class. This is also the case for the +FooBarCpp::Foo method of the example code: +

        + +
        +
        +virtual std::string Foo() {
        +  return "C++ " + FooBarAbstract::Foo();
        +}
        +
        +
        + +

        +To use base methods the DirectorClassNameMethodName wrapper functions +are automatically generated by SWIG for public and protected virtual methods. +The FooBarGo.Foo implementation in the example looks like this: +

        + +
        +
        +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
        +  return "Go " + DirectorFooBarAbstractFoo(om.fb)
        +}
        +
        +
        + +

        +The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. +

        + + +

        23.4.7.6 Subclass via embedding

        + + +

        +As previously mentioned in this guide the +default and director constructor functions return the same interface type. To +properly subclass a C++ class with a Go type the director object instance +returned by the NewDirectorClassName constructor function should be +embedded into a Go struct so that it represents a distinct but compatible type +in Go's type system. This Go struct should be private and the constructor and +destructor functions should instead work with a public interface type so that +the Go class that subclasses a C++ class can be used as a compatible drop in. +

        + +

        +The subclassing part of the FooBarGo class for an example looks like +this: +

        + +
        +
        +type FooBarGo interface {
        +  FooBarAbstract
        +  deleteFooBarAbstract()
        +  IsFooBarGo()
        +}
        +
        +type fooBarGo struct {
        +  FooBarAbstract
        +}
        +
        +func (fbgs *fooBarGo) deleteFooBarAbstract() {
        +  DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract)
        +}
        +
        +func (fbgs *fooBarGo) IsFooBarGo() {}
        +
        +func NewFooBarGo() FooBarGo {
        +  om := &overwrittenMethodsOnFooBarAbstract{}
        +  fb := NewDirectorFooBarAbstract(om)
        +  om.fb = fb
        +
        +  return &fooBarGo{FooBarAbstract: fb}
        +}
        +
        +func DeleteFooBarGo(fbg FooBarGo) {
        +  fbg.deleteFooBarAbstract()
        +}
        +
        +
        + + +

        +The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. In +this part of the example the private fooBarGo struct embeds +FooBarAbstract which lets the fooBarGo Go type "inherit" all the +methods of the FooBarAbstract C++ class by means of embedding. The +public FooBarGo interface type includes the FooBarAbstract +interface and hence FooBarGo can be used as a drop in replacement for +FooBarAbstract while the reverse isn't possible and would raise a +compile time error. Furthemore the constructor and destructor functions +NewFooBarGo and DeleteFooBarGo take care of all the director +specifics and to the user the class appears as any other SWIG wrapped C++ +class. +

        + + +

        23.4.7.7 Memory management with runtime.SetFinalizer

        + + +

        +In general all guidelines for C++ class memory +management apply as well to director classes. One often overlooked +limitation with runtime.SetFinalizer is that a finalizer doesn't run +in case of a cycle and director classes typically have a cycle. The cycle +in the FooBarGo class is here: +

        + +
        +
        +type overwrittenMethodsOnFooBarAbstract struct {
        +  fb FooBarAbstract
        +}
        +
        +func NewFooBarGo() FooBarGo {
        +  om := &overwrittenMethodsOnFooBarAbstract{}
        +  fb := NewDirectorFooBarAbstract(om) // fb.v = om
        +  om.fb = fb // Backlink causes cycle as fb.v = om!
        +  ...
        +}
        +
        +
        + +

        +In order to be able to use runtime.SetFinalizer nevertheless the +finalizer needs to be set on something that isn't in a cycle and that references +the director object instance. In the FooBarGo class example the +FooBarAbstract director instance can be automatically deleted by setting +the finalizer on fooBarGo: +

        + +
        +
        +type fooBarGo struct {
        +  FooBarAbstract
        +}
        +
        +type overwrittenMethodsOnFooBarAbstract struct {
        +  fb FooBarAbstract
        +}
        +
        +func NewFooBarGo() FooBarGo {
        +  om := &overwrittenMethodsOnFooBarAbstract{}
        +  fb := NewDirectorFooBarAbstract(om)
        +  om.fb = fb // Backlink causes cycle as fb.v = om!
        +
        +  fbgs := &fooBarGo{FooBarAbstract: fb}
        +  runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract)
        +  return fbgs
        +}
        +
        +
        + +

        +Furthermore if runtime.SetFinalizer is in use either the +DeleteClassName destructor function needs to be removed or the +fooBarGo struct needs additional data to prevent double deletion. Please +read the C++ class memory management subchapter +before using runtime.SetFinalizer to know all of its gotchas. +

        + + +

        23.4.7.8 Complete FooBarGo example class

        + + +

        +The complete and annotated FooBarGo class looks like this: +

        + +
        +
        +// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a
        +// drop in replacement for FooBarAbstract but the reverse causes a compile time
        +// error.
        +type FooBarGo interface {
        +  FooBarAbstract
        +  deleteFooBarAbstract()
        +  IsFooBarGo()
        +}
        +
        +// Via embedding fooBarGo "inherits" all methods of FooBarAbstract.
        +type fooBarGo struct {
        +  FooBarAbstract
        +}
        +
        +func (fbgs *fooBarGo) deleteFooBarAbstract() {
        +  DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract)
        +}
        +
        +// The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract.
        +// This is also how the class hierarchy gets represented by the SWIG generated
        +// wrapper code.  For an instance FooBarCpp has the IsFooBarAbstract and
        +// IsFooBarCpp methods.
        +func (fbgs *fooBarGo) IsFooBarGo() {}
        +
        +// Go type that defines the DirectorInterface. It contains the Foo and Bar
        +// methods that overwrite the respective virtual C++ methods on FooBarAbstract.
        +type overwrittenMethodsOnFooBarAbstract struct {
        +  // Backlink to FooBarAbstract so that the rest of the class can be used by
        +  // the overridden methods.
        +  fb FooBarAbstract
        +
        +  // If additional constructor arguments have been given they are typically
        +  // stored here so that the overriden methods can use them.
        +}
        +
        +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
        +  // DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo.
        +  return "Go " + DirectorFooBarAbstractFoo(om.fb)
        +}
        +
        +func (om *overwrittenMethodsOnFooBarAbstract) Bar() string {
        +  return "Go Bar"
        +}
        +
        +func NewFooBarGo() FooBarGo {
        +  // Instantiate FooBarAbstract with selected methods overridden.  The methods
        +  // that will be overwritten are defined on
        +  // overwrittenMethodsOnFooBarAbstract and have a compatible signature to the
        +  // respective virtual C++ methods. Furthermore additional constructor
        +  // arguments will be typically stored in the
        +  // overwrittenMethodsOnFooBarAbstract struct.
        +  om := &overwrittenMethodsOnFooBarAbstract{}
        +  fb := NewDirectorFooBarAbstract(om)
        +  om.fb = fb // Backlink causes cycle as fb.v = om!
        +
        +  fbgs := &fooBarGo{FooBarAbstract: fb}
        +  // The memory of the FooBarAbstract director object instance can be
        +  // automatically freed once the FooBarGo instance is garbage collected by
        +  // uncommenting the following line.  Please make sure to understand the
        +  // runtime.SetFinalizer specific gotchas before doing this.  Furthemore
        +  // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo
        +  // struct needs additional data to prevent double deletion.
        +  // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract)
        +  return fbgs
        +}
        +
        +// Recommended to be removed if runtime.SetFinalizer is in use.
        +func DeleteFooBarGo(fbg FooBarGo) {
        +  fbg.deleteFooBarAbstract()
        +}
        +
        +
        + +

        +Returned string by the FooBarGo.FooBar method is: +

        + +
        +
        +Go Foo, Go Bar
        +
        +
        + +

        +For comparison the FooBarCpp class looks like this: +

        + +
        +
        +class FooBarCpp : public FooBarAbstract
        +{
        +protected:
        +  virtual std::string Foo() {
        +    return "C++ " + FooBarAbstract::Foo();
        +  }
        +
        +  virtual std::string Bar() {
        +    return "C++ Bar";
        +  }
        +};
        +
        +
        + +

        +For comparison the returned string by the FooBarCpp::FooBar method is: +

        + +
        +
        +C++ Foo, C++ Bar
        +
        +
        + +

        +The complete source of this example can be found under + +SWIG/Examples/go/director/. +

        + + +

        23.4.8 Default Go primitive type mappings

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

        -

        23.4.9 Output arguments

        +

        23.4.9 Output arguments

        Because of limitations in the way output arguments are processed in swig, @@ -777,7 +1302,7 @@ void f(char *output); -

        23.4.10 Adding additional go code

        +

        23.4.10 Adding additional go code

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

        23.4.11 Go typemaps

        +

        23.4.11 Go typemaps

        diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 4c1126c7f..f30e139e5 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -1,14 +1,14 @@ - - + SWIG and Guile + -

        24 SWIG and Guile

        +

        24 SWIG and Guile

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

          This section details guile-specific support in SWIG. -

          24.1 Supported Guile Versions

          +

          24.1 Supported Guile Versions

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

          24.2 Meaning of "Module"

          +

          24.2 Meaning of "Module"

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

          24.3 Old GH Guile API

          +

          24.3 Old GH Guile API

          Guile 1.8 and older could be interfaced using two different api's, the SCM @@ -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. -

          24.4 Linkage

          +

          24.4 Linkage

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

          24.4.1 Simple Linkage

          +

          24.4.1 Simple Linkage

          @@ -158,8 +158,8 @@ following module-system hack:

           (module-map (lambda (sym var)
          -	      (module-export! (current-module) (list sym)))
          -	    (current-module))
          +              (module-export! (current-module) (list sym)))
          +            (current-module))
           
          @@ -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. -

          24.4.2 Passive Linkage

          +

          24.4.2 Passive Linkage

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

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

          24.4.3 Native Guile Module Linkage

          +

          24.4.3 Native Guile Module Linkage

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

      -

      24.4.4 Old Auto-Loading Guile Module Linkage

      +

      24.4.4 Old Auto-Loading Guile Module Linkage

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

      24.4.5 Hobbit4D Linkage

      +

      24.4.5 Hobbit4D Linkage

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

      -

      24.5 Underscore Folding

      +

      24.5 Underscore Folding

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

      24.6 Typemaps

      +

      24.6 Typemaps

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

      -

      24.7 Representation of pointers as smobs

      +

      24.7 Representation of pointers as smobs

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

      24.7.1 Smobs

      +

      24.7.1 Smobs

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

      -

      24.7.2 Garbage Collection

      +

      24.7.2 Garbage Collection

      Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8, @@ -453,7 +453,7 @@ is exactly like described in 24.8 Exception Handling +

      24.8 Exception Handling

      @@ -462,16 +462,16 @@ mapping:

      -      MAP(SWIG_MemoryError,	"swig-memory-error");
      -      MAP(SWIG_IOError,		"swig-io-error");
      -      MAP(SWIG_RuntimeError,	"swig-runtime-error");
      -      MAP(SWIG_IndexError,	"swig-index-error");
      -      MAP(SWIG_TypeError,	"swig-type-error");
      -      MAP(SWIG_DivisionByZero,	"swig-division-by-zero");
      -      MAP(SWIG_OverflowError,	"swig-overflow-error");
      -      MAP(SWIG_SyntaxError,	"swig-syntax-error");
      -      MAP(SWIG_ValueError,	"swig-value-error");
      -      MAP(SWIG_SystemError,	"swig-system-error");
      +      MAP(SWIG_MemoryError,     "swig-memory-error");
      +      MAP(SWIG_IOError,         "swig-io-error");
      +      MAP(SWIG_RuntimeError,    "swig-runtime-error");
      +      MAP(SWIG_IndexError,      "swig-index-error");
      +      MAP(SWIG_TypeError,       "swig-type-error");
      +      MAP(SWIG_DivisionByZero,  "swig-division-by-zero");
      +      MAP(SWIG_OverflowError,   "swig-overflow-error");
      +      MAP(SWIG_SyntaxError,     "swig-syntax-error");
      +      MAP(SWIG_ValueError,      "swig-value-error");
      +      MAP(SWIG_SystemError,     "swig-system-error");
       
      @@ -479,7 +479,7 @@ mapping: The default when not specified here is to use "swig-error". See Lib/exception.i for details. -

      24.9 Procedure documentation

      +

      24.9 Procedure documentation

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

      24.10 Procedures with setters

      +

      24.10 Procedures with setters

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

      24.11 GOOPS Proxy Classes

      +

      24.11 GOOPS Proxy Classes

      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.

      -

      24.11.1 Naming Issues

      +

      24.11.1 Naming Issues

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

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

      24.11.2 Linking

      +

      24.11.2 Linking

      The guile-modules generated above all need to be linked together. GOOPS support requires diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index 02a41169a..1c29f4760 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -1,12 +1,13 @@ - + Introduction + -

      2 Introduction

      +

      2 Introduction

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

        2.1 What is SWIG?

        +

        2.1 What is SWIG?

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

        2.2 Why use SWIG?

        +

        2.2 Why use SWIG?

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

        2.3 A SWIG example

        +

        2.3 A SWIG example

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

      2.3.1 SWIG interface file

      +

      2.3.1 SWIG interface file

      @@ -199,7 +202,7 @@ module that will be created by SWIG.  The %{ %} block
       provides a location for inserting additional code, such as C header
       files or additional C declarations, into the generated C wrapper code.
       
      -

      2.3.2 The swig command

      +

      2.3.2 The swig command

      @@ -221,8 +224,7 @@ unix > tclsh 7.5 %

      -

      - +

      The swig command produced a new file called example_wrap.c that should be compiled along with the example.c file. Most operating systems and scripting @@ -233,7 +235,7 @@ and variables declared in the SWIG interface. A look at the file example_wrap.c reveals a hideous mess. However, you almost never need to worry about it. -

      2.3.3 Building a Perl5 module

      +

      2.3.3 Building a Perl5 module

      @@ -244,8 +246,8 @@ any changes type the following (shown for Solaris):

       unix > swig -perl5 example.i
       unix > gcc -c example.c example_wrap.c \
      -	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
      -unix > ld -G example.o example_wrap.o -o example.so		# This is for Solaris
      +        -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
      +unix > ld -G example.o example_wrap.o -o example.so # This is for Solaris
       unix > perl5.003
       use example;
       print example::fact(4), "\n";
      @@ -259,7 +261,7 @@ unix >
       
      -

      2.3.4 Building a Python module

      +

      2.3.4 Building a Python module

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

      2.3.5 Shortcuts

      +

      2.3.5 Shortcuts

      @@ -296,7 +298,7 @@ SWIG on the C header file and specifying a module name as follows

       unix > swig -perl5 -module example example.h
       unix > gcc -c example.c example_wrap.c \
      -	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
      +        -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
       unix > ld -G example.o example_wrap.o -o example.so
       unix > perl5.003
       use example;
      @@ -309,7 +311,7 @@ print $example::My_variable + 4.5, "\n";
       7.5
       
      -

      2.4 Supported C/C++ language features

      +

      2.4 Supported C/C++ language features

      @@ -334,7 +336,7 @@ major features include:

    -Most of C++11 is also supported. Details are in the C++11 section. +Most of C++11 is also supported. Details are in the C++11 section.

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

    2.5 Non-intrusive interface building

    +

    2.5 Non-intrusive interface building

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

    -

    2.6 Incorporating SWIG into a build system

    +

    2.6 Incorporating SWIG into a build system

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

    -

    2.7 Hands off code generation

    +

    2.7 Hands off code generation

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

    -

    2.8 SWIG and freedom

    +

    2.8 SWIG and freedom

    diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 3a4f7ee5d..eb9d91450 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -1,11 +1,12 @@ - + SWIG and Java + -

    25 SWIG and Java

    +

    25 SWIG and Java

  • Further details on the generated Java classes +
  • Interfaces
  • Cross language polymorphism using directors
      @@ -157,7 +163,7 @@ It covers most SWIG features, but certain low-level details are covered in less

      -

      25.1 Overview

      +

      25.1 Overview

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

      -

      25.2 Preliminaries

      +

      25.2 Preliminaries

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

      -

      25.2.1 Running SWIG

      +

      25.2.1 Running SWIG

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

      -

      25.2.2 Additional Commandline Options

      +

      25.2.2 Additional Commandline Options

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

      -

      25.2.3 Getting the right header files

      +

      25.2.3 Getting the right header files

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

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

      -

      25.2.4 Compiling a dynamic module

      +

      25.2.4 Compiling a dynamic module

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

      -

      25.2.5 Using your module

      +

      25.2.5 Using your module

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

      -

      25.2.6 Dynamic linking problems

      +

      25.2.6 Dynamic linking problems

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

      +

      25.2.7 Compilation problems and compiling with C++

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

      -

      25.2.8 Building on Windows

      +

      25.2.8 Building on Windows

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

      -

      25.2.8.1 Running SWIG from Visual Studio

      +

      25.2.8.1 Running SWIG from Visual Studio

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

      -

      25.2.8.2 Using NMAKE

      +

      25.2.8.2 Using NMAKE

      @@ -627,11 +631,11 @@ CFLAGS = /Z7 /Od /c /nologo JAVA_INCLUDE = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32 java:: - swig -java -o $(WRAPFILE) $(INTERFACE) - $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) - set LIB=$(TOOLS)\lib - $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj - javac *.java + swig -java -o $(WRAPFILE) $(INTERFACE) + $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) + set LIB=$(TOOLS)\lib + $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj + javac *.java

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

      -

      25.3 A tour of basic C/C++ wrapping

      +

      25.3 A tour of basic C/C++ wrapping

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

      +

      25.3.1 Modules, packages and generated Java classes

      @@ -687,7 +691,7 @@ swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i SWIG won't create the directory, so make sure it exists beforehand.

      -

      25.3.2 Functions

      +

      25.3.2 Functions

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

      25.3.3 Global variables

      +

      25.3.3 Global variables

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

      25.3.4 Constants

      +

      25.3.4 Constants

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

      -

      25.3.5 Enumerations

      +

      25.3.5 Enumerations

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

      -

      25.3.5.1 Anonymous enums

      +

      25.3.5.1 Anonymous enums

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

      -

      25.3.5.2 Typesafe enums

      +

      25.3.5.2 Typesafe enums

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

      -

      25.3.5.3 Proper Java enums

      +

      25.3.5.3 Proper Java enums

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

      -

      25.3.5.4 Type unsafe enums

      +

      25.3.5.4 Type unsafe enums

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

      -

      25.3.5.5 Simple enums

      +

      25.3.5.5 Simple enums

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

      -

      25.3.6 Pointers

      +

      25.3.6 Pointers

      @@ -1305,16 +1309,16 @@ 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) { - return f+i; + return f+i; } %} @@ -1327,7 +1331,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return a NULL pointer if the conversion can't be performed.

      -

      25.3.7 Structures

      +

      25.3.7 Structures

      @@ -1337,7 +1341,7 @@ member variables. For example,

       struct Vector {
      -	double x,y,z;
      +  double x,y,z;
       };
       
       
      @@ -1373,12 +1377,12 @@ can also be forced to be read-only using the %immutable directive. For
       struct Foo {
      -   ...
      -   %immutable;
      -   int x;        /* Read-only members */
      -   char *name;
      -   %mutable;
      -   ...
      +  ...
      +  %immutable;
      +  int x;        /* Read-only members */
      +  char *name;
      +  %mutable;
      +  ...
       };
       
      @@ -1399,7 +1403,7 @@ example, consider this:
       struct Bar {
      -    int  x[16];
      +  int  x[16];
       };
       
      @@ -1448,11 +1452,11 @@ pointer. For example, suppose you have two structures like this:
       struct Foo {
      -   int a;
      +  int a;
       };
       
       struct Bar {
      -   Foo f;
      +  Foo f;
       };
       
      @@ -1495,7 +1499,7 @@ x.setA(3); // Modify x.a - this is the same as b.f.a -

      25.3.8 C++ classes

      +

      25.3.8 C++ classes

      @@ -1540,8 +1544,8 @@ Static class members are unsurprisingly wrapped as static members of the Java cl

       class Spam {
       public:
      -   static void foo();
      -   static int bar;
      +  static void foo();
      +  static int bar;
       };
       
      @@ -1558,7 +1562,7 @@ int bar = Spam.getBar(); -

      25.3.9 C++ inheritance

      +

      25.3.9 C++ inheritance

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

      +

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

      -

      25.3.10.1 Null pointers

      +

      25.3.10.1 Null pointers

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

      -

      25.3.11 C++ overloaded functions

      +

      25.3.11 C++ overloaded functions

      @@ -1734,9 +1738,9 @@ Similarly, if you have a class like this,

       class Foo {
       public:
      -    Foo();
      -    Foo(const Foo &);
      -    ...
      +  Foo();
      +  Foo(const Foo &);
      +  ...
       };
       
      @@ -1813,7 +1817,7 @@ void spam(unsigned short); // Ignored -

      25.3.12 C++ default arguments

      +

      25.3.12 C++ default arguments

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

      -

      25.3.13 C++ namespaces

      +

      25.3.13 C++ namespaces

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

      -

      25.3.14 C++ templates

      +

      25.3.14 C++ templates

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

      -

      25.3.15 C++ Smart Pointers

      +

      25.3.15 C++ Smart Pointers

      + + +

      25.3.15.1 The shared_ptr Smart Pointer

      + + +

      +The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Java in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +

      + + +

      25.3.15.2 Generic Smart Pointers

      @@ -2007,9 +2025,9 @@ that implements operator->() like this:

       template<class T> class SmartPtr {
      -   ...
      -   T *operator->();
      -   ...
      +  ...
      +  T *operator->();
      +  ...
       }
       
      @@ -2022,8 +2040,8 @@ Then, if you have a class like this,
       class Foo {
       public:
      -     int x;
      -     int bar();
      +  int x;
      +  int bar();
       };
       
      @@ -2079,7 +2097,7 @@ Foo f = p.__deref__(); // Returns underlying Foo * -

      25.4 Further details on the generated Java classes

      +

      25.4 Further details on the generated Java classes

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

      -

      25.4.1 The intermediary JNI class

      +

      25.4.1 The intermediary JNI class

      @@ -2107,8 +2125,8 @@ have a global function and class like this

       class Foo {
       public:
      -     int x;
      -     int spam(int num, Foo* foo);
      +  int x;
      +  int spam(int num, Foo* foo);
       };
       void egg(Foo* chips);
       
      @@ -2122,19 +2140,19 @@ These procedural wrappers essentially perform the equivalent of this C++ code:
       Foo *new_Foo() {
      -    return new Foo();
      +  return new Foo();
       }
       void delete_Foo(Foo *f) {
      -    delete f;
      +  delete f;
       }
       int Foo_x_get(Foo *f) {
      -    return f->x;
      +  return f->x;
       }
       void Foo_x_set(Foo *f, int value) {
      -    f->x = value;
      +  f->x = value;
       }
       int Foo_spam(Foo *f, int num, Foo* foo) {
      -    return f->spam(num, foo);
      +  return f->spam(num, foo);
       }
       
      @@ -2214,7 +2232,7 @@ If name is the same as modulename then the module class name g from modulename to modulenameModule.

      -

      25.4.1.1 The intermediary JNI class pragmas

      +

      25.4.1.1 The intermediary JNI class pragmas

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

      -

      25.4.2 The Java module class

      +

      25.4.2 The Java module class

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

      -

      25.4.2.1 The Java module class pragmas

      +

      25.4.2.1 The Java module class pragmas

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

      -

      25.4.3 Java proxy classes

      +

      25.4.3 Java proxy classes

      @@ -2390,8 +2408,8 @@ The default proxy class for our previous example looks like this:

       public class Foo {
      -  private long swigCPtr;
      -  protected boolean swigCMemOwn;
      +  private transient long swigCPtr;
      +  protected transient boolean swigCMemOwn;
       
         protected Foo(long cPtr, boolean cMemoryOwn) {
           swigCMemOwn = cMemoryOwn;
      @@ -2454,7 +2472,7 @@ int y = f.spam(5, new Foo());
       
      -

      25.4.3.1 Memory management

      +

      25.4.3.1 Memory management

      @@ -2476,10 +2494,10 @@ they came from. Therefore, the ownership is set to false. For example:

       class Foo {
       public:
      -    Foo();
      -    Foo bar1();
      -    Foo &bar2();
      -    Foo *bar2();
      +  Foo();
      +  Foo bar1();
      +  Foo &bar2();
      +  Foo *bar2();
       };
       
      @@ -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

      -

      25.4.3.2 Inheritance

      +

      25.4.3.2 Inheritance

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

      25.4.3.3 Proxy classes and garbage collection

      @@ -2815,7 +2833,7 @@ The section on Java typemaps details how to specify See the How to Handle Java Finalization's Memory-Retention Issues article for alternative approaches to managing memory by avoiding finalizers altogether.

      -

      25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

      +

      25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

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

      -

      25.4.3.5 Single threaded applications and thread safety

      +

      25.4.3.5 Single threaded applications and thread safety

      @@ -2960,8 +2978,8 @@ and the Java proxy class generated by SWIG:

       public class Test {
      -  private long swigCPtr;
      -  protected boolean swigCMemOwn;
      +  private transient long swigCPtr;
      +  protected transient boolean swigCMemOwn;
       
         protected Test(long cPtr, boolean cMemoryOwn) {
           swigCMemOwn = cMemoryOwn;
      @@ -3025,7 +3043,7 @@ for (int i=0; i<100000; i++) {
       
      -

      25.4.4 Type wrapper classes

      +

      25.4.4 Type wrapper classes

      @@ -3034,7 +3052,7 @@ The generated type wrapper class, for say an int *, looks like this:

       public class SWIGTYPE_p_int {
      -  private long swigCPtr;
      +  private transient long swigCPtr;
       
         protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
           swigCPtr = cPtr;
      @@ -3112,7 +3130,7 @@ public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
       
      -

      25.4.5 Enum classes

      +

      25.4.5 Enum classes

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

      -

      25.4.5.1 Typesafe enum classes

      +

      25.4.5.1 Typesafe enum classes

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

      -

      25.4.5.2 Proper Java enum classes

      +

      25.4.5.2 Proper Java enum classes

      @@ -3283,7 +3301,7 @@ These needn't be generated if the enum being wrapped does not have any initializ Simpler Java enums for enums without initializers section describes how typemaps can be used to achieve this.

      -

      25.4.5.3 Type unsafe enum classes

      +

      25.4.5.3 Type unsafe enum classes

      @@ -3314,7 +3332,252 @@ public final class Beverage {

      -

      25.5 Cross language polymorphism using directors

      +

      25.4.6 Interfaces

      + + +

      +By default SWIG wraps all C++ classes as Java classes. +As Java only supports derivation from a single base class, SWIG has to ignore all +bases except the first when a C++ class inherits from more than one base class. +However, there is a family of SWIG macros that change the default wrapping and allows a C++ class +to be wrapped as a Java interface instead of a Java class. +These macros provide a way to support some sort of multiple inheritance as there is no limit to +the number of interfaces that a Java class can inherit from. +

      + +

      +When a C++ class is wrapped as a Java interface, a Java proxy class is still needed. +The swiginterface.i library file provides three macros for marking a C++ class to be +wrapped as a Java interface. +There is more than one macro in order to provide a choice for choosing the Java interface and Java proxy names. +

      + + + + + + + + + + + + + + + + + + +
      Interface Macro NameDescription
      %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. +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Example UsageProxy Class NameInterface Class Name
      %interface(Base)BaseBaseSwigInterface
      %interface_impl(Base)BaseSwigImplBase
      %interface_custom("BaseProxy", "IBase", Base)BaseProxyIBase
      %interface_custom("%sProxy", "IBase", Base)BaseProxyIBase
      %interface_custom("%sProxy", "%sInterface", Base)BaseProxyBaseProxyInterface
      %interface_custom("%sProxy", "%(rstrip:[Proxy])sInterface", Base)BaseProxyBaseInterface
      + +

      +The 2nd last example shows the names used in the string formatting functions. +The input for PROXY that "%s" expands to is the proxy name, that is, Base. +The input for INTERFACE that "%s" expands to is the proxy name, that is, BaseProxy. +

      +

      +The last example shows rstrip and in this case strips the Proxy suffix and then adds on Interface. +

      + +

      +Consider the following C++ code: +

      + +
      +
      +namespace Space {
      +  struct Base1 {
      +    virtual void Method1();
      +  };
      +  struct Base2 {
      +    virtual void Method2();
      +  };
      +  struct Derived : Base1, Base2 {
      +  };
      +  void UseBases(const Base1 &b1, const Base2 &b2);
      +}
      +
      +
      + +

      +By default all classes are wrapped and are available in Java, but, Derived +has all bases ignored except the first. +SWIG generates a warning for the above code: +

      + +
      +
      +example.i:10: Warning 813: Warning for Derived, base Base2 ignored. 
      +Multiple inheritance is not supported in Java.
      +
      +
      + +

      +If we decide to wrap the two base classes as interfaces and add the following before SWIG parses the above example code: +

      + +
      +
      +%include <swiginterface.i>
      +%interface_impl(Space::Base1);
      +%interface_impl(Space::Base2);
      +
      +
      + +

      +then two interface files are generated, Base1.java and Base2.java in addition to proxy class files, Base1SwigImpl.java and Base2SwigImpl.java. +The contents of interface file Base1.java for Base1 is shown below: +

      + +
      +
      +public interface Base1 {
      +  long Base1_GetInterfaceCPtr();
      +  void Method1();
      +}
      +
      +
      + +

      +The proxy class in Base1SwigImpl.java for Base1 is as it would have been if %interface was not used, +except the name has changed to Base1SwigImpl and it implements the appropriate base: +

      + +
      +
      +public class Base1SwigImpl implements Base1 {
      +...
      +  public long Base1_GetInterfaceCPtr() {
      +    return exampleJNI.Base1SwigImpl_Base1_GetInterfaceCPtr(swigCPtr);
      +  }
      +
      +  public void Method1() {
      +    exampleJNI.Base1SwigImpl_Method1(swigCPtr, this);
      +  }
      +...
      +}
      +
      +
      + +

      +In fact any class deriving from Base will now implement the interface instead of +deriving from it (or ignoring the base in the case of multiple base classes). +Hence the Derived proxy class will now implement both bases: +

      + +
      +
      +public class Derived implements Base1, Base2 {
      +...
      +  public long Base1_GetInterfaceCPtr() {
      +    return exampleJNI.Derived_Base1_GetInterfaceCPtr(swigCPtr);
      +  }
      +
      +  public long Base2_GetInterfaceCPtr() {
      +    return exampleJNI.Derived_Base2_GetInterfaceCPtr(swigCPtr);
      +  }
      +
      +  public void Method1() {
      +    exampleJNI.Derived_Method1(swigCPtr, this);
      +  }
      +
      +  public void Method2() {
      +    exampleJNI.Derived_Method2(swigCPtr, this);
      +  }
      +...
      +}
      +
      +
      + +

      +Wherever a class marked as an interface is used, such as the UseBases method in the example, +the interface name is used as the type in the Java layer: +

      + +
      +
      +  public static void UseBases(Base1 b1, Base2 b2) {
      +    exampleJNI.UseBases(b1.Base1_GetInterfaceCPtr(), b1, b2.Base2_GetInterfaceCPtr(), b2);
      +  }
      +
      +
      + +

      +Note that each Java interface has a method added to obtain the correct C++ pointer for passing to the native function - +Base1_GetInterfaceCPtr for Base1. +This method is similar to the getCPtr method in the proxy classes. +In fact, as shown above in the Derived class, the proxy classes implement +this generated interface by calling a native method (Derived_Base1_GetInterfaceCPtr) +which calls an appropriate C++ cast of the pointer up the inheritance chain. +

      + +

      +The interface macros are implemented using the interface feature and typemaps. +For example: +

      + +
      +
      +%define %interface(CTYPE...)
      +%feature("interface", name="%sSwigInterface") CTYPE;
      +INTERFACE_TYPEMAPS(CTYPE)
      +%enddef
      +
      +
      + +

      +The feature accepts one attribute called name, which is the name of the Java interface mentioned earlier. +The INTERFACE_TYPEMAPS macro implements the typemaps and can be viewed in the +swiginterface.i file and contain +the usual Java typemaps for generating code plus the javainterfacecode +typemap which is only used when a class is marked with the interface feature. +See Java code typemaps for details. +

      + +

      25.5 Cross language polymorphism using directors

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

      -

      25.5.1 Enabling directors

      +

      25.5.1 Enabling directors

      @@ -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(); };

      -

      25.5.2 Director classes

      +

      25.5.2 Director classes

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

      -

      25.5.3 Overhead and code bloat

      +

      25.5.3 Overhead and code bloat

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

      -

      25.5.4 Simple directors example

      +

      25.5.4 Simple directors example

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

      25.5.5 Director threading issues

      +

      25.5.5 Director threading issues

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

      25.5.6 Director performance tuning

      +

      25.5.6 Director performance tuning

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

      -

      25.5.7 Java exceptions from directors

      +

      25.5.7 Java exceptions from directors

      @@ -3655,12 +3918,12 @@ is used in the feature code. Consider the following, which also happens to be th

       %feature("director:except") %{
      -   jthrowable $error = jenv->ExceptionOccurred();
      -   if ($error) {
      -     jenv->ExceptionClear();
      -     $directorthrowshandlers
      -     throw Swig::DirectorException(jenv, $error);
      -   }
      +  jthrowable $error = jenv->ExceptionOccurred();
      +  if ($error) {
      +    jenv->ExceptionClear();
      +    $directorthrowshandlers
      +    throw Swig::DirectorException(jenv, $error);
      +  }
       %}
       
      @@ -3722,12 +3985,12 @@ unexpected exceptions, the default handling can be changed with:
       %feature("director:except") %{
      -   jthrowable $error = jenv->ExceptionOccurred();
      -   if ($error) {
      -     jenv->ExceptionClear();
      -     $directorthrowshandlers
      -     return $null; // exception is ignored
      -   }
      +  jthrowable $error = jenv->ExceptionOccurred();
      +  if ($error) {
      +    jenv->ExceptionClear();
      +    $directorthrowshandlers
      +    return $null; // exception is ignored
      +  }
       %}
       
      @@ -3740,7 +4003,7 @@ the return $null; could be changed to:
      -   throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
      +  throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
       
      @@ -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.
        @@ -25,7 +26,7 @@
    • Embedded Webkit
    • Creating Applications with node-webkit @@ -51,7 +52,7 @@

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

      -

      26.1 Overview

      +

      26.1 Overview

      Javascript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. @@ -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.

      -

      26.2 Preliminaries

      +

      26.2 Preliminaries

      -

      26.2.1 Running SWIG

      +

      26.2.1 Running SWIG

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

      @@ -89,11 +90,22 @@ $ swig -javascript -jsc example.i $ swig -c++ -javascript -jsc example.i
    • The V8 code that SWIG generates should work with most versions from 3.11.10 up to 3.29.14 and later.

      -

      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:

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

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

      +
      +
      +$ swig -c++ -javascript -v8 example.i
      +

      This creates a C/C++ source file example_wrap.c or example_wrap.cxx. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module.

      The name of the wrapper file is derived from the name of the input file. For example, if the input file is example.i, the name of the wrapper file is example_wrap.c. To change this, you can use the -o option. The wrapped module will export one function which must be called to register the module with the Javascript interpreter. For example, if your module is named example the corresponding initializer for JavascriptCore would be

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

      -

      26.2.2 Running Tests and Examples

      +

      26.2.2 Running Tests and Examples

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

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

      26.2.3 Known Issues

      +

      26.2.3 Known Issues

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

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

    -

    26.3 Integration

    +

    26.3 Integration

    This chapter gives a short introduction how to use a native Javascript extension: as a node.js module, and as an extension for an embedded Webkit.

    -

    26.3.1 Creating node.js Extensions

    +

    26.3.1 Creating node.js Extensions

    -

    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.

     $ sudo add-apt-repository ppa:chris-lea/node.js
    @@ -209,7 +221,7 @@ require("./build/Release/example")

    A more detailed explanation is given in the Examples section.

    -

    26.3.1.1 Troubleshooting

    +

    26.3.1.1 Troubleshooting

      @@ -221,12 +233,12 @@ require("./build/Release/example") $ sudo apt-get remove gyp -

      26.3.2 Embedded Webkit

      +

      26.3.2 Embedded Webkit

      -

      Webkit is pre-installed on OSX and available as a library for GTK.

      +

      Webkit is pre-installed on Mac OS X and available as a library for GTK.

      -

      26.3.2.1 OSX

      +

      26.3.2.1 Mac OS X

      There is general information about programming with WebKit on Apple Developer Documentation. Details about Cocoa programming are not covered here.

      @@ -274,7 +286,7 @@ extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports) @end -

      26.3.2.2 GTK

      +

      26.3.2.2 GTK

      There is general information about programming GTK at GTK documentation and in the GTK tutorial, and for Webkit there is a Webkit GTK+ API Reference.

      @@ -288,38 +300,38 @@ extern bool example_initialize(JSGlobalContextRef context); int main(int argc, char* argv[]) { - // Initialize GTK+ - gtk_init(&argc, &argv); + // Initialize GTK+ + gtk_init(&argc, &argv); - ... + ... - // Create a browser instance - WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); - WebFrame *webframe = webkit_web_view_get_main_frame(webView); - JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame); - JSObjectRef global = JSContextGetGlobalObject(context); + // Create a browser instance + WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebFrame *webframe = webkit_web_view_get_main_frame(webView); + JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame); + JSObjectRef global = JSContextGetGlobalObject(context); - JSObjectRef exampleModule; - example_initialize(context, &exampleModule); - JSStringRef jsName = JSStringCreateWithUTF8CString("example"); - JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL); - JSStringRelease(jsName); + JSObjectRef exampleModule; + example_initialize(context, &exampleModule); + JSStringRef jsName = JSStringCreateWithUTF8CString("example"); + JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(jsName); - ... + ... - // Load a web page into the browser instance - webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/"); + // Load a web page into the browser instance + webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/"); - ... + ... - // Run the main GTK+ event loop - gtk_main(); + // Run the main GTK+ event loop + gtk_main(); - return 0; + return 0; } -

      26.3.3 Creating Applications with node-webkit

      +

      26.3.3 Creating Applications with node-webkit

      To get started with node-webkit there is a very informative set of wiki pages.

      @@ -348,7 +360,7 @@ It has some extras to configure node-webkit. See the
      @@ -368,7 +380,7 @@ The 'main' property of package.json specifies a web-pa
       the main window.

      - app.html: +app.html:

      @@ -395,7 +407,7 @@ open new windows, and many more things.

      - app.js: +app.js:

      @@ -410,12 +422,12 @@ open new windows, and many more things. };
      -

      26.4 Examples

      +

      26.4 Examples

      Some basic examples are shown here in more detail.

      -

      26.4.1 Simple

      +

      26.4.1 Simple

      The common example simple looks like this:

      @@ -465,7 +477,7 @@ example.Foo = 3.1415926;

      Note: ECMAScript 5, the currently implemented Javascript standard, does not have modules. node.js and other implementations provide this mechanism defined by the CommonJS group. For browsers this is provided by Browserify, for instance.

      -

      26.4.2 Class

      +

      26.4.2 Class

      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.

      -

      26.5 Implementation

      +

      26.5 Implementation

      The Javascript Module implementation has taken a very different approach compared to other language modules in order to support different Javascript interpreters.

      -

      26.5.1 Source Code

      +

      26.5.1 Source Code

      The Javascript module is implemented in Source/Modules/javascript.cxx. It dispatches the code generation to a JSEmitter instance, V8Emitter or JSCEmitter. Additionally there are some helpers: Template, for templated code generation, and JSEmitterState, which is used to manage state information during AST traversal. This rough map shall make it easier to find a way through this huge source file:

      @@ -701,7 +713,7 @@ Template::Template(const String *code_) { ... } ... -

      26.5.2 Code Templates

      +

      26.5.2 Code Templates

      All generated code is created on the basis of code templates. The templates for JavascriptCore can be found in Lib/javascript/jsc/javascriptcode.swg, for v8 in Lib/javascript/v8/javascriptcode.swg.

      @@ -740,7 +752,7 @@ t_register.replace("$jsparent", state.clazz(NAME_MANGLED))

      Template creates a copy of that string and Template::replace uses Swig's Replaceall to replace variables in the template. Template::trim can be used to eliminate leading and trailing whitespaces. Template::print is used to write the final template string to a Swig DOH (based on Printv). All methods allow chaining.

      -

      26.5.3 Emitter

      +

      26.5.3 Emitter

      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.

      -

      26.5.4 Emitter states

      +

      26.5.4 Emitter states

      For storing information during the AST traversal the emitter provides a JSEmitterState with different slots to store data representing the scopes global, class, function, and variable.

      @@ -903,7 +915,7 @@ state.clazz(NAME, Getattr(n, "sym:name"));

      State information can be retrieved using state.clazz(NAME) or with Getattr on state.clazz() which actually returns a Hash instance.

      -

      26.5.5 Handling Exceptions in JavascriptCore

      +

      26.5.5 Handling Exceptions in JavascriptCore

      Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.

      diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 069707559..a9c827add 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -1,12 +1,13 @@ - + SWIG Library + -

      9 SWIG library

      +

      9 SWIG library

        @@ -59,7 +60,7 @@ Alternative libraries provide similar functionality. Please read this chapter carefully if you used the old libraries.

        -

        9.1 The %include directive and library search path

        +

        9.1 The %include directive and library search path

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

        -

        9.2 C Arrays and Pointers

        +

        9.2 C Arrays and Pointers

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

        -

        9.2.1 cpointer.i

        +

        9.2.1 cpointer.i

        @@ -217,13 +218,13 @@ interface is as follows:

         struct name {
        -   name();                            // Create pointer object
        -  ~name();                            // Delete pointer object
        -   void assign(type value);           // Assign value
        -   type value();                      // Get value
        -   type *cast();                      // Cast the pointer to original type
        -   static name *frompointer(type *);  // Create class wrapper from existing
        -                                      // pointer
        +  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.

        -

        9.2.2 carrays.i

        +

        9.2.2 carrays.i

        @@ -383,10 +384,10 @@ function like this:

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

        -

        9.2.3 cmalloc.i

        +

        9.2.3 cmalloc.i

        @@ -658,7 +659,7 @@ Now, in a script:

      -

      9.2.4 cdata.i

      +

      9.2.4 cdata.i

      @@ -760,7 +761,7 @@ char *cdata_name(type* ptr, int nitems) Clearly they are unsafe.

      -

      9.3 C String Handling

      +

      9.3 C String Handling

      @@ -780,7 +781,7 @@ morality. The modules in this section provide basic functionality for manipulating raw C strings.

      -

      9.3.1 Default string handling

      +

      9.3.1 Default string handling

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

      -

      9.3.2 Passing binary data

      +

      9.3.2 Passing binary data

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

      -

      9.3.3 Using %newobject to release memory

      +

      9.3.3 Using %newobject to release memory

      @@ -873,9 +874,9 @@ If you have a function that allocates memory like this,

       char *foo() {
      -   char *result = (char *) malloc(...);
      -   ...
      -   return result;
      +  char *result = (char *) malloc(...);
      +  ...
      +  return result;
       }
       
      @@ -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.

      -

      9.3.4 cstring.i

      +

      9.3.4 cstring.i

      @@ -918,16 +919,16 @@ implementation:

       void get_path(char *s) {
      -    // Potential buffer overflow---uh, oh.
      -    sprintf(s,"%s/%s", base_directory, sub_directory);
      +  // Potential buffer overflow---uh, oh.
      +  sprintf(s,"%s/%s", base_directory, sub_directory);
       }
       ...
       // Somewhere else in the C program
       {
      -    char path[1024];
      -    ...
      -    get_path(path);
      -    ...
      +  char path[1024];
      +  ...
      +  get_path(path);
      +  ...
       }
       
      @@ -1235,8 +1236,8 @@ returned in a parameter of type char **. For example:
       void foo(char **s) {
      -    *s = (char *) malloc(64);
      -    sprintf(*s, "Hello world\n");
      +  *s = (char *) malloc(64);
      +  sprintf(*s, "Hello world\n");
       }
       
      @@ -1283,10 +1284,10 @@ returned in two parameters of type char ** and int *. For exa
       void foo(char **s, int *sz) {
      -    *s = (char *) malloc(64);
      -    *sz = 64;
      -    // Write some binary data
      -    ...
      +  *s = (char *) malloc(64);
      +  *sz = 64;
      +  // Write some binary data
      +  ...
       }
       
      @@ -1336,7 +1337,7 @@ You could wrap it with a function like this:
       void my_get_data(char **result, int *len) {
      -   *result = get_data(len);
      +  *result = get_data(len);
       }
       
      @@ -1364,7 +1365,7 @@ structure or class instead.
    -

    9.4 STL/C++ Library

    +

    9.4 STL/C++ Library

    @@ -1392,7 +1393,8 @@ The following table shows which C++ classes are supported and the equivalent SWI std::set set std_set.i std::string string std_string.i std::vector vector std_vector.i - std::shared_ptr shared_ptr std_shared_ptr.i + std::array array (C++11) std_array.i + std::shared_ptr shared_ptr (C++11) std_shared_ptr.i @@ -1402,7 +1404,7 @@ Please look for the library files in the appropriate language library directory.

    -

    9.4.1 std::string

    +

    9.4.1 std::string

    @@ -1486,7 +1488,7 @@ void foo(string s, const String &t); // std_string typemaps still applie -

    9.4.2 std::vector

    +

    9.4.2 std::vector

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

    -

    9.4.3 STL exceptions

    +

    9.4.3 STL exceptions

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

    -

    9.4.4 shared_ptr smart pointer

    +

    9.4.4 shared_ptr smart pointer

    @@ -1906,7 +1908,7 @@ Please help to improve this support by providing patches with improvements.

    -

    9.4.5 auto_ptr smart pointer

    +

    9.4.5 auto_ptr smart pointer

    @@ -1955,10 +1957,10 @@ int value = k.getValue(); -

    9.5 Utility Libraries

    +

    9.5 Utility Libraries

    -

    9.5.1 exception.i

    +

    9.5.1 exception.i

    @@ -2009,11 +2011,11 @@ For example:

     %include "exception.i"
     %exception std::vector::getitem {
    -    try {
    -        $action
    -    } catch (std::out_of_range& e) {
    -        SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what()));
    -    }
    +  try {
    +    $action
    +  } catch (std::out_of_range& e) {
    +    SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what()));
    +  }
     }
     
    diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index 0b8d47846..190e7bdfb 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -1,12 +1,13 @@ - + SWIG and Common Lisp + -

    27 SWIG and Common Lisp

    +

    27 SWIG and Common Lisp

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

      -

      27.1 Allegro Common Lisp

      +

      27.1 Allegro Common Lisp

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

      -

      27.2 Common Foreign Function Interface(CFFI)

      +

      27.2 Common Foreign Function Interface(CFFI)

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

      -

      27.2.1 Additional Commandline Options

      +

      27.2.1 Additional Commandline Options

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

      27.2.2 Generating CFFI bindings

      +

      27.2.2 Generating CFFI bindings

      As we mentioned earlier the ideal way to use SWIG is to use interface @@ -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)) -

    27.2.3 Generating CFFI bindings for C++ code

    +

    27.2.3 Generating CFFI bindings for C++ code

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

    27.2.4 Inserting user code into generated files

    +

    27.2.4 Inserting user code into generated files

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

    -

    27.3 CLISP

    +

    27.3 CLISP

    @@ -638,7 +638,7 @@ swig -clisp -module module-name file-name interface file for the CLISP module. The CLISP module tries to produce code which is both human readable and easily modifyable.

    -

    27.3.1 Additional Commandline Options

    +

    27.3.1 Additional Commandline Options

    @@ -658,33 +658,33 @@ swig -clisp -help -extern-all 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. -

    27.3.2 Details on CLISP bindings

    +

    27.3.2 Details on CLISP bindings

    As mentioned earlier the CLISP bindings generated by SWIG may need - some modifications. The clisp module creates a lisp file with - the same name as the module name. This - lisp file contains a 'defpackage' declaration, with the - package name same as the module name. This package uses the - 'common-lisp' and 'ffi' packages. Also, package exports all - the functions, structures and variables for which an ffi - binding was generated.
    - After generating the defpackage statement, the clisp module also - sets the default language. +some modifications. The clisp module creates a lisp file with +the same name as the module name. This +lisp file contains a 'defpackage' declaration, with the +package name same as the module name. This package uses the +'common-lisp' and 'ffi' packages. Also, package exports all +the functions, structures and variables for which an ffi +binding was generated.
    +After generating the defpackage statement, the clisp module also +sets the default language.

     (defpackage :test
    @@ -734,18 +734,18 @@ void test123(float x , double y);
     (ffi:def-call-out pointer_func
         (:name "pointer_func")
       (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL))
    -						      (arg1 (ffi:c-pointer NIL))
    -						      (arg2 (ffi:c-pointer NIL)))
    -					  (:return-type NIL)))
    -	      (y ffi:int))
    +                                                      (arg1 (ffi:c-pointer NIL))
    +                                                      (arg2 (ffi:c-pointer NIL)))
    +                                          (:return-type NIL)))
    +              (y ffi:int))
       (:return-type ffi:int)
       (:library +library-name+))
     
     (ffi:def-call-out func123
         (:name "func123")
       (:arguments (x (ffi:c-pointer div_t))
    -	      (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))
    -	      (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10))))))
    +              (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))
    +              (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10))))))
       (:return-type ffi:int)
       (:library +library-name+))
     
    @@ -753,14 +753,14 @@ void test123(float x , double y);
     (ffi:def-call-out lispsort_double
         (:name "lispsort_double")
       (:arguments (n ffi:int)
    -	      (array (ffi:c-ptr DOUBLE-FLOAT)))
    +              (array (ffi:c-ptr DOUBLE-FLOAT)))
       (:return-type NIL)
       (:library +library-name+))
     
     (ffi:def-call-out test123
         (:name "test")
       (:arguments (x SINGLE-FLOAT)
    -	      (y DOUBLE-FLOAT))
    +              (y DOUBLE-FLOAT))
       (:return-type NIL)
       (:library +library-name+))
     
    @@ -774,10 +774,10 @@ The module also handles strutcures and #define constants as shown
     

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

    27.4 UFFI

    +

    27.4 UFFI

    diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 2e1515c43..131d92825 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -1,12 +1,13 @@ - + SWIG and Lua + -

    28 SWIG and Lua

    +

    28 SWIG and Lua

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

      -

      28.1 Preliminaries

      +

      28.1 Preliminaries

      The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also has support for eLua starting from eLua 0.8. Due to substantial changes between SWIG 2.x and SWIG 3.0 and unavailability of testing platform, eLua status was downgraded to 'experimental'.

      -

      28.2 Running SWIG

      +

      28.2 Running SWIG

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

      -

      28.2.1 Additional command line options

      +

      28.2.1 Additional command line options

      @@ -178,7 +179,7 @@ swig -lua -help -

      28.2.2 Compiling and Linking and Interpreter

      +

      28.2.2 Compiling and Linking and Interpreter

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

      -

      28.2.3 Compiling a dynamic module

      +

      28.2.3 Compiling a dynamic module

      @@ -317,7 +318,7 @@ Is quite obvious (Go back and consult the Lua documents on how to enable loadlib -

      28.2.4 Using your module

      +

      28.2.4 Using your module

      @@ -335,19 +336,19 @@ $ ./my_lua >

    -

    28.3 A tour of basic C/C++ wrapping

    +

    28.3 A tour of basic C/C++ wrapping

    By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.

    -

    28.3.1 Modules

    +

    28.3.1 Modules

    The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.

    -

    28.3.2 Functions

    +

    28.3.2 Functions

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

    28.3.3 Global variables

    +

    28.3.3 Global variables

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

    -

    28.3.4 Constants and enums

    +

    28.3.4 Constants and enums

    @@ -511,7 +512,7 @@ If you're using eLua and have used -elua or -eluac to generate Hello World -

    28.3.4.1 Constants/enums and classes/structures

    +

    28.3.4.1 Constants/enums and classes/structures

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

    -

    28.3.5 Pointers

    +

    28.3.5 Pointers

    @@ -605,7 +606,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -

    28.3.6 Structures

    +

    28.3.6 Structures

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

    -

    28.3.7 C++ classes

    +

    28.3.7 C++ classes

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

    -

    28.3.8 C++ inheritance

    +

    28.3.8 C++ inheritance

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

    It is safe to use multiple inheritance with SWIG.

    -

    28.3.9 Pointers, references, values, and arrays

    +

    28.3.9 Pointers, references, values, and arrays

    @@ -840,7 +841,7 @@ Foo spam7();

    then all three functions will return a pointer to some Foo object. Since the third function (spam7) returns a value, newly allocated memory is used to hold the result and a pointer is returned (Lua will release this memory when the return value is garbage collected). The other two are pointers which are assumed to be managed by the C code and so will not be garbage collected.

    -

    28.3.10 C++ overloaded functions

    +

    28.3.10 C++ overloaded functions

    @@ -870,9 +871,9 @@ Similarly, if you have a class like this,

    class Foo {
     public:
    -    Foo();
    -    Foo(const Foo &);
    -    ...
    +  Foo();
    +  Foo(const Foo &);
    +  ...
     };
     

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

    -

    28.3.11 C++ operators

    +

    28.3.11 C++ operators

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

    -

    28.3.12 Class extension with %extend

    +

    28.3.12 Class extension with %extend

    @@ -1089,13 +1090,14 @@ public: Now we extend it with some new code

    %extend Complex {
    -   const char *__str__() {
    -       static char tmp[1024];
    -       sprintf(tmp,"Complex(%g,%g)", $self->re(),$self->im());
    -       return tmp;
    -   }
    -   bool operator==(const Complex& c)
    -   {    return ($self->re()==c.re() && $self->im()==c.im());}
    +  const char *__str__() {
    +    static char tmp[1024];
    +    sprintf(tmp,"Complex(%g,%g)", $self->re(),$self->im());
    +    return tmp;
    +  }
    +  bool operator==(const Complex& c) {
    +    return ($self->re()==c.re() && $self->im()==c.im());
    +  }
     };
     

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

    -

    28.3.13 Using %newobject to release memory

    +

    28.3.13 Using %newobject to release memory

    If you have a function that allocates memory like this,

    char *foo() {
    -   char *result = (char *) malloc(...);
    -   ...
    -   return result;
    +  char *result = (char *) malloc(...);
    +  ...
    +  return result;
     }
     
    @@ -1140,7 +1142,7 @@ char *foo();

    This will release the allocated memory.

    -

    28.3.14 C++ templates

    +

    28.3.14 C++ templates

    @@ -1153,12 +1155,12 @@ char *foo(); 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(); }; @@ -1175,16 +1177,16 @@ In Lua:

    Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.

    -

    28.3.15 C++ Smart Pointers

    +

    28.3.15 C++ Smart Pointers

    In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:

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

    28.3.16 C++ Exceptions

    +

    28.3.16 C++ Exceptions

    @@ -1370,7 +1372,7 @@ and the "Exception handling add exception specification to functions or globally (respectively).

    -

    28.3.17 Namespaces

    +

    28.3.17 Namespaces

    @@ -1421,7 +1423,7 @@ Now, from Lua usage is as follows: 19 > -

    28.3.17.1 Compatibility Note

    +

    28.3.17.1 Compatibility Note

    @@ -1437,7 +1439,7 @@ If SWIG is running in a backwards compatible way, i.e. without the -no-old-m -

    28.3.17.2 Names

    +

    28.3.17.2 Names

    If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries @@ -1481,7 +1483,7 @@ surrounding scope without any prefixing. Pretending that Test2 is a struct, not > -

    28.3.17.3 Inheritance

    +

    28.3.17.3 Inheritance

    The internal organization of inheritance has changed. @@ -1522,12 +1524,12 @@ function > -

    28.4 Typemaps

    +

    28.4 Typemaps

    This section explains what typemaps are and how to use them. The default wrapping behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrapping. This section will be explaining how to use typemaps to best effect

    -

    28.4.1 What is a typemap?

    +

    28.4.1 What is a typemap?

    A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:

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

    28.4.2 Using typemaps

    +

    28.4.2 Using typemaps

    There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.

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

    -

    28.4.3 Typemaps and arrays

    +

    28.4.3 Typemaps and arrays

    Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor @@ -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.

    -

    28.4.4 Typemaps and pointer-pointer functions

    +

    28.4.4 Typemaps and pointer-pointer functions

    Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX as well as many other libraries have this kind of function. An example is given below:

    @@ -1706,7 +1708,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -

    28.5 Writing typemaps

    +

    28.5 Writing typemaps

    This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Lua C API as well as the material in the "Typemaps" chapter.

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

    -

    28.5.1 Typemaps you can write

    +

    28.5.1 Typemaps you can write

    There are many different types of typemap that can be written, the full list can be found in the "Typemaps" chapter. However the following are the most commonly used ones.

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

    28.5.2 SWIG's Lua-C API

    +

    28.5.2 SWIG's Lua-C API

    This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.

    @@ -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()

    void SWIG_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type,int own);

    @@ -1777,7 +1779,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp
    Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.
    -

    28.6 Customization of your Bindings

    +

    28.6 Customization of your Bindings

    @@ -1786,7 +1788,7 @@ This section covers adding of some small extra bits to your module to add the la -

    28.6.1 Writing your own custom wrappers

    +

    28.6.1 Writing your own custom wrappers

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

    -

    28.6.2 Adding additional Lua code

    +

    28.6.2 Adding additional Lua code

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

    -

    28.7 Details on the Lua binding

    +

    28.7 Details on the Lua binding

    @@ -1854,7 +1856,7 @@ See Examples/lua/arrays for an example of this code.

    -

    28.7.1 Binding global data into the module.

    +

    28.7.1 Binding global data into the module.

    @@ -1914,7 +1916,7 @@ end

    That way when you call 'a=example.Foo', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code 'example.Foo=10', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.

    -

    28.7.2 Userdata and Metatables

    +

    28.7.2 Userdata and Metatables

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

    -

    28.7.3 Memory management

    +

    28.7.3 Memory management

    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)

    Text

    style links don't work and need changing to +#

    Text

    +# 2) Tabs in
     elements should be expanded to 8 spaces by default, but
    +#     are expanded to just one space and css tab-size is not working.
    +#  3) 
       elements do not always select a fixed-width font - try installing the
    +#     Courier font to fix - these have been added to style.css.
    +generate: SWIGDocumentation.html
    +	wkhtmltopdf --version | grep "with patched qt" || (echo "wkhtmltopdf is not the patched qt version and so cannot be used - download it from http://wkhtmltopdf.org/downloads.html" && false)
    +	wkhtmltopdf --margin-top 20mm --margin-bottom 20mm --margin-left 10mm --margin-right 10mm --header-font-size 6 --footer-font-size 6 --header-spacing 6 --footer-spacing 6 --header-center '[doctitle]' --footer-left '[subsection]' --footer-right '[page]' SWIGDocumentation.html SWIGDocumentation.pdf
    +
    +SWIGDocumentation.html: swightml.book
     	htmldoc --batch swightml.book || true
    -	htmldoc --batch swigpdf.book || true
     	python fixstyle.py SWIGDocumentation.html
     
    -swigpdf.book: chapters Sections.html
    -	echo "#HTMLDOC 1.8.24" > swigpdf.book
    -	echo -t pdf13 -f SWIGDocumentation.pdf $(HTMLDOC_OPTIONS) --stylesheet style.css >> swigpdf.book
    -	echo "Sections.html" >> swigpdf.book
    -	cat chapters >> swigpdf.book
    -
     swightml.book: chapters Sections.html
     	echo "#HTMLDOC 1.8.24" > swightml.book
     	echo -t html -f SWIGDocumentation.html $(HTMLDOC_OPTIONS) >> swightml.book
    @@ -52,10 +58,9 @@ swightml.book: chapters Sections.html
     
     maintainer-clean: clean-baks
     	rm -f swightml.book
    -	rm -f swigpdf.book
    -	rm -f CCache.html
     	rm -f SWIGDocumentation.html
     	rm -f SWIGDocumentation.pdf
    +	rm -rf linkchecker-tmp
     
     clean-baks:
     	rm -f *.bak
    @@ -69,9 +74,18 @@ test:
     validate:
     	all=`sed '/^#/d' chapters`; for a in $$all; do validate --emacs $$a; done;
     
    -# Link checking using linkchecker
    -linkchecker:
    +# Link checking using linkchecker of the index.html only file (including anchors)
    +linkchecker1:
     	@echo -----------------------------------------------------------------------
     	@echo Note linkchecker versions prior to 6.1 do not work properly wrt anchors
     	@echo -----------------------------------------------------------------------
    -	linkchecker --config=./linkchecker.config index.html
    +	linkchecker --config=./linkchecker.config --anchors index.html
    +
    +# Check for links which don't work including those generated from the individual .html files into SWIGDocumentation.html
    +linkchecker2:
    +	rm -rf linkchecker-tmp
    +	mkdir linkchecker-tmp
    +	cp SWIGDocumentation.html linkchecker-tmp
    +	cp *.png linkchecker-tmp
    +	(cd linkchecker-tmp && linkchecker --config=../linkchecker.config -F text --no-warnings SWIGDocumentation.html)
    +
    diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html
    index ffbf6132d..f324495a3 100644
    --- a/Doc/Manual/Modula3.html
    +++ b/Doc/Manual/Modula3.html
    @@ -1,11 +1,12 @@
    -
    +
     
     
     SWIG and Modula-3
     
    +
     
     
    -

    29 SWIG and Modula-3

    +

    29 SWIG and Modula-3

    -

    29.4.5 Exceptions

    +

    29.4.5 Exceptions

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

    -

    29.4.6 Example

    +

    29.4.6 Example

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

    -

    29.5 More hints to the generator

    +

    29.5 More hints to the generator

    -

    29.5.1 Features

    +

    29.5.1 Features

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

    29.5.2 Pragmas

    +

    29.5.2 Pragmas

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

    29.6 Remarks

    +

    29.6 Remarks

      diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index 4846aedc1..089b1a4ad 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -1,12 +1,13 @@ - + Working with Modules + -

      16 Working with Modules

      +

      16 Working with Modules

        @@ -23,7 +24,7 @@ -

        16.1 Modules Introduction

        +

        16.1 Modules Introduction

        @@ -77,7 +78,7 @@ where you want to create a collection of modules. Each module in the collection is created via separate invocations of SWIG.

        -

        16.2 Basics

        +

        16.2 Basics

        @@ -176,7 +177,7 @@ in parallel from multiple threads as SWIG provides no locking - for more on that issue, read on.

        -

        16.3 The SWIG runtime code

        +

        16.3 The SWIG runtime code

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

        -

        16.4 External access to the runtime

        +

        16.4 External access to the runtime

        As described in The run-time type checker, @@ -281,7 +282,7 @@ SWIG_TYPE_TABLE to be the same as the module whose types you are trying to access.

        -

        16.5 A word of caution about static libraries

        +

        16.5 A word of caution about static libraries

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

        -

        16.6 References

        +

        16.6 References

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

        -

        16.7 Reducing the wrapper file size

        +

        16.7 Reducing the wrapper file size

        diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index fadda5fc9..08402b68c 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -1,14 +1,14 @@ - - + SWIG and MzScheme/Racket + -

        30 SWIG and MzScheme/Racket

        +

        30 SWIG and MzScheme/Racket

          @@ -24,7 +24,7 @@

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

          30.1 Creating native structures

          +

          30.1 Creating native structures

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

          30.2 Simple example

          +

          30.2 Simple example

          @@ -166,7 +166,7 @@ Some points of interest:

        • The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
        -

        30.3 External documentation

        +

        30.3 External documentation

        diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index da20b8da3..e489c4147 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -1,12 +1,13 @@ - + SWIG and Ocaml + -

        31 SWIG and Ocaml

        +

        31 SWIG and Ocaml

      @@ -80,10 +81,10 @@ variants, functions, classes, etc.

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

      -

      31.1 Preliminaries

      +

      31.1 Preliminaries

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

      -

      31.1.1 Running SWIG

      +

      31.1.1 Running SWIG

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

      -

      31.1.2 Compiling the code

      +

      31.1.2 Compiling the code

      @@ -161,7 +162,7 @@ in C++ mode, you must:

      -

      31.1.3 The camlp4 module

      +

      31.1.3 The camlp4 module

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

      31.1.4 Using your module

      +

      31.1.4 Using your module

      @@ -251,7 +252,7 @@ option to build your functions into the primitive list. This option is not needed when you build native code.

      -

      31.1.5 Compilation problems and compiling with C++

      +

      31.1.5 Compilation problems and compiling with C++

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

      -

      31.2 The low-level Ocaml/C interface

      +

      31.2 The low-level Ocaml/C interface

      @@ -307,19 +308,19 @@ A few functions exist which generate and return these:

      • caml_ptr_val receives a c_obj and returns a void *. This - should be used for all pointer purposes.
      • + should be used for all pointer purposes.
      • caml_long_val receives a c_obj and returns a long. This - should be used for most integral purposes.
      • + should be used for most integral purposes.
      • caml_val_ptr receives a void * and returns a c_obj.
      • caml_val_bool receives a C int and returns a c_obj representing - its bool value.
      • + its bool value.
      • caml_val_(u)?(char|short|int|long|float|double) receives an - appropriate C value and returns a c_obj representing it.
      • + appropriate C value and returns a c_obj representing it.
      • caml_val_string receives a char * and returns a string value.
      • caml_val_string_len receives a char * and a length and returns - a string value.
      • + a string value.
      • caml_val_obj receives a void * and an object type and returns - a C_obj, which contains a closure giving method access.
      • + a C_obj, which contains a closure giving method access.

      @@ -362,7 +363,7 @@ value items pass through directly, but you must make your own type signature for a function that uses value in this way.

      -

      31.2.1 The generated module

      +

      31.2.1 The generated module

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

      31.2.2 Enums

      +

      31.2.2 Enums

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

      31.2.2.1 Enum typing in Ocaml

      +

      31.2.2.1 Enum typing in Ocaml

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

      -

      31.2.3 Arrays

      +

      31.2.3 Arrays

      -

      31.2.3.1 Simple types of bounded arrays

      +

      31.2.3.1 Simple types of bounded arrays

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

      -

      31.2.3.2 Complex and unbounded arrays

      +

      31.2.3.2 Complex and unbounded arrays

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

      -

      31.2.3.3 Using an object

      +

      31.2.3.3 Using an object

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

      -

      31.2.3.4 Example typemap for a function taking float * and int

      +

      31.2.3.4 Example typemap for a function taking float * and int

      @@ -543,24 +544,24 @@ into this type of function convenient. #include <stdio.h> void printfloats( float *tab, int len ) { - int i; + int i; - for( i = 0; i < len; i++ ) { - printf( "%f ", tab[i] ); - } + for( i = 0; i < len; i++ ) { + printf( "%f ", tab[i] ); + } - printf( "\n" ); + printf( "\n" ); } %} %typemap(in) (float *tab, int len) { - int i; - /* $*1_type */ - $2 = caml_array_len($input); - $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); - for( i = 0; i < $2; i++ ) { - $1[i] = caml_double_val(caml_array_nth($input,i)); - } + int i; + /* $*1_type */ + $2 = caml_array_len($input); + $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); + for( i = 0; i < $2; i++ ) { + $1[i] = caml_double_val(caml_array_nth($input,i)); + } } void printfloats( float *tab, int len ); @@ -574,7 +575,7 @@ void printfloats( float *tab, int len ); -

      31.2.4 C++ Classes

      +

      31.2.4 C++ Classes

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

      -

      31.2.4.1 STL vector and string Example

      +

      31.2.4.1 STL vector and string Example

      @@ -639,7 +640,7 @@ length. Instead, use multiple returns, as in the argout_ref example. %include <stl.i> namespace std { - %template(StringVector) std::vector < string >; + %template(StringVector) std::vector < string >; }; %include "example.h" @@ -697,7 +698,7 @@ baz # -

      31.2.4.2 C++ Class Example

      +

      31.2.4.2 C++ Class Example

      @@ -714,20 +715,20 @@ Here's a simple example using Trolltech's Qt Library: %} class QApplication { public: - QApplication( int argc, char **argv ); - void setMainWidget( QWidget *widget ); - void exec(); + QApplication( int argc, char **argv ); + void setMainWidget( QWidget *widget ); + void exec(); }; class QPushButton { public: - QPushButton( char *str, QWidget *w ); - void resize( int x, int y ); - void show(); + QPushButton( char *str, QWidget *w ); + void resize( int x, int y ); + void show(); }; -

      31.2.4.3 Compiling the example

      +

      31.2.4.3 Compiling the example

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

      31.2.4.4 Sample Session

      +

      31.2.4.4 Sample Session

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

      -

      31.2.5 Director Classes

      +

      31.2.5 Director Classes

      -

      31.2.5.1 Director Introduction

      +

      31.2.5.1 Director Introduction

      @@ -802,7 +803,7 @@ class foo { };

      -

      31.2.5.2 Overriding Methods in Ocaml

      +

      31.2.5.2 Overriding Methods in Ocaml

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

      -

      31.2.5.3 Director Usage Example

      +

      31.2.5.3 Director Usage Example

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

      -

      31.2.5.4 Creating director objects

      +

      31.2.5.4 Creating director objects

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

      -

      31.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      +

      31.2.5.5 Typemaps for directors, directorin, directorout, directorargout

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

      -

      31.2.5.6 directorin typemap

      +

      31.2.5.6 typemap

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

      -

      31.2.5.7 directorout typemap

      +

      31.2.5.7 directorout typemap

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

      -

      31.2.5.8 directorargout typemap

      +

      31.2.5.8 directorargout typemap

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

      -

      31.2.6 Exceptions

      +

      31.2.6 Exceptions

      diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 5f8437a6a..25ec933ff 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -1,14 +1,15 @@ - + SWIG and Octave + -

      32 SWIG and Octave

      +

      32 SWIG and Octave

      -

      32.3 A tour of basic C/C++ wrapping

      +

      32.3 A tour of basic C/C++ wrapping

      -

      32.3.1 Modules

      +

      32.3.1 Modules

      @@ -211,7 +217,7 @@ octave:4> swigexample.gcd(4,6) ans = 2 -

      32.3.2 Functions

      +

      32.3.2 Functions

      @@ -228,7 +234,7 @@ int fact(int n);

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

      32.3.3 Global variables

      +

      32.3.3 Global variables

      @@ -281,7 +287,7 @@ octave:2> swigexample.PI=3.142; octave:3> swigexample.PI ans = 3.1420 -

      32.3.4 Constants and enums

      +

      32.3.4 Constants and enums

      @@ -303,12 +309,12 @@ swigexample.SCONST="Hello World" swigexample.SUNDAY=0 .... -

      32.3.5 Pointers

      +

      32.3.5 Pointers

      C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface: - 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 
      -

      32.3.6 Structures and C++ classes

      +

      32.3.6 Structures and C++ classes

      @@ -485,7 +491,7 @@ ans = 1 Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.

      -

      32.3.7 C++ inheritance

      +

      32.3.7 C++ inheritance

      @@ -494,7 +500,7 @@ This information contains the full class hierarchy. When an indexing operation ( the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref.

      -

      32.3.8 C++ overloaded functions

      +

      32.3.8 C++ overloaded functions

      @@ -504,7 +510,7 @@ The dispatch function selects which overload to call (if any) based on the passe typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.

      -

      32.3.9 C++ operators

      +

      32.3.9 C++ operators

      @@ -512,7 +518,7 @@ C++ operator overloading is supported, in a way similar to other modules. The swig_ref type supports all unary and binary operators between itself and all other types that exist in the system at module load time. When an operator is used (where one of the operands is a swig_ref), the runtime routes the call to either a member function of the given object, or to a global function whose named is derived from the types of the operands (either both or just the lhs or rhs).

      -For example, if a and b are SWIG variables in Octave, a+b becomes a.__add(b). The wrapper is then free to implement __add to do whatever it wants. A wrapper may define the __add function manually, %rename some other function to it, or %rename a C++ operator to it. +For example, if a and b are SWIG variables in Octave, a+b becomes a.__add__(b). The wrapper is then free to implement __add__ to do whatever it wants. A wrapper may define the __add__ function manually, %rename some other function to it, or %rename a C++ operator to it.

      By default the C++ operators are renamed to their corresponding Octave operators. So without doing any work, the following interface @@ -539,87 +545,87 @@ assert(c.value==5); Octave operators are mapped in the following way:

      -__brace      a{args}
      -__brace_asgn a{args} = rhs
      -__paren      a(args)
      -__paren_asgn a(args) = rhs
      -__str        generates string rep
      -__not        !a
      -__uplus      +a
      -__uminus     -a
      -__transpose  a.'
      -__hermitian  a'
      -__incr       a++
      -__decr       a--
      -__add        a + b
      -__sub        a - b
      -__mul        a * b
      -__div        a / b
      -__pow        a ^ b
      -__ldiv       a \ b
      -__lshift     a << b
      -__rshift     a >> b
      -__lt         a < b
      -__le         a <= b
      -__eq         a == b
      -__ge         a >= b
      -__gt         a > b
      -__ne         a != b
      -__el_mul     a .* b
      -__el_div     a ./ b
      -__el_pow     a .^ b
      -__el_ldiv    a .\ b
      -__el_and     a & b
      -__el_or      a | b
      +__brace__      a{args}
      +__brace_asgn__ a{args} = rhs
      +__paren__      a(args)
      +__paren_asgn__ a(args) = rhs
      +__str__        generates string rep
      +__not__        !a
      +__uplus__      +a
      +__uminus__     -a
      +__transpose__  a.'
      +__hermitian__  a'
      +__incr__       a++
      +__decr__       a--
      +__add__        a + b
      +__sub__        a - b
      +__mul__        a * b
      +__div__        a / b
      +__pow__        a ^ b
      +__ldiv__       a \ b
      +__lshift__     a << b
      +__rshift__     a >> b
      +__lt__         a < b
      +__le__         a <= b
      +__eq__         a == b
      +__ge__         a >= b
      +__gt__         a > b
      +__ne__         a != b
      +__el_mul__     a .* b
      +__el_div__     a ./ b
      +__el_pow__     a .^ b
      +__el_ldiv__    a .\ b
      +__el_and__     a & b
      +__el_or__      a | b
       

      On the C++ side, the default mappings are as follows:

      -%rename(__add)       *::operator+;
      -%rename(__add)       *::operator+();
      -%rename(__add)       *::operator+() const;
      -%rename(__sub)       *::operator-;
      -%rename(__uminus)    *::operator-();
      -%rename(__uminus)    *::operator-() const;
      -%rename(__mul)       *::operator*;
      -%rename(__div)       *::operator/;
      -%rename(__mod)       *::operator%;
      -%rename(__lshift)    *::operator<<;
      -%rename(__rshift)    *::operator>>;
      -%rename(__el_and)    *::operator&&;
      -%rename(__el_or)     *::operator||;
      -%rename(__xor)       *::operator^;
      -%rename(__invert)    *::operator~;
      -%rename(__lt)        *::operator<;
      -%rename(__le)        *::operator<=;
      -%rename(__gt)        *::operator>;
      -%rename(__ge)        *::operator>=;
      -%rename(__eq)        *::operator==;
      -%rename(__ne)        *::operator!=;
      -%rename(__not)       *::operator!;
      -%rename(__incr)      *::operator++;
      -%rename(__decr)      *::operator--;
      -%rename(__paren)     *::operator();
      -%rename(__brace)     *::operator[];
      +%rename(__add__)       *::operator+;
      +%rename(__add__)       *::operator+();
      +%rename(__add__)       *::operator+() const;
      +%rename(__sub__)       *::operator-;
      +%rename(__uminus__)    *::operator-();
      +%rename(__uminus__)    *::operator-() const;
      +%rename(__mul__)       *::operator*;
      +%rename(__div__)       *::operator/;
      +%rename(__mod__)       *::operator%;
      +%rename(__lshift__)    *::operator<<;
      +%rename(__rshift__)    *::operator>>;
      +%rename(__el_and__)    *::operator&&;
      +%rename(__el_or__)     *::operator||;
      +%rename(__xor__)       *::operator^;
      +%rename(__invert__)    *::operator~;
      +%rename(__lt__)        *::operator<;
      +%rename(__le__)        *::operator<=;
      +%rename(__gt__)        *::operator>;
      +%rename(__ge__)        *::operator>=;
      +%rename(__eq__)        *::operator==;
      +%rename(__ne__)        *::operator!=;
      +%rename(__not__)       *::operator!;
      +%rename(__incr__)      *::operator++;
      +%rename(__decr__)      *::operator--;
      +%rename(__paren__)     *::operator();
      +%rename(__brace__)     *::operator[];
       

      Octave can also utilise friend (i.e. non-member) operators with a simple %rename: see the example in the Examples/octave/operator directory.

      -

      32.3.10 Class extension with %extend

      +

      32.3.10 Class extension with %extend

      The %extend directive works the same as in other modules.

      -You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed to a special method __str that can be defined inside an %extend. +You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed to a special method __str__ that can be defined inside an %extend.

       %extend A {
      -string __str() {
      +string __str__() {
         stringstream sout;
         sout<<$self->value;
         return sout.str();
      @@ -635,10 +641,19 @@ octave:2> a
       a = 4
       octave:3> printf("%s\n",a);
       4
      -octave:4> a.__str()
      +octave:4> a.__str__()
       4
       
      -

      32.3.11 C++ templates

      + +

      +Similarly, Octave can use the __float__ method to convert an object to a numeric value. +

      + +

      +Octave 3.8.0 and later versions will also map unary functions X() to the corresponding __X__ method, where X includes: abs(), acos(), acosh(), angle(), arg(), asin(), asinh(), atan(), atanh(), cbrt(), ceil(), conj(), cos(), cosh(), dawson(), erf(), erfc(), erfcinv(), erfcx(), erfi(), erfinv(), exp(), expm1(), finite(), fix(), floor(), gamma(), imag(), isalnum(), isalpha(), isascii(), iscntrl(), isdigit(), isgraph(), isinf(), islower(), isna(), isnan(), isprint(), ispunct(), isspace(), isupper(), isxdigit(), lgamma(), log(), log10(), log1p(), log2(), real(), round(), roundb(), signbit(), signum(), sin(), sinh(), sqrt(), tan(), tanh(), toascii(), tolower(), toupper() +

      + +

      32.3.11 C++ templates

      @@ -648,10 +663,10 @@ For example, function templates can be instantiated as follows:

      %module swigexample
       %inline {
      - template<class __scalar>
      -   __scalar mul(__scalar a,__scalar b) {
      -   return a*b;
      - }
      +  template<class __scalar>
      +    __scalar mul(__scalar a,__scalar b) {
      +    return a*b;
      +  }
       }
       %include <std_complex.i>
       %template(mul) mul<std::complex<double> >
      @@ -687,7 +702,7 @@ Similarly, class templates can be instantiated as in the following example,
             s+=_s;
             return *this;
           }
      -    std::string __str() const {
      +    std::string __str__() const {
             std::stringstream sout;
             sout<<s;
             return sout.str();
      @@ -715,14 +730,28 @@ ans =
       
      -

      32.3.12 C++ Smart Pointers

      +

      32.3.12 C++ Smart Pointers

      + + +

      32.3.12.1 The shared_ptr Smart Pointer

      + + +

      +The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Octave in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +

      + + +

      32.3.12.2 Generic Smart Pointers

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

      -

      32.3.13 Directors (calling Octave from C++ code)

      +

      32.3.13 Directors (calling Octave from C++ code)

      @@ -803,14 +832,14 @@ c-side routine called octave-side routine called -

      32.3.14 Threads

      +

      32.3.14 Threads

      The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.

      -

      32.3.15 Memory management

      +

      32.3.15 Memory management

      @@ -844,14 +873,14 @@ The %newobject directive may be used to control this behavior for pointers retur In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing).

      -

      32.3.16 STL support

      +

      32.3.16 STL support

      Various STL library files are provided for wrapping STL containers.

      -

      32.3.17 Matrix typemaps

      +

      32.3.17 Matrix typemaps

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 8bc7cbfd3..4722a01ba 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -1,12 +1,13 @@ - + SWIG and Perl5 + -

      33 SWIG and Perl5

      +

      33 SWIG and Perl5

        @@ -96,7 +97,7 @@ later. We're no longer testing regularly with older versions, but Perl 5.6 seems to mostly work, while older versions don't.

        -

        33.1 Overview

        +

        33.1 Overview

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

        -

        33.2 Preliminaries

        +

        33.2 Preliminaries

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

        -

        33.2.1 Getting the right header files

        +

        33.2.1 Getting the right header files

        @@ -174,7 +175,7 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'

      -

      33.2.2 Compiling a dynamic module

      +

      33.2.2 Compiling a dynamic module

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

      -

      33.2.3 Building a dynamic module with MakeMaker

      +

      33.2.3 Building a dynamic module with MakeMaker

      @@ -219,9 +220,9 @@ script such as the following:

      # File : Makefile.PL use ExtUtils::MakeMaker; WriteMakefile( - `NAME' => `example', # Name of package - `LIBS' => [`-lm'], # Name of custom libraries - `OBJECT' => `example.o example_wrap.o' # Object files + `NAME' => `example', # Name of package + `LIBS' => [`-lm'], # Name of custom libraries + `OBJECT' => `example.o example_wrap.o' # Object files ); @@ -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.

      -

      33.2.4 Building a static version of Perl

      +

      33.2.4 Building a static version of Perl

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

       $ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \
      -	-lperl -lsocket -lnsl -lm -o myperl
      +        -lperl -lsocket -lnsl -lm -o myperl
       

      @@ -310,7 +311,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

      -

      33.2.5 Using the module

      +

      33.2.5 Using the module

      @@ -463,7 +464,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      33.2.6 Compilation problems and compiling with C++

      +

      33.2.6 Compilation problems and compiling with C++

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

      -

      33.2.7 Compiling for 64-bit platforms

      +

      33.2.7 Compiling for 64-bit platforms

      @@ -633,7 +634,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      33.3 Building Perl Extensions under Windows

      +

      33.3 Building Perl Extensions under Windows

      @@ -644,7 +645,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

      -

      33.3.1 Running SWIG from Developer Studio

      +

      33.3.1 Running SWIG from Developer Studio

      @@ -707,7 +708,7 @@ print "$a\n"; -

      33.3.2 Using other compilers

      +

      33.3.2 Using other compilers

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

      -

      33.4 The low-level interface

      +

      33.4 The low-level interface

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

      -

      33.4.1 Functions

      +

      33.4.1 Functions

      @@ -748,7 +749,7 @@ use example; $a = &example::fact(2); -

      33.4.2 Global variables

      +

      33.4.2 Global variables

      @@ -818,7 +819,7 @@ extern char *path; // Declared later in the input -

      33.4.3 Constants

      +

      33.4.3 Constants

      @@ -858,7 +859,7 @@ print example::FOO,"\n"; -

      33.4.4 Pointers

      +

      33.4.4 Pointers

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

      -

      33.4.5 Structures

      +

      33.4.5 Structures

      @@ -977,7 +978,7 @@ accessor functions as described in the "SWIG Basics" chapter. For example,

       struct Vector {
      -	double x,y,z;
      +  double x,y,z;
       };
       
      @@ -1019,12 +1020,12 @@ can also be forced to be read-only using the %immutable directive. For
       struct Foo {
      -   ...
      -   %immutable;
      -   int x;        /* Read-only members */
      -   char *name;
      -   %mutable;
      -   ...
      +  ...
      +  %immutable;
      +  int x;        /* Read-only members */
      +  char *name;
      +  %mutable;
      +  ...
       };
       
      @@ -1044,7 +1045,7 @@ Array members are normally wrapped as read-only. For example,
       struct Foo {
      -   int  x[50];
      +  int x[50];
       };
       
      @@ -1075,11 +1076,11 @@ When structure members are wrapped, they are handled as pointers. For example,
       struct Foo {
      -   ...
      +  ...
       };
       
       struct Bar {
      -   Foo f;
      +  Foo f;
       };
       
      @@ -1101,7 +1102,7 @@ void Bar_f_set(Bar *b, Foo *val) { -

      33.4.6 C++ classes

      +

      33.4.6 C++ classes

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

      -

      33.4.7 C++ classes and type-checking

      +

      33.4.7 C++ classes and type-checking

      @@ -1202,7 +1203,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

      -

      33.4.8 C++ overloaded functions

      +

      33.4.8 C++ overloaded functions

      @@ -1221,9 +1222,9 @@ void foo(char *c); // Stays 'foo' (not renamed) class Spam { public: - void foo(int); // Becomes 'foo_i' - void foo(double); // Becomes 'foo_d' - ... + void foo(int); // Becomes 'foo_i' + void foo(double); // Becomes 'foo_d' + ... }; @@ -1246,7 +1247,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.

      -

      33.4.9 Operators

      +

      33.4.9 Operators

      @@ -1258,22 +1259,22 @@ The following C++ operators are currently supported by the Perl module:

        -
      • operator++
      • -
      • operator--
      • -
      • operator+
      • -
      • operator-
      • -
      • operator*
      • -
      • operator/
      • -
      • operator==
      • -
      • operator!=
      • -
      • operator%
      • -
      • operator>
      • -
      • operator<
      • +
      • operator++
      • +
      • operator--
      • +
      • operator+
      • +
      • operator-
      • +
      • operator*
      • +
      • operator/
      • +
      • operator==
      • +
      • operator!=
      • +
      • operator%
      • +
      • operator>
      • +
      • operator<
      • operator and
      • operator or
      -

      33.4.10 Modules and packages

      +

      33.4.10 Modules and packages

      @@ -1368,7 +1369,7 @@ print Foo::fact(4),"\n"; # Call a function in package FooBar --> -

      33.5 Input and output parameters

      +

      33.5 Input and output parameters

      @@ -1379,7 +1380,7 @@ example:

       void add(int x, int y, int *result) {
      -   *result = x + y;
      +  *result = x + y;
       }
       
      @@ -1391,7 +1392,7 @@ or perhaps
       int sub(int *x, int *y) {
      -   return *x+*y;
      +  return *x+*y;
       }
       
      @@ -1455,7 +1456,7 @@ If a function mutates one of its parameters like this,
       void negate(int *x) {
      -   *x = -(*x);
      +  *x = -(*x);
       }
       
      @@ -1587,7 +1588,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

      -

      33.6 Exception handling

      +

      33.6 Exception handling

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

      -

      33.7 Remapping datatypes with typemaps

      +

      33.7 Remapping datatypes with typemaps

      @@ -1769,7 +1770,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

      -

      33.7.1 A simple typemap example

      +

      33.7.1 A simple typemap example

      @@ -1782,8 +1783,8 @@ you might define a typemap like this: %module example %typemap(in) int { - $1 = (int) SvIV($input); - printf("Received an integer : %d\n", $1); + $1 = (int) SvIV($input); + printf("Received an integer : %d\n", $1); } ... %inline %{ @@ -1828,8 +1829,8 @@ the typemap system follows typedef declarations. For example:

       %typemap(in) int n {
      -	$1 = (int) SvIV($input);
      -	printf("n = %d\n",$1);
      +  $1 = (int) SvIV($input);
      +  printf("n = %d\n",$1);
       }
       %inline %{
       typedef int Integer;
      @@ -1873,7 +1874,7 @@ example::count("e","Hello World");
       
      -

      33.7.2 Perl5 typemaps

      +

      33.7.2 Perl5 typemaps

      @@ -1978,7 +1979,7 @@ Return of C++ member data (all languages). Check value of input parameter. -

      33.7.3 Typemap variables

      +

      33.7.3 Typemap variables

      @@ -2049,7 +2050,7 @@ properly assigned. The Perl name of the wrapper function being created. -

      33.7.4 Useful functions

      +

      33.7.4 Useful functions

      @@ -2118,7 +2119,7 @@ int sv_isa(SV *, char *0; -

      33.8 Typemap Examples

      +

      33.8 Typemap Examples

      @@ -2127,7 +2128,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

      -

      33.8.1 Converting a Perl5 array to a char **

      +

      33.8.1 Converting a Perl5 array to a char **

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

      33.8.2 Return values

      +

      33.8.2 Return values

      @@ -2239,16 +2240,16 @@ can be done using the EXTEND() macro as in:

       %typemap(argout) int *OUTPUT {
      -	if (argvi >= items) {            
      -		EXTEND(sp,1);              /* Extend the stack by 1 object */
      -	}
      -	$result = sv_newmortal();
      -	sv_setiv($target,(IV) *($1));
      -	argvi++;
      +  if (argvi >= items) {
      +    EXTEND(sp,1);              /* Extend the stack by 1 object */
      +  }
      +  $result = sv_newmortal();
      +  sv_setiv($target,(IV) *($1));
      +  argvi++;
       }
       
      -

      33.8.3 Returning values from arguments

      +

      33.8.3 Returning values from arguments

      @@ -2263,24 +2264,24 @@ its arguments. This example describes the implementation of the OUTPUT // an output value. %typemap(argout) double *OUTPUT { - $result = sv_newmortal(); - sv_setnv($result, *$input); - argvi++; /* Increment return count -- important! */ + $result = sv_newmortal(); + sv_setnv($result, *$input); + argvi++; /* Increment return count -- important! */ } // We don't care what the input value is. Ignore, but set to a temporary variable %typemap(in,numinputs=0) double *OUTPUT(double junk) { - $1 = &junk; + $1 = &junk; } // Now a function to test it %{ /* Returns the first two input arguments */ int multout(double a, double b, double *out1, double *out2) { - *out1 = a; - *out2 = b; - return 0; + *out1 = a; + *out2 = b; + return 0; }; %} @@ -2302,7 +2303,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13); -

      33.8.4 Accessing array structure members

      +

      33.8.4 Accessing array structure members

      @@ -2348,10 +2349,10 @@ For example:

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

      -

      33.8.5 Turning Perl references into C pointers

      +

      33.8.5 Turning Perl references into C pointers

      @@ -2376,7 +2377,7 @@ have a C function that modifies its arguments like this:

       void add(double a, double b, double *c) {
      -	*c = a + b;
      +  *c = a + b;
       }
       
      @@ -2430,7 +2431,7 @@ print "$c\n"; -

      33.8.6 Pointer handling

      +

      33.8.6 Pointer handling

      @@ -2476,7 +2477,9 @@ is usually accessed as follows:

       Foo *f;
      -if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
      +if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0))) {
      +  SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +}
       
       SV *sv = sv_newmortal();
       SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
      @@ -2491,7 +2494,9 @@ variable $1_descriptor.  For example:
       
       %typemap(in) Foo * {
      -   if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
      +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) {
      +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +  }
       }
       
      @@ -2504,12 +2509,14 @@ For example:
       %typemap(in) Foo * {
      -   if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
      +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $descriptor(Foo *), 0))) {
      +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +  }
       }
       
      -

      33.9 Proxy classes

      +

      33.9 Proxy classes

      @@ -2525,7 +2532,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

      -

      33.9.1 Preliminaries

      +

      33.9.1 Preliminaries

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

      -

      33.9.2 Structure and class wrappers

      +

      33.9.2 Structure and class wrappers

      @@ -2557,9 +2564,9 @@ Suppose you have the following SWIG interface file:

       %module example
       struct Vector {
      -	Vector(double x, double y, double z);
      -	~Vector();
      -	double x,y,z;
      +  Vector(double x, double y, double z);
      +  ~Vector();
      +  double x,y,z;
       };
       
       
      @@ -2609,8 +2616,9 @@ sub DESTROY { my $self = tied(%{$_[0]}); delete $ITERATORS{$self}; if (exists $OWNER{$self}) { - examplec::delete_Vector($self)); - delete $OWNER{$self}; + examplec::delete_Vector($self)); + delete $OWNER{$self}; + } } sub FETCH { @@ -2662,8 +2670,8 @@ $v->{x} = 7.5; # Assignment of all members %$v = ( x=>3, - y=>9, - z=>-2); + y=>9, + z=>-2); # Reading members $x = $v->{x}; @@ -2673,7 +2681,7 @@ $v->DESTROY();
      -

      33.9.3 Object Ownership

      +

      33.9.3 Object Ownership

      @@ -2684,7 +2692,7 @@ problem---suppose you had a function like this:

       Vector *Vector_get(Vector *v, int index) {
      -	return &v[i];
      +  return &v[i];
       }
       
      @@ -2697,9 +2705,9 @@ Vector object:
       Vector *new_Vector(double x, double y, double z) {
      -	Vector *v;
      -	v = new Vector(x,y,z);        // Call C++ constructor
      -	return v;
      +  Vector *v;
      +  v = new Vector(x,y,z);        // Call C++ constructor
      +  return v;
       }
       
      @@ -2760,7 +2768,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages.

      -

      33.9.4 Nested Objects

      +

      33.9.4 Nested Objects

      @@ -2769,10 +2777,10 @@ Suppose that we have a new object that looks like this:

       struct Particle {
      -	Vector r;
      -	Vector v;
      -	Vector f;
      -	int	type;
      +  Vector r;
      +  Vector v;
      +  Vector f;
      +  int type;
       }
       
       
      @@ -2788,9 +2796,9 @@ look like this (along with some supporting code): package Particle; ... %BLESSEDMEMBERS = ( - r => `Vector', - v => `Vector', - f => `Vector', + r => `Vector', + v => `Vector', + f => `Vector', ); @@ -2813,7 +2821,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0); -

      33.9.5 Proxy Functions

      +

      33.9.5 Proxy Functions

      @@ -2847,7 +2855,7 @@ This function replaces the original function, but operates in an identical manner.

      -

      33.9.6 Inheritance

      +

      33.9.6 Inheritance

      @@ -2866,23 +2874,23 @@ interface file: class Shape { public: - virtual double area() = 0; - virtual double perimeter() = 0; - void set_location(double x, double y); + virtual double area() = 0; + virtual double perimeter() = 0; + void set_location(double x, double y); }; class Circle : public Shape { public: - Circle(double radius); - ~Circle(); - double area(); - double perimeter(); + Circle(double radius); + ~Circle(); + double area(); + double perimeter(); }; class Square : public Shape { public: - Square(double size); - ~Square(); - double area(); - double perimeter(); + Square(double size); + ~Square(); + double area(); + double perimeter(); } @@ -2923,7 +2931,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).

      -

      33.9.7 Modifying the proxy methods

      +

      33.9.7 Modifying the proxy methods

      @@ -2951,7 +2959,7 @@ public: }; -

      33.10 Adding additional Perl code

      +

      33.10 Adding additional Perl code

      @@ -2995,14 +3003,14 @@ low-level helper functions. For example, this code now seems to work:

       my $a =
         [[1,0,0,0],
      -   [0,1,0,0],
      -   [0,0,1,0],
      -   [0,0,0,1]];
      +  [0,1,0,0],
      +  [0,0,1,0],
      +  [0,0,0,1]];
       set_transform($im, $a);
       
      -

      33.11 Cross language polymorphism

      +

      33.11 Cross language polymorphism

      @@ -3036,7 +3044,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      33.11.1 Enabling directors

      +

      33.11.1 Enabling directors

      @@ -3126,7 +3134,7 @@ sub one { -

      33.11.2 Director classes

      +

      33.11.2 Director classes

      @@ -3206,7 +3214,7 @@ so there is no need for the extra overhead involved with routing the calls through Perl.

      -

      33.11.3 Ownership and object destruction

      +

      33.11.3 Ownership and object destruction

      @@ -3255,7 +3263,7 @@ sub DESTROY { -

      33.11.4 Exception unrolling

      +

      33.11.4 Exception unrolling

      @@ -3311,7 +3319,7 @@ Swig::DirectorMethodException is thrown, Perl will register the exception as soon as the C wrapper function returns.

      -

      33.11.5 Overhead and code bloat

      +

      33.11.5 Overhead and code bloat

      @@ -3345,7 +3353,7 @@ directive) for only those methods that are likely to be extended in Perl.

      -

      33.11.6 Typemaps

      +

      33.11.6 Typemaps

      diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 623adb68a..0019968cc 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -1,13 +1,13 @@ - - + SWIG and PHP + -

      34 SWIG and PHP

      +

      34 SWIG and PHP

        @@ -25,7 +25,7 @@
      • Pointers and References
      • Structures and C++ classes
          -
        • Using -noproxy +
        • Using -noproxy
        • Constructors and Destructors
        • Static Member Variables
        • Static Member Functions @@ -49,19 +49,6 @@ -

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

          -

          34.1 Generating PHP Extensions

          +

          34.1 Generating PHP Extensions

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

          -

          34.1.1 Building a loadable extension

          +

          34.1.1 Building a loadable extension

          @@ -136,11 +139,11 @@ least work for Linux though):

          -	gcc `php-config --includes` -fpic -c example_wrap.c example.c
          -	gcc -shared example_wrap.o example.o -o example.so
          +        gcc `php-config --includes` -fpic -c example_wrap.c example.c
          +        gcc -shared example_wrap.o example.o -o example.so
           
          -

          34.1.2 Using PHP Extensions

          +

          34.1.2 Using PHP Extensions

          @@ -150,7 +153,7 @@ load it. To do this, add a line like this to the [PHP] section of

          -	extension=/path/to/modulename.so
          +        extension=/path/to/modulename.so
           

          @@ -165,7 +168,7 @@ PHP script which uses your extension:

          -	dl("/path/to/modulename.so");	// Load the module
          +        dl("/path/to/modulename.so"); // Load the module
           

          @@ -180,7 +183,7 @@ call for you if the extension isn't already loaded:

          -	include("example.php");
          +        include("example.php");
           

          @@ -188,7 +191,7 @@ This PHP module also defines the PHP classes for the wrapped API, so you'll almost certainly want to include it anyway.

          -

          34.2 Basic PHP interface

          +

          34.2 Basic PHP interface

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

          -

          34.2.1 Constants

          +

          34.2.1 Constants

          @@ -249,7 +252,7 @@ For example,

           %module example
           
          -#define EASY_TO_MISPELL	0
          +#define EASY_TO_MISPELL 0
           
          @@ -262,9 +265,9 @@ accessed incorrectly in PHP, include("example.php"); if(EASY_TO_MISPEL) { - .... + ... } else { - .... + ... } @@ -273,10 +276,11 @@ if(EASY_TO_MISPEL) {

          The mis-spelled constant will become the string 'EASY_TO_MISPEL', which is treated as true by the if test, when the value of the intended constant -would be treated as false! +would be treated as false! Modern versions of PHP will at least issue +a PHP notice by default when this happens.

          -

          34.2.2 Global Variables

          +

          34.2.2 Global Variables

          @@ -303,7 +307,7 @@ is accessed as follows:

           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.

          -

          34.2.3 Functions

          +

          34.2.3 Functions

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

      34.2.4 Overloading

      +

      34.2.4 Overloading

      @@ -434,7 +438,7 @@ taking the integer argument.

      --> -

      34.2.5 Pointers and References

      +

      34.2.5 Pointers and References

      @@ -579,7 +583,7 @@ PHP in a number of ways: by using unset on an existing variable, or assigning NULL to a variable.

      -

      34.2.6 Structures and C++ classes

      +

      34.2.6 Structures and C++ classes

      @@ -599,10 +603,10 @@ This interface file class Vector { public: - double x,y,z; - Vector(); - ~Vector(); - double magnitude(); + double x,y,z; + Vector(); + ~Vector(); + double magnitude(); }; struct Complex { @@ -611,7 +615,7 @@ struct Complex {

      -Would be used in the following way from PHP5: +Would be used in the following way from PHP:

      @@ -640,13 +644,13 @@ Would be used in the following way from PHP5:
       Member variables and methods are accessed using the -> operator.
       

      -

      34.2.6.1 Using -noproxy

      +

      34.2.6.1 Using -noproxy

      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:

      @@ -666,7 +670,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj);
      -

      34.2.6.2 Constructors and Destructors

      +

      34.2.6.2 Constructors and Destructors

      @@ -707,7 +711,7 @@ the programmer can either reassign the variable or call unset($v)

      -

      34.2.6.3 Static Member Variables

      +

      34.2.6.3 Static Member Variables

      @@ -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"; -

      34.2.6.4 Static Member Functions

      +

      34.2.6.4 Static Member Functions

      @@ -772,7 +776,7 @@ Ko::threats(); -

      34.2.6.5 Specifying Implemented Interfaces

      +

      34.2.6.5 Specifying Implemented Interfaces

      @@ -790,7 +794,7 @@ so: If there are multiple interfaces, just list them separated by commas.

      -

      34.2.7 PHP Pragmas, Startup and Shutdown code

      +

      34.2.7 PHP Pragmas, Startup and Shutdown code

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

      -

      34.3 Cross language polymorphism

      +

      34.3 Cross language polymorphism

      @@ -913,7 +917,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

      -

      34.3.1 Enabling directors

      +

      34.3.1 Enabling directors

      @@ -995,14 +999,14 @@ require("mymodule.php"); class MyFoo extends Foo { function one() { - print "one from php\n"; + print "one from php\n"; } } -

      34.3.2 Director classes

      +

      34.3.2 Director classes

      @@ -1082,7 +1086,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

      -

      34.3.3 Ownership and object destruction

      +

      34.3.3 Ownership and object destruction

      @@ -1138,7 +1142,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

      -

      34.3.4 Exception unrolling

      +

      34.3.4 Exception unrolling

      @@ -1197,7 +1201,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

      -

      34.3.5 Overhead and code bloat

      +

      34.3.5 Overhead and code bloat

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

      -

      34.3.6 Typemaps

      +

      34.3.6 Typemaps

      @@ -1244,7 +1248,7 @@ need to be supported.

      -

      34.3.7 Miscellaneous

      +

      34.3.7 Miscellaneous

      Director typemaps for STL classes are mostly in place, and hence you diff --git a/Doc/Manual/Pike.html b/Doc/Manual/Pike.html index 44c6930f8..22ab4e2a2 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -1,12 +1,13 @@ - + SWIG and Pike + -

      35 SWIG and Pike

      +

      35 SWIG and Pike

        @@ -46,10 +47,10 @@ least, make sure you read the "SWIG Basics" chapter.

        -

        35.1 Preliminaries

        +

        35.1 Preliminaries

        -

        35.1.1 Running SWIG

        +

        35.1.1 Running SWIG

        @@ -94,7 +95,7 @@ can use the -o option:

        $ swig -pike -o pseudonym.c example.i
        -

        35.1.2 Getting the right header files

        +

        35.1.2 Getting the right header files

        @@ -114,7 +115,7 @@ You're looking for files with the names global.h, program.h and so on.

        -

        35.1.3 Using your module

        +

        35.1.3 Using your module

        @@ -129,10 +130,10 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24

      -

      35.2 Basic C/C++ Mapping

      +

      35.2 Basic C/C++ Mapping

      -

      35.2.1 Modules

      +

      35.2.1 Modules

      @@ -143,7 +144,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

      -

      35.2.2 Functions

      +

      35.2.2 Functions

      @@ -168,7 +169,7 @@ exactly as you'd expect it to: (1) Result: 24 -

      35.2.3 Global variables

      +

      35.2.3 Global variables

      @@ -197,7 +198,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -

      35.2.4 Constants and enumerated types

      +

      35.2.4 Constants and enumerated types

      @@ -205,7 +206,7 @@ Enumerated types in C/C++ declarations are wrapped as Pike constants, not as Pike enums.

      -

      35.2.5 Constructors and Destructors

      +

      35.2.5 Constructors and Destructors

      @@ -213,7 +214,7 @@ Constructors are wrapped as create() methods, and destructors are wrapped as destroy() methods, for Pike classes.

      -

      35.2.6 Static Members

      +

      35.2.6 Static Members

      diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index d17dc229c..3b654a6d2 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -1,12 +1,13 @@ - + Preface + -

      1 Preface

      +

      1 Preface

        @@ -35,7 +36,7 @@ -

        1.1 Introduction

        +

        1.1 Introduction

        @@ -58,7 +59,7 @@ has since evolved into a general purpose tool that is used in a wide variety of applications--in fact almost anything where C/C++ programming is involved. -

        1.2 SWIG Versions

        +

        1.2 SWIG Versions

        @@ -70,7 +71,7 @@ An official stable version was released along with the decision to make SWIG license changes and this gave rise to version 2.0.0 in 2010.

        -

        1.3 SWIG License

        +

        1.3 SWIG License

        @@ -86,7 +87,7 @@ under license terms of the user's choice/requirements and at the same time the S source was placed under the GNU General Public License version 3.

        -

        1.4 SWIG resources

        +

        1.4 SWIG resources

        @@ -126,7 +127,7 @@ about this can be obtained at: -

        1.5 Prerequisites

        +

        1.5 Prerequisites

        @@ -151,7 +152,7 @@ However, this isn't meant to be a tutorial on C++ programming. For many of the gory details, you will almost certainly want to consult a good C++ reference. If you don't program in C++, you may just want to skip those parts of the manual. -

        1.6 Organization of this manual

        +

        1.6 Organization of this manual

        @@ -163,7 +164,7 @@ can probably skip to that chapter and find almost everything you need to know.

        -

        1.7 How to avoid reading the manual

        +

        1.7 How to avoid reading the manual

        @@ -175,7 +176,7 @@ The SWIG distribution also comes with a large directory of examples that illustrate different topics.

        -

        1.8 Backwards compatibility

        +

        1.8 Backwards compatibility

        @@ -211,7 +212,7 @@ Note: The version symbol is not defined in the generated SWIG wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.

        -

        1.9 Release notes

        +

        1.9 Release notes

        @@ -220,7 +221,7 @@ contain, respectively, detailed release notes for the current version, detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards.

        -

        1.10 Credits

        +

        1.10 Credits

        @@ -233,7 +234,7 @@ who have made contributions at all levels over time. Contributors are mentioned either in the COPYRIGHT file or CHANGES files shipped with SWIG or in submitted bugs.

        -

        1.11 Bug reports

        +

        1.11 Bug reports

        @@ -248,23 +249,30 @@ used, and any important pieces of the SWIG generated wrapper code. We can only fix bugs if we know about them.

        -

        1.12 Installation

        +

        1.12 Installation

        -

        1.12.1 Windows installation

        +

        1.12.1 Windows installation

        -Please see the dedicated Windows chapter for instructions on installing +Please see the dedicated Windows chapter for instructions on installing SWIG on Windows and running the examples. The Windows distribution is called swigwin and includes a prebuilt SWIG executable, swig.exe, included in the top level directory. Otherwise it is exactly the same as the main SWIG distribution. There is no need to download anything else.

        -

        1.12.2 Unix installation

        +

        1.12.2 Unix installation

        +

        +These installation instructions are for using the distributed tarball, +for example, swig-3.0.8.tar.gz. +If you wish to build and install from source on Github, extra steps are required. +Please see the Bleeding Edge page on the SWIG website. +

        +

        You must use GNU make to build and install SWIG.

        @@ -332,7 +340,7 @@ be configured with a subset of target languages. SWIG used to include a set of runtime libraries for some languages for working with multiple modules. These are no longer built during the installation stage. However, users can build them just like any wrapper module as described in -the Modules chapter. +the Modules chapter. The CHANGES file shipped with SWIG in the top level directory also lists some examples which build the runtime library.

        @@ -350,7 +358,7 @@ a number of packages to be installed. Full instructions at
      -

      1.12.3 Macintosh OS X installation

      +

      1.12.3 Macintosh OS X installation

      @@ -370,7 +378,7 @@ installation of software you might have. However, this is generally not the rec technique for building larger extension modules. Instead, you should utilize Darwin's two-level namespaces. Some details about this can be found here -http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNamespaces.html. +Understanding Two-Level Namespaces.

      @@ -378,7 +386,7 @@ Darwin's two-level namespaces. Some details about this can be found here Needless to say, you might have to experiment a bit to get things working at first.

      -

      1.12.4 Testing

      +

      1.12.4 Testing

      @@ -432,7 +440,7 @@ have many different target languages installed and a slow machine, it might take more than an hour to run the test-suite.

      -

      1.12.5 Examples

      +

      1.12.5 Examples

      diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index e188fc0be..ab32f79c7 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -1,12 +1,13 @@ - + SWIG Preprocessor + -

      8 Preprocessing

      +

      8 Preprocessing

        @@ -37,7 +38,7 @@ However, a number of modifications and enhancements have been made. This chapter describes some of these modifications.

        -

        8.1 File inclusion

        +

        8.1 File inclusion

        @@ -63,7 +64,7 @@ By default, the #include is ignored unless you run SWIG with the is that you often don't want SWIG to try and wrap everything included in standard header system headers and auxiliary files. -

        8.2 File imports

        +

        8.2 File imports

        @@ -92,7 +93,7 @@ The -importall directive tells SWIG to follow all #include sta as imports. This might be useful if you want to extract type definitions from system header files without generating any wrappers. -

        8.3 Conditional Compilation

        +

        8.3 Conditional Compilation

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

        -

        8.4 Macro Expansion

        +

        8.4 Macro Expansion

        @@ -211,7 +214,7 @@ like #x. This is a non-standard SWIG extension.

      -

      8.5 SWIG Macros

      +

      8.5 SWIG Macros

      @@ -224,16 +227,16 @@ For example: %define ARRAYHELPER(type,name) %inline %{ type *new_ ## name (int nitems) { - return (type *) malloc(sizeof(type)*nitems); + return (type *) malloc(sizeof(type)*nitems); } void delete_ ## name(type *t) { - free(t); + free(t); } type name ## _get(type *t, int index) { - return t[index]; + return t[index]; } void name ## _set(type *t, int index, type val) { - t[index] = val; + t[index] = val; } %} %enddef @@ -257,7 +260,7 @@ many of SWIG's advanced features and libraries are built using this mechanism (s support).

      -

      8.6 C99 and GNU Extensions

      +

      8.6 C99 and GNU Extensions

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

      -

      8.7 Preprocessing and delimiters

      +

      8.7 Preprocessing and delimiters

      The preprocessor handles { }, " " and %{ %} delimiters differently.

      -

      8.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      +

      8.7.1 Preprocessing and %{ ... %} & " ... " delimiters

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

      -

      8.7.2 Preprocessing and { ... } delimiters

      +

      8.7.2 Preprocessing and { ... } delimiters

      @@ -357,11 +360,11 @@ file. For example:

       %extend Foo {
      -   void bar() {
      -      #ifdef DEBUG
      -       printf("I'm in bar\n");
      -      #endif
      -   }
      +  void bar() {
      +    #ifdef DEBUG
      +      printf("I'm in bar\n");
      +    #endif
      +  }
       }
       
      @@ -374,11 +377,11 @@ to actually go into the wrapper file, prefix the preprocessor directives with
       %extend Foo {
      -   void bar() {
      -      %#ifdef DEBUG
      -       printf("I'm in bar\n");
      -      %#endif
      -   }
      +  void bar() {
      +    %#ifdef DEBUG
      +      printf("I'm in bar\n");
      +    %#endif
      +  }
       }
       
      @@ -387,7 +390,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.

      -

      8.8 Preprocessor and Typemaps

      +

      8.8 Preprocessor and Typemaps

      @@ -458,7 +461,7 @@ would generate

      -

      8.9 Viewing preprocessor output

      +

      8.9 Viewing preprocessor output

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

      -

      8.10 The #error and #warning directives

      +

      8.10 The #error and #warning directives

      diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 57a2cd3ef..cb847c074 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -1,12 +1,13 @@ - + SWIG and Python + -

      36 SWIG and Python

      +

      36 SWIG and Python

      @@ -143,7 +157,7 @@ very least, make sure you read the "SWIG Basics" chapter.

      -

      36.1 Overview

      +

      36.1 Overview

      @@ -170,10 +184,10 @@ described followed by a discussion of low-level implementation details.

      -

      36.2 Preliminaries

      +

      36.2 Preliminaries

      -

      36.2.1 Running SWIG

      +

      36.2.1 Running SWIG

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

      -

      36.2.2 Using distutils

      +

      36.2.2 Using distutils

      The preferred approach to building an extension module for python is to compile it with distutils, which comes with all recent versions of python -(Distutils Docs). +(Distutils Docs).

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

      -

      36.2.3 Hand compiling a dynamic module

      +

      36.2.3 Hand compiling a dynamic module

      @@ -411,7 +425,7 @@ module actually consists of two files; socket.py and

      -

      36.2.4 Static linking

      +

      36.2.4 Static linking

      @@ -456,14 +470,14 @@ you simply do something like this:

      -$ swig -python example.i
      +$ swig -python -lembed.i example.i
       $ gcc example.c example_wrap.c \
               -Xlinker -export-dynamic \
      -        -DHAVE_CONFIG_H -I/usr/local/include/python2.1 \
      -	-I/usr/local/lib/python2.1/config \
      -	-L/usr/local/lib/python2.1/config -lpython2.1 -lm -ldl \
      -	-o mypython
      -
      +        -DHAVE_CONFIG_H -I/usr/include/python2.7 \
      +        -I/usr/lib/python2.7/config-x86_64-linux-gnu \
      +        -I/usr/lib/python2.7/config \
      +        -L/usr/lib/python2.7/config -lpython2.7 -lm -ldl \
      +        -o mypython
       

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

      -

      36.2.5 Using your module

      +

      36.2.5 Using your module

      To use your module, simply use the Python import statement. If -all goes well, you will be able to this: +all goes well, you will be able to run this:

      @@ -647,7 +661,7 @@ system configuration (this requires root access and you will need to
       read the man pages).
       

      -

      36.2.6 Compilation of C++ extensions

      +

      36.2.6 Compilation of C++ extensions

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

      -

      36.2.7 Compiling for 64-bit platforms

      +

      36.2.7 Compiling for 64-bit platforms

      @@ -776,7 +790,7 @@ and -m64 allow you to choose the desired binary format for your python extension.

      -

      36.2.8 Building Python Extensions under Windows

      +

      36.2.8 Building Python Extensions under Windows

      @@ -905,7 +919,7 @@ SWIG Wiki.

      -

      36.3 A tour of basic C/C++ wrapping

      +

      36.3 A tour of basic C/C++ wrapping

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

      -

      36.3.1 Modules

      +

      36.3.1 Modules

      @@ -927,7 +941,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.

      -

      36.3.2 Functions

      +

      36.3.2 Functions

      @@ -951,7 +965,7 @@ like you think it does: >>>

      -

      36.3.3 Global variables

      +

      36.3.3 Global variables

      @@ -1089,7 +1103,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

      -

      36.3.4 Constants and enums

      +

      36.3.4 Constants and enums

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

      -

      36.3.5 Pointers

      +

      36.3.5 Pointers

      @@ -1155,7 +1169,7 @@ When wrapped, you will be able to use the functions in a natural way from Python

       >>> import example
      ->>> f = example.fopen("junk","w")
      +>>> f = example.fopen("junk", "w")
       >>> example.fputs("Hello World\n", f)
       >>> example.fclose(f)
       
      @@ -1248,12 +1262,12 @@ consider writing some helper functions instead. For 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) { @@ -1270,7 +1284,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

      -

      36.3.6 Structures

      +

      36.3.6 Structures

      @@ -1280,7 +1294,7 @@ a very natural interface. For example,

       struct Vector {
      -	double x,y,z;
      +  double x,y,z;
       };
       
       
      @@ -1341,12 +1355,12 @@ can also be forced to be read-only using the %immutable directive. For
       struct Foo {
      -   ...
      -   %immutable;
      -   int x;        /* Read-only members */
      -   char *name;
      -   %mutable;
      -   ...
      +  ...
      +  %immutable;
      +  int x;        /* Read-only members */
      +  char *name;
      +  %mutable;
      +  ...
       };
       
      @@ -1413,11 +1427,11 @@ pointer. For example, suppose you have two structures like this:
       struct Foo {
      -   int a;
      +  int a;
       };
       
       struct Bar {
      -   Foo f;
      +  Foo f;
       };
       
      @@ -1459,7 +1473,7 @@ everything works just like you would expect. For example:
      -

      36.3.7 C++ classes

      +

      36.3.7 C++ classes

      @@ -1511,9 +1525,8 @@ suppose you have a class like this:

       class Spam {
       public:
      -   static void foo();
      -   static int bar;
      -
      +  static void foo();
      +  static int bar;
       };
       
      @@ -1548,7 +1561,7 @@ they are accessed through cvar like this: -

      36.3.8 C++ inheritance

      +

      36.3.8 C++ inheritance

      @@ -1603,7 +1616,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

      -

      36.3.9 Pointers, references, values, and arrays

      +

      36.3.9 Pointers, references, values, and arrays

      @@ -1664,7 +1677,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.

      -

      36.3.10 C++ overloaded functions

      +

      36.3.10 C++ overloaded functions

      @@ -1787,7 +1800,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      36.3.11 C++ operators

      +

      36.3.11 C++ operators

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

      -

      36.3.12 C++ namespaces

      +

      36.3.12 C++ namespaces

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

      -

      36.3.13 C++ templates

      +

      36.3.13 C++ templates

      @@ -1962,13 +1975,13 @@ 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&); - ~pair(); + typedef T1 first_type; + typedef T2 second_type; + T1 first; + T2 second; + pair(); + pair(const T1&, const T2&); + ~pair(); }; %template(pairii) pair<int,int>; @@ -1997,7 +2010,21 @@ Some more complicated examples will appear later.

      -

      36.3.14 C++ Smart Pointers

      +

      36.3.14 C++ Smart Pointers

      + + +

      36.3.14.1 The shared_ptr Smart Pointer

      + + +

      +The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Python in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +

      + + +

      36.3.14.2 Generic Smart Pointers

      @@ -2009,9 +2036,9 @@ that implements operator->() like this:

       template<class T> class SmartPtr {
      -   ...
      -   T *operator->();
      -   ...
      +  ...
      +  T *operator->();
      +  ...
       }
       
      @@ -2024,8 +2051,8 @@ Then, if you have a class like this,
       class Foo {
       public:
      -     int x;
      -     int bar();
      +  int x;
      +  int bar();
       };
       
      @@ -2081,7 +2108,7 @@ simply use the __deref__() method. For example: -

      36.3.15 C++ reference counted objects

      +

      36.3.15 C++ reference counted objects

      @@ -2090,7 +2117,7 @@ Python examples of memory management using referencing counting.

      -

      36.4 Further details on the Python class interface

      +

      36.4 Further details on the Python class interface

      @@ -2113,7 +2140,7 @@ the -builtin option are in the Built-in section.

      -

      36.4.1 Proxy classes

      +

      36.4.1 Proxy classes

      @@ -2126,9 +2153,9 @@ have a class like this

       class Foo {
       public:
      -     int x;
      -     int spam(int);
      -     ...
      +    int x;
      +    int spam(int);
      +    ...
       
      @@ -2202,7 +2229,7 @@ you can attach new Python methods to the class and you can even inherit from it by Python built-in types until Python 2.2).

      -

      36.4.2 Built-in Types

      +

      36.4.2 Built-in Types

      @@ -2246,7 +2273,7 @@ please refer to the python documentation:

      http://docs.python.org/extending/newtypes.html

      -

      36.4.2.1 Limitations

      +

      36.4.2.1 Limitations

      Use of the -builtin option implies a couple of limitations: @@ -2414,7 +2441,7 @@ assert(issubclass(B.Derived, A.Base)) -

      36.4.2.2 Operator overloads -- use them!

      +

      36.4.2.2 Operator overloads and slots -- use them!

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

      +Read about all of the available python slots here: +http://docs.python.org/c-api/typeobj.html

      + +

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

      -%feature("python:slot", "tp_hash", functype="hashfunc") Cheese::cheeseHashFunc;
      +%feature("python:tp_hash") MyClass "myHashFunc";
       
      -class Cheese {
      +class MyClass {
       public:
      -    Cheese (const char *name);
      -    long cheeseHashFunc () const;
      +  long field1;
      +  long field2;
      +  ...
      +};
      +
      +%{
      +#if PY_VERSION_HEX >= 0x03020000
      +  static Py_hash_t myHashFunc(PyObject *pyobj)
      +#else
      +  static long myHashFunc(PyObject *pyobj)
      +#endif
      +  {
      +    MyClass *cobj;
      +    // Convert pyobj to cobj
      +    return (cobj->field1 * (cobj->field2 << 7));
      +  }
      +%}
      +
      +
      + +

      +If you examine the generated code, the supplied hash function will now be +the function callback in the tp_hash slot for the builtin type for MyClass: +

      + +
      +
      +static PyHeapTypeObject SwigPyBuiltin__MyClass_type = {
      +    ...
      +    (hashfunc) myHashFunc,       /* tp_hash */
      +    ...
      +
      +
      + +

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

      + +
      +
      +%feature("python:slot", "tp_hash", functype="hashfunc") MyClass::myHashFunc;
      +
      +#if PY_VERSION_HEX < 0x03020000
      +  #define Py_hash_t long
      +#endif
      +
      +class MyClass {
      +  public:
      +    Py_hash_t myHashFunc() const;
      +    ...
       };
       
      -

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

      -
      -
      -from my MyPackage import Cheese
      -
      -inventory = {
      -    Cheese("cheddar") : 0,
      -    Cheese("gouda") : 0,
      -    Cheese("camembert") : 0
      -}
      -
      -
      - -

      Because you defined the tp_hash slot, Cheese objects may -be used as hash keys; and when the cheeseHashFunc method is invoked -by a python dict, it will not go through named method dispatch. -A more detailed discussion about %feature("python:slot") can be found +

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

      - -

      http://docs.python.org/c-api/typeobj.html

      - -

      You may override (almost) all of the slots defined in the PyTypeObject, -PyNumberMethods, PyMappingMethods, PySequenceMethods, and PyBufferProcs -structs.

      -

      36.4.3 Memory management

      +

      36.4.3 Memory management

      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:

       class Node {
      -   Object *value;
      +  Object *value;
       public:
      -   void set_value(Object *v) { value = v; }
      -   ...
      +  void set_value(Object *v) { value = v; }
      +  ...
       };
       
      @@ -2710,7 +2795,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

      -

      36.4.4 Python 2.2 and classic classes

      +

      36.4.4 Python 2.2 and classic classes

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

      -

      36.5 Cross language polymorphism

      +

      36.5 Cross language polymorphism

      @@ -2781,7 +2866,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      36.5.1 Enabling directors

      +

      36.5.1 Enabling directors

      @@ -2873,7 +2958,7 @@ class MyFoo(mymodule.Foo): -

      36.5.2 Director classes

      +

      36.5.2 Director classes

      @@ -2955,7 +3040,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

      -

      36.5.3 Ownership and object destruction

      +

      36.5.3 Ownership and object destruction

      @@ -3022,7 +3107,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

      -

      36.5.4 Exception unrolling

      +

      36.5.4 Exception unrolling

      @@ -3081,7 +3166,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

      -

      36.5.5 Overhead and code bloat

      +

      36.5.5 Overhead and code bloat

      @@ -3115,7 +3200,7 @@ directive) for only those methods that are likely to be extended in Python.

      -

      36.5.6 Typemaps

      +

      36.5.6 Typemaps

      @@ -3129,7 +3214,7 @@ need to be supported.

      -

      36.5.7 Miscellaneous

      +

      36.5.7 Miscellaneous

      @@ -3176,7 +3261,7 @@ methods that return const references.

      -

      36.6 Common customization features

      +

      36.6 Common customization features

      @@ -3189,7 +3274,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

      -

      36.6.1 C/C++ helper functions

      +

      36.6.1 C/C++ helper functions

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

      -

      36.6.2 Adding additional Python code

      +

      36.6.2 Adding additional Python code

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

      -

      36.6.3 Class extension with %extend

      +

      36.6.3 Class extension with %extend

      @@ -3539,22 +3624,22 @@ Here is a simple example: %} struct Vector { - double x,y,z; + double x,y,z; }; %extend Vector { - char *__str__() { - static char tmp[1024]; - sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z); - return tmp; - } - Vector(double x, double y, double z) { - Vector *v = (Vector *) malloc(sizeof(Vector)); - v->x = x; - v->y = y; - v->z = z; - return v; - } + char *__str__() { + static char tmp[1024]; + sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z); + return tmp; + } + Vector(double x, double y, double z) { + Vector *v = (Vector *) malloc(sizeof(Vector)); + v->x = x; + v->y = y; + v->z = z; + return v; + } }; @@ -3580,13 +3665,13 @@ For example, if you wanted to overload a Python operator, you might do this:

       %extend Vector {
      -    Vector __add__(Vector *other) {
      -         Vector v;
      -         v.x = $self->x + other->x;
      -         v.y = $self->y + other->y;
      -         v.z = $self->z + other->z;
      -         return v;
      -    }
      +  Vector __add__(Vector *other) {
      +    Vector v;
      +    v.x = $self->x + other->x;
      +    v.y = $self->y + other->y;
      +    v.z = $self->z + other->z;
      +    return v;
      +  }
       };
       
      @@ -3611,7 +3696,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.

      -

      36.6.4 Exception handling with %exception

      +

      36.6.4 Exception handling with %exception

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

       %exception {
      -   $action
      -   if (err_occurred()) {
      -      PyErr_SetString(PyExc_RuntimeError, err_message());
      -      return NULL;
      -   }
      +  $action
      +  if (err_occurred()) {
      +    PyErr_SetString(PyExc_RuntimeError, err_message());
      +    SWIG_fail;
      +  }
       }
       
      @@ -3680,25 +3765,26 @@ C++ exceptions are also easy to handle. For example, you can write code like th
       %exception getitem {
      -   try {
      -      $action
      -   } catch (std::out_of_range &e) {
      -      PyErr_SetString(PyExc_IndexError, const_cast<char*>(e.what()));
      -      return NULL;
      -   }
      +  try {
      +    $action
      +  } catch (std::out_of_range &e) {
      +    PyErr_SetString(PyExc_IndexError, const_cast<char*>(e.what()));
      +    SWIG_fail;
      +  }
       }
       
       class Base {
       public:
      -     Foo *getitem(int index);      // Exception handled added
      -     ...
      +  Foo *getitem(int index);      // Exception handled added
      +  ...
       };
       

      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.

      -

      36.7 Tips and techniques

      +

      36.7 Tips and techniques

      @@ -3747,7 +3840,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

      -

      36.7.1 Input and output parameters

      +

      36.7.1 Input and output parameters

      @@ -3758,7 +3851,7 @@ example:

       void add(int x, int y, int *result) {
      -   *result = x + y;
      +  *result = x + y;
       }
       
      @@ -3770,7 +3863,7 @@ or perhaps
       int sub(int *x, int *y) {
      -   return *x-*y;
      +  return *x-*y;
       }
       
      @@ -3835,7 +3928,7 @@ If a function mutates one of its parameters like this,
       void negate(int *x) {
      -   *x = -(*x);
      +  *x = -(*x);
       }
       
      @@ -3960,7 +4053,7 @@ void foo(Bar *OUTPUT); may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

      -

      36.7.2 Simple pointers

      +

      36.7.2 Simple pointers

      @@ -4029,7 +4122,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.

      -

      36.7.3 Unbounded C Arrays

      +

      36.7.3 Unbounded C Arrays

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

      -

      36.7.4 String handling

      +

      36.7.4 String handling

      @@ -4161,12 +4254,12 @@ also be used to extra binary data from arbitrary pointers.

      -

      36.7.5 Default arguments

      +

      36.7.5 Default arguments

      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:cdefaultargs feature 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.

      -

      36.8 Typemaps

      +

      36.8 Typemaps

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

      -

      36.8.1 What is a typemap?

      +

      36.8.1 What is a typemap?

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

      36.8.2 Python typemaps

      +

      36.8.2 Python typemaps

      @@ -4434,7 +4527,7 @@ a look at the SWIG library version 1.3.20 or so.

      -

      36.8.3 Typemap variables

      +

      36.8.3 Typemap variables

      @@ -4505,7 +4598,7 @@ properly assigned. The Python name of the wrapper function being created.

      -

      36.8.4 Useful Python Functions

      +

      36.8.4 Useful Python Functions

      @@ -4633,7 +4726,7 @@ write me -

      36.9 Typemap Examples

      +

      36.9 Typemap Examples

      @@ -4642,7 +4735,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

      -

      36.9.1 Converting Python list to a char **

      +

      36.9.1 Converting Python list to a char **

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

      +

      36.9.2 Expanding a Python object into multiple arguments

      @@ -4743,7 +4836,7 @@ allows the function to be used from Python as follows:

      ->>> foo(4, ["foo","bar","spam","1"])
      +>>> foo(4, ["foo", "bar", "spam", "1"])
       
      @@ -4763,18 +4856,18 @@ previous example: $2 = (char **) malloc(($1+1)*sizeof(char *)); for (i = 0; i < $1; i++) { PyObject *o = PyList_GetItem($input,i); - if (PyString_Check(o)) - $2[i] = PyString_AsString(PyList_GetItem($input,i)); - else { - PyErr_SetString(PyExc_TypeError,"list must contain strings"); - free($2); - return NULL; + if (PyString_Check(o)) { + $2[i] = PyString_AsString(PyList_GetItem($input,i)); + } else { + free($2); + PyErr_SetString(PyExc_TypeError,"list must contain strings"); + SWIG_fail; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); - return NULL; + SWIG_fail; } } @@ -4797,11 +4890,51 @@ to supply the argument count. This is automatically set by the typemap code. F
      ->>> foo(["foo","bar","spam","1"])
      +>>> foo(["foo", "bar", "spam", "1"])
       
      -

      36.9.3 Using typemaps to return arguments

      +

      +If your function is overloaded in C++, for example: +

      + +
      +
      +int foo(int argc, char **argv);
      +int foo();
      +
      +
      + +

      +don't forget to also provide a suitable typecheck typemap for overloading +such as: +

      + +
      +
      +%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char **argv) {
      +  $1 = PyList_Check($input) ? 1 : 0;
      +}
      +
      +
      + +

      +If you don't you'll get an error message along the lines of: +

      + +
      +
      +Traceback (most recent call last):
      +  File "runme.py", line 3, in >module<
      +    example.foo(["foo", "bar", "spam", "1"])
      +NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'.
      +  Possible C/C++ prototypes are:
      +    foo(int,char **)
      +    foo()
      +
      +
      + +

      36.9.3 Using typemaps to return arguments

      @@ -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:
       %typemap(in,numinputs=0) double *OutValue(double temp) {
      -    $1 = &temp;
      +  $1 = &temp;
       }
       
       
      @@ -4889,7 +5022,7 @@ function can now be used as follows: >>>
      -

      36.9.4 Mapping Python tuples into small arrays

      +

      36.9.4 Mapping Python tuples into small arrays

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

      -

      36.9.5 Mapping sequences to C arrays

      +

      36.9.5 Mapping sequences to C arrays

      @@ -4951,22 +5084,22 @@ arrays of different sizes. To do this, you might write a typemap as follows: %typemap(in) double[ANY](double temp[$1_dim0]) { int i; if (!PySequence_Check($input)) { - PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); - return NULL; + PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); + SWIG_fail; } if (PyObject_Length($input) != $1_dim0) { - PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements"); - return NULL; + PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements"); + SWIG_fail; } for (i =0; i < $1_dim0; i++) { - PyObject *o = PySequence_GetItem($input,i); - if (!PyFloat_Check(o)) { - Py_XDECREF(o); - PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); - return NULL; - } - temp[i] = PyFloat_AsDouble(o); - Py_DECREF(o); + PyObject *o = PySequence_GetItem($input,i); + if (!PyFloat_Check(o)) { + Py_XDECREF(o); + PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); + SWIG_fail; + } + temp[i] = PyFloat_AsDouble(o); + Py_DECREF(o); } $1 = &temp[0]; } @@ -4997,37 +5130,37 @@ to use a helper function instead. This will greatly reduce the amount of wrappe static int convert_darray(PyObject *input, double *ptr, int size) { int i; if (!PySequence_Check(input)) { - PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); - return 0; + PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); + return 0; } if (PyObject_Length(input) != size) { - PyErr_SetString(PyExc_ValueError,"Sequence size mismatch"); - return 0; + PyErr_SetString(PyExc_ValueError,"Sequence size mismatch"); + return 0; } for (i =0; i < size; i++) { - PyObject *o = PySequence_GetItem(input,i); - if (!PyFloat_Check(o)) { - Py_XDECREF(o); - PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); - return 0; - } - ptr[i] = PyFloat_AsDouble(o); - Py_DECREF(o); + PyObject *o = PySequence_GetItem(input,i); + if (!PyFloat_Check(o)) { + Py_XDECREF(o); + PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); + return 0; + } + ptr[i] = PyFloat_AsDouble(o); + Py_DECREF(o); } return 1; } %} %typemap(in) double [ANY](double temp[$1_dim0]) { - if (!convert_darray($input,temp,$1_dim0)) { - return NULL; - } - $1 = &temp[0]; + if (!convert_darray($input,temp,$1_dim0)) { + SWIG_fail; + } + $1 = &temp[0]; } -

      36.9.6 Pointer handling

      +

      36.9.6 Pointer handling

      @@ -5075,8 +5208,9 @@ is usually accessed as follows:

       Foo *f;
      -if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, SWIG_POINTER_EXCEPTION) == -1)
      -  return NULL;
      +if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0))) {
      +  SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +}
       
       PyObject *obj;
       obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
      @@ -5091,8 +5225,9 @@ variable $1_descriptor.  For example:
       
       %typemap(in) Foo * {
      -if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,SWIG_POINTER_EXCEPTION)) == -1)
      -  return NULL;
      +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) {
      +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +  }
       }
       
      @@ -5105,9 +5240,9 @@ For example:
       %typemap(in) Foo * {
      -if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 
      -                                               SWIG_POINTER_EXCEPTION)) == -1)
      -  return NULL;
      +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $descriptor(Foo *), 0))) {
      +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +  }
       }
       
      @@ -5124,7 +5259,7 @@ class object (if applicable). -

      36.10 Docstring Features

      +

      36.10 Docstring Features

      @@ -5152,7 +5287,7 @@ of your users much simpler.

      -

      36.10.1 Module docstring

      +

      36.10.1 Module docstring

      @@ -5186,7 +5321,7 @@ layout of controls on a panel, etc. to be loaded from an XML file."

      -

      36.10.2 %feature("autodoc")

      +

      36.10.2 %feature("autodoc")

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

      36.10.2.1 %feature("autodoc", "0")

      +

      36.10.2.1 %feature("autodoc", "0")

      @@ -5243,7 +5378,7 @@ def function_name(*args, **kwargs): -

      36.10.2.2 %feature("autodoc", "1")

      +

      36.10.2.2 %feature("autodoc", "1")

      @@ -5268,13 +5403,13 @@ def function_name(*args, **kwargs): -

      36.10.2.3 %feature("autodoc", "2")

      +

      36.10.2.3 %feature("autodoc", "2")

      Level "2" results in the function prototype as per level "0". In addition, a line of -documentation is generated for each parameter. Using the previous example, the generated -code will be: +documentation is generated for each parameter using numpydoc style. +Using the previous example, the generated code will be:

      @@ -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 *
       
           """
       
      -

      36.10.2.4 %feature("autodoc", "3")

      +

      36.10.2.4 %feature("autodoc", "3")

      @@ -5341,11 +5478,12 @@ def function_name(*args, **kwargs): """ function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool - Parameters: - x: int - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x: int + y: int + foo: Foo * + bar: Bar * """ ... @@ -5353,7 +5491,7 @@ def function_name(*args, **kwargs):

      -

      36.10.2.5 %feature("autodoc", "docstring")

      +

      36.10.2.5 %feature("autodoc", "docstring")

      @@ -5372,7 +5510,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

      36.10.3 %feature("docstring")

      +

      36.10.3 %feature("docstring")

      @@ -5404,7 +5542,7 @@ with more than one line. -

      36.11 Python Packages

      +

      36.11 Python Packages

      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.

      -

      36.11.1 Setting the Python package

      +

      36.11.1 Setting the Python package

      @@ -5516,7 +5671,7 @@ pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWI -

      36.11.2 Absolute and relative imports

      +

      36.11.2 Absolute and relative imports

      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

      @@ -5631,22 +5787,17 @@ import pkg1.pkg2.mod3 write

      -
      -import pkg2.mod3
      +  
      +from sys import version_info
      +if version_info >= (2, 7, 0):
      +    from . import pkg2
      +    import pkg1.pkg2.mod3
      +else:
      +    import pkg2.mod3
      +del version_info
       
      -

      if -py3 is not used, or

      - -
      -
      -from . import pkg2
      -import pkg1.pkg2.mod3
      -
      -
      - -

      when -py3 is used.

      -

      You should avoid using relative imports and use absolute ones whenever possible. There are some cases, however, when relative imports may be necessary. The first example is, when some (legacy) Python code refers entities @@ -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).

      -

      36.11.3 Enforcing absolute import semantics

      +

      36.11.3 Enforcing absolute import semantics

      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 -

      36.11.4 Importing from __init__.py

      +

      36.11.4 Importing from __init__.py

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

      +

      36.11.5 Implicit Namespace Packages

      -

      36.12 Python 3 Support

      + +

      Python 3.3 introduced +PEP 0420 which +implements implicit namespace packages. In a nutshell, implicit namespace +packages remove the requirement of an __init__.py file and allow packages +to be split across multiple PATH elements. For example: +

      + +
      +
      +/fragment1/pkg1/mod1.py
      +/fragment2/pkg1/mod2.py
      +/fragment3/pkg1/mod3.py
      +
      +
      + +

      If PYTHONPATH is set to "/fragment1:/fragment2:/fragment3", then mod1, mod2 +and mod3 will be part of pkg1. This allows for splitting of packages into +separate pieces. This can be useful for SWIG generated wrappers in the +following way. +

      + +

      Suppose you create a SWIG wrapper for a module called robin. The SWIG +generated code consists of two files robin.py and _robin.so. You wish to +make these modules part of a subpackage (brave.sir). With implicit namespace +packages you can place these files in the following configurations: +

      + +

      Using PYTHONPATH="/some/path"

      +
      +
      +/some/path/brave/sir/robin.py
      +/some/path/brave/sir/_robin.so
      +
      +
      + +

      Using PYTHONPATH="/some/path:/some/other/path" + +

      +
      +/some/path/brave/sir/robin.py
      +/some/other/path/brave/sir/_robin.so
      +
      +
      + +

      Finally suppose that your pure python code is stored in a .zip file or +some other way (database, web service connection, etc). Python can load the +robin.py module using a custom importer. But the _robin.so module will need +to be located on a file system. Implicit namespace packages make this +possible. For example, using PYTHONPATH="/some/path/foo.zip:/some/other/path" + +

      Contents of foo.zip

      +
      +
      +brave/
      +brave/sir/
      +brave/sir/robin.py
      +
      +
      + +

      File system contents

      +
      +
      +/some/other/path/brave/sir/_robin.so
      +
      +
      + +

      Support for implicit namespace packages was added to python-3.3. The +zipimporter requires python-3.5.1 or newer to work with subpackages. +

      + +

      +Compatibility Note: Support for implicit namespace packages was added in SWIG-3.0.9. +

      + + +

      36.11.6 Searching for the wrapper module

      + + +

      +When SWIG creates wrappers from an interface file, say foo.i, two Python modules are +created. There is a pure Python module module (foo.py) and C/C++ code which is +built and linked into a dynamically (or statically) loaded 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: +

      + +
        +
      1. The pure Python module, foo.py, tries to load the C/C++ module, _foo, from the same package foo.py is + located in. The package name is determined from the __name__ + attribute given to foo.py by the Python loader that imported + foo.py. If foo.py is not in a package then _foo is loaded + as a global module.

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

        +
      4. +
      + +

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

      + +
      +
      +%define MODULEIMPORT
      +"
      +print 'Loading low-level module $module'
      +import $module
      +print 'Module has loaded'
      +"
      +%enddef
      +
      +%module(moduleimport=MODULEIMPORT) foo
      +
      +
      + + +

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

      + + +

      36.11.6.1 Both modules in the same package

      + + +

      Both modules are in one package:

      +
      +
      +/dir/package/foo.py
      +/dir/package/__init__.py
      +/dir/package/_foo.so
      +
      +
      +

      And imported with

      +
      +
      +from package import foo
      +
      +
      + + +

      36.11.6.2 Split modules

      + + +

      The pure python module is in a package and the C/C++ module is global:

      +
      +
      +/dir/package/foo.py
      +/dir/package/__init__.py
      +/dir/_foo.so
      +
      +
      +

      And imported with

      +
      +
      +from package import foo
      +
      +
      + + +

      36.11.6.3 Both modules are global

      + + +

      Both modules are global:

      +
      +
      +/dir/foo.py
      +/dir/_foo.so
      +
      +
      +

      And imported with

      +
      +
      +import foo
      +
      +
      + +

      +If _foo is statically linked into an embedded Python interpreter, then it may or +may not be in a Python package. This depends in the exact way the module was +loaded statically. The above search order will still be used for statically +loaded modules. So, one may place the module either globally or in a package +as desired. +

      + +

      36.11.6.4 Statically linked C modules

      + + +

      It is strongly recommended to use dynamically linked modules for the C +portion of your pair of Python modules. +If for some reason you still need +to link the C module of the pair of Python modules generated by SWIG into +your interpreter, then this section provides some details on how this impacts +the pure Python modules ability to locate the other part of the pair. +Please also see the Static Linking section. +

      + +

      When Python is extended with C code the Python interpreter needs to be +informed about details of the new C functions that have been linked into +the executable. The code to do this is created by SWIG and is automatically +called in the correct way when the module is dynamically loaded. However +when the code is not dynamically loaded (because it is statically linked) +Then the initialization method for the module created by SWIG is not +called automatically and the Python interpreter has no idea that the +new SWIG C module exists. +

      + +

      Before Python 3, one could simply call the init method created by SWIG +which would have normally been called when the shared object was dynamically +loaded. The specific name of this method is not given here because statically +linked modules are not encouraged with SWIG +(Static Linking). However one can find this +init function in the C file generated by SWIG. +

      + +

      If you are really keen on static linking there are two ways +to initialize the SWIG generated C module with the init method. Which way +you use depends on what version of Python your module is being linked with. +Python 2 and Python 3 treat this init function differently. And the way +they treat it affects how the pure Python module will be able to +locate the C module. +

      + +

      The details concerning this are covered completly in the documentation +for Python itself. Links to the relavent sections follow: +

      + + + +

      There are two keys things to understand. The first is that in +Python 2 the init() function returns void. In Python 3 the init() function +returns a PyObject * which points to the new module. Secondly, when +you call the init() method manually, you are the Python importer. So, you +determine which package the C module will be located in. +

      + +

      So, if you are using Python 3 it is important that you follow what is +described in the Python documentation linked above. In particular, you can't +simply call the init() function generated by SWIG and cast the PyObject +pointer it returns over the side. If you do then Python 3 will have no +idea that your C module exists and the pure Python half of your wrapper will +not be able to find it. You need to register your module with the Python +interpreter as described in the Python docs. +

      + +

      With Python 2 things are somewhat more simple. In this case the init function +returns void. Calling it will register your new C module as a global +module. The pure Python part of the SWIG wrapper will be able to find it +because it tries both the pure Python module it is part of and the global +module. If you wish not to have the statically linked module be a global +module then you will either need to refer to the Python documentation on how +to do this (remember you are now the Python importer) or use dynamic linking. +

      + +

      36.12 Python 3 Support

      @@ -5830,7 +6268,7 @@ The following are Python 3.0 new features that are currently supported by SWIG.

      -

      36.12.1 Function annotation

      +

      36.12.1 Function annotation

      @@ -5860,10 +6298,10 @@ all overloaded functions share the same function in SWIG generated proxy class.

      For detailed usage of function annotation, see -PEP 3107. +PEP 3107.

      -

      36.12.2 Buffer interface

      +

      36.12.2 Buffer interface

      @@ -6015,7 +6453,7 @@ modify the buffer. -

      36.12.3 Abstract base classes

      +

      36.12.3 Abstract base classes

      @@ -6053,10 +6491,10 @@ used to define an abstract base class for your own C++ class:

      For details of abstract base class, please see -PEP 3119. +PEP 3119.

      -

      36.12.4 Byte string output conversion

      +

      36.12.4 Byte string output conversion

      @@ -6139,7 +6577,157 @@ in Python 3 code.

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

      + +
      +%module char_to_bytes
      +%begin %{
      +#define SWIG_PYTHON_STRICT_BYTE_CHAR
      +%}
      +
      +char *charstring(char *s) {
      +  return s;
      +}
      +
      + +

      +This will modify the behavior so that only Python 3 bytes objects will be +accepted and converted to a C/C++ string, and any string returned from C/C++ +will be converted to a bytes object in Python 3: +

      + +
      +>>> from char_to_bytes import *
      +>>> charstring(b"hi") # Byte string
      +b'hi'
      +>>> charstring("hi")  # Unicode string
      +Traceback (most recent call last):
      +  File "<stdin>", line 1, in ?
      +TypeError: in method 'charstring', argument 1 of type 'char *'
      +
      + +

      +Note that in Python 2, defining SWIG_PYTHON_STRICT_BYTE_CHAR has no +effect, since strings in Python 2 are equivalent to Python 3 bytes objects. +However, there is a similar capability to force unicode-only handling for +wide characters C/C++ strings (wchar_t * or std::wstring +types) in Python 2. By default, in Python 2 both strings and unicode strings +are converted to C/C++ wide strings, and returned wide strings are converted +to a Python unicode string. To instead only convert unicode strings to wide +strings, users can add SWIG_PYTHON_STRICT_UNICODE_WCHAR to the +generated code: +

      + +
      +%module wchar_to_unicode
      +%begin %{
      +#define SWIG_PYTHON_STRICT_UNICODE_WCHAR
      +%}
      +
      +wchar_t *wcharstring(wchar_t *s) {
      +  return s;
      +}
      +
      + +

      +This ensures that only unicode strings are accepted by wcharstring in both +Python 2 and Python 3: +

      + +
      +>>> from wchar_to_unicode import *
      +>>> wcharstring(u"hi") # Unicode string
      +u'hi'
      +>>> wcharstring(b"hi") # Byte string
      +Traceback (most recent call last):
      +  File "<stdin>", line 1, in ?
      +TypeError: in method 'charstring', argument 1 of type 'wchar_t *'
      +
      + +

      +By defining both SWIG_PYTHON_STRICT_BYTE_CHAR and +SWIG_PYTHON_STRICT_UNICODE_WCHAR, Python wrapper code can support +overloads taking both std::string (as Python bytes) and std::wstring +(as Python unicode). +

      + +

      36.12.5 Python 2 Unicode

      + + +

      +A Python 3 string is a Unicode string so by default a Python 3 string that contains Unicode +characters passed to C/C++ will be accepted and converted to a C/C++ string +(char * or std::string types). +A Python 2 string is not a unicode string by default and should a Unicode string be +passed to C/C++ it will fail to convert to a C/C++ string +(char * or std::string types). +The Python 2 behavior can be made more like Python 3 by defining +SWIG_PYTHON_2_UNICODE when compiling the generated C/C++ code. +By default when the following is wrapped: +

      + +
      +%module unicode_strings
      +char *charstring(char *s) {
      +  return s;
      +}
      +
      + +

      +An error will occur when using Unicode strings in Python 2: +

      + +
      +>>> from unicode_strings import *
      +>>> charstring("hi")
      +'hi'
      +>>> charstring(u"hi")
      +Traceback (most recent call last):
      +  File "<stdin>", line 1, in ?
      +TypeError: in method 'charstring', argument 1 of type 'char *'
      +
      + +

      +When the SWIG_PYTHON_2_UNICODE macro is added to the generated code: +

      + +
      +%module unicode_strings
      +%begin %{
      +#define SWIG_PYTHON_2_UNICODE
      +%}
      +
      +char *charstring(char *s) {
      +  return s;
      +}
      +
      + +

      +Unicode strings will be successfully accepted and converted from UTF-8, +but note that they are returned as a normal Python 2 string: +

      + +
      +>>> from unicode_strings import *
      +>>> charstring("hi")
      +'hi'
      +>>> charstring(u"hi")
      +'hi'
      +>>>
      +
      + +

      +Note that defining both SWIG_PYTHON_2_UNICODE and +SWIG_PYTHON_STRICT_BYTE_CHAR at the same time is not allowed, since +the first is allowing unicode conversion and the second is explicitly +prohibiting it.

      diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index 50e861b22..9b5993bff 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -1,12 +1,13 @@ - + SWIG and R + -

      37 SWIG and R

      +

      37 SWIG and R

        @@ -33,7 +34,7 @@ compile and run an R interface to QuantLib running on Mandriva Linux with gcc. The R bindings also work on Microsoft Windows using Visual C++.

        -

        37.1 Bugs

        +

        37.1 Bugs

        @@ -45,7 +46,7 @@ Currently the following features are not implemented or broken:

      • C Array wrappings
      -

      37.2 Using R and SWIG

      +

      37.2 Using R and SWIG

      @@ -136,7 +137,7 @@ Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") :

    • Make sure the architecture of the shared library(x64 for instance), matches the architecture of the R program you want to load your shared library into -

      37.3 Precompiling large R files

      +

      37.3 Precompiling large R files

      In cases where the R file is large, one make save a lot of loading @@ -154,7 +155,7 @@ will save a large amount of loading time. -

      37.4 General policy

      +

      37.4 General policy

      @@ -163,7 +164,7 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.

      -

      37.5 Language conventions

      +

      37.5 Language conventions

      @@ -172,7 +173,7 @@ and [ are overloaded to allow for R syntax (one based indices and slices)

      -

      37.6 C++ classes

      +

      37.6 C++ classes

      @@ -184,7 +185,7 @@ keep track of the pointer object which removes the necessity for a lot of the proxy class baggage you see in other languages.

      -

      37.7 Enumerations

      +

      37.7 Enumerations

      diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index e78447b92..cfb99e792 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -1,13 +1,14 @@ - + - SWIG and Ruby - +SWIG and Ruby + + -

      38 SWIG and Ruby

      +

      38 SWIG and Ruby

      -

      38.1.3 Compiling a dynamic module

      +

      38.1.3 Compiling a dynamic module

      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.

      -

      38.1.4 Using your module

      +

      38.1.4 Using your module

      Ruby module names must be capitalized, @@ -315,7 +320,7 @@ begins with:

      will result in an extension module using the feature name "example" and Ruby module name "Example".

      -

      38.1.5 Static linking

      +

      38.1.5 Static linking

      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.

      -

      38.1.6 Compilation of C++ extensions

      +

      38.1.6 Compilation of C++ extensions

      On most machines, C++ extension modules should be linked @@ -362,7 +367,7 @@ $libs = append_library($libs, "supc++") create_makefile('example')

    • -

      38.2 Building Ruby Extensions under Windows 95/NT

      +

      38.2 Building Ruby Extensions under Windows 95/NT

      Building a SWIG extension to Ruby under Windows 95/NT is @@ -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.

      -

      38.2.1 Running SWIG from Developer Studio

      +

      38.2.1 Running SWIG from Developer Studio

      If you are developing your application within Microsoft @@ -451,13 +456,13 @@ Foo = 3.0 -

      38.3 The Ruby-to-C/C++ Mapping

      +

      38.3 The Ruby-to-C/C++ Mapping

      This section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs.

      -

      38.3.1 Modules

      +

      38.3.1 Modules

      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.

      -

      38.3.2 Functions

      +

      38.3.2 Functions

      Global functions are wrapped as Ruby module methods. For @@ -563,7 +568,7 @@ irb(main):002:0> Example.fact(4) 24 -

      38.3.3 Variable Linking

      +

      38.3.3 Variable Linking

      C/C++ global variables are wrapped as a pair of singleton @@ -625,7 +630,7 @@ directive. For example:

      effect until it is explicitly disabled using %mutable.

      -

      38.3.4 Constants

      +

      38.3.4 Constants

      C/C++ constants are wrapped as module constants initialized @@ -653,7 +658,7 @@ irb(main):002:0> Example::PI 3.14159 -

      38.3.5 Pointers

      +

      38.3.5 Pointers

      "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -677,7 +682,7 @@ returns an instance of an internally generated Ruby class:

      A NULL pointer is always represented by the Ruby nil object.

      -

      38.3.6 Structures

      +

      38.3.6 Structures

      C/C++ structs are wrapped as Ruby classes, with accessor @@ -782,7 +787,7 @@ void Bar_f_set(Bar *b, Foo *val) { } -

      38.3.7 C++ classes

      +

      38.3.7 C++ classes

      Like structs, C++ classes are wrapped by creating a new Ruby @@ -837,7 +842,7 @@ Ale 3 -

      38.3.8 C++ Inheritance

      +

      38.3.8 C++ Inheritance

      The SWIG type-checker is fully aware of C++ inheritance. @@ -990,7 +995,7 @@ inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").

      -

      38.3.9 C++ Overloaded Functions

      +

      38.3.9 C++ Overloaded Functions

      C++ overloaded functions, methods, and constructors are @@ -1080,7 +1085,7 @@ arises--in this case, the first declaration takes precedence.

      Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      38.3.10 C++ Operators

      +

      38.3.10 C++ Operators

      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.

      -

      38.3.11 C++ namespaces

      +

      38.3.11 C++ namespaces

      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.

      -

      38.3.12 C++ templates

      +

      38.3.12 C++ templates

      C++ templates don't present a huge problem for SWIG. However, @@ -1221,7 +1226,7 @@ irb(main):004:0> p.second 4 -

      38.3.13 C++ Standard Template Library (STL)

      +

      38.3.13 C++ Standard Template Library (STL)

      On a related note, the standard SWIG library contains a @@ -1314,7 +1319,7 @@ puts v shown in these examples. More details can be found in the SWIG and C++ chapter.

      -

      38.3.14 C++ STL Functors

      +

      38.3.14 C++ STL Functors

      Some containers in the STL allow you to modify their default @@ -1347,7 +1352,7 @@ are provided.

      %include <std_set.i> -%typemap(IntSet) std::set< int, swig::BinaryPredicate >; +%template(IntSet) std::set< int, swig::BinaryPredicate >;

      You can then use the set from Ruby with or without a proc @@ -1375,7 +1380,7 @@ b -

      38.3.15 C++ STL Iterators

      +

      38.3.15 C++ STL Iterators

      The STL is well known for the use of iterators. There @@ -1458,7 +1463,21 @@ i

      If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

      -

      38.3.16 C++ Smart Pointers

      +

      38.3.16 C++ Smart Pointers

      + + +

      38.3.16.1 The shared_ptr Smart Pointer

      + + +

      +The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Ruby in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +

      + + +

      38.3.16.2 Generic Smart Pointers

      In certain C++ programs, it is common to use classes that @@ -1523,7 +1542,7 @@ method. For example:

      irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
      -

      38.3.17 Cross-Language Polymorphism

      +

      38.3.17 Cross-Language Polymorphism

      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 +

      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.

      -

      38.4 Naming

      +

      38.4 Naming

      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.

      -

      38.4.1 Defining Aliases

      +

      38.4.1 Defining Aliases

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

      -

      38.4.2 Predicate Methods

      +

      38.4.2 Predicate Methods

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

      -

      38.4.3 Bang Methods

      +

      38.4.3 Bang Methods

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

      -

      38.4.4 Getters and Setters

      +

      38.4.4 Getters and Setters

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

      38.5 Input and output parameters

      +

      38.5 Input and output parameters

      A common problem in some C programs is handling parameters @@ -1918,10 +1937,10 @@ void get_dimensions(Matrix *m, int *rows, int*columns);

      r, c = Example.get_dimensions(m)
      -

      38.6 Exception handling

      +

      38.6 Exception handling

      -

      38.6.1 Using the %exception directive

      +

      38.6.1 Using the %exception directive

      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.

      -

      38.6.2 Handling Ruby Blocks

      +

      38.6.2 Handling Ruby Blocks

      One of the highlights of Ruby and most of its standard library @@ -2097,7 +2116,7 @@ a special in typemap, like:

      For more information on typemaps, see Typemaps.

      -

      38.6.3 Raising exceptions

      +

      38.6.3 Raising exceptions

      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.

      -

      38.6.4 Exception classes

      +

      38.6.4 Exception classes

      Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -2291,7 +2310,7 @@ end

      For another example look at swig/Examples/ruby/exception_class.

      -

      38.7 Typemaps

      +

      38.7 Typemaps

      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.

      -

      38.7.1 What is a typemap?

      +

      38.7.1 What is a typemap?

      A typemap is nothing more than a code generation rule that is @@ -2463,7 +2482,7 @@ to be used as follows (notice how the length parameter is omitted):

      2 -

      38.7.2 Typemap scope

      +

      38.7.2 Typemap scope

      Once defined, a typemap remains in effect for all of the @@ -2509,7 +2528,7 @@ where the class itself is defined. For example:

      }; -

      38.7.3 Copying a typemap

      +

      38.7.3 Copying a typemap

      A typemap is copied by using assignment. For example:

      @@ -2551,7 +2570,7 @@ rules as for %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments -

      38.7.4 Deleting a typemap

      +

      38.7.4 Deleting a typemap

      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.

      -

      38.7.5 Placement of typemaps

      +

      38.7.5 Placement of typemaps

      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 .

      -

      38.7.6 Ruby typemaps

      +

      38.7.6 Ruby typemaps

      The following list details all of the typemap methods that can be used by the Ruby module:

      -

      38.7.6.1 "in" typemap

      +

      38.7.6.1 "in" typemap

      Converts Ruby objects to input @@ -2720,7 +2739,7 @@ arguments to be specified. For example:

      At this time, only zero or one arguments may be converted.

      -

      38.7.6.2 "typecheck" typemap

      +

      38.7.6.2 "typecheck" typemap

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

      -

      38.7.6.3 "out" typemap

      +

      38.7.6.3 "out" typemap

      Converts return value of a C function @@ -2793,7 +2812,7 @@ version of the C datatype matched by the typemap.

      -

      38.7.6.4 "arginit" typemap

      +

      38.7.6.4 "arginit" typemap

      The "arginit" typemap is used to set the initial value of a @@ -2808,7 +2827,7 @@ applications. For example:

      } -

      38.7.6.5 "default" typemap

      +

      38.7.6.5 "default" typemap

      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 +

      38.7.6.6 "check" typemap

      The "check" typemap is used to supply value checking code @@ -2848,7 +2867,7 @@ arguments have been converted. For example:

      } -

      38.7.6.7 "argout" typemap

      +

      38.7.6.7 "argout" typemap

      The "argout" typemap is used to return values from arguments. @@ -2902,7 +2921,7 @@ some function like SWIG_Ruby_AppendOutput.

      See the typemaps.i library for examples.

      -

      38.7.6.8 "freearg" typemap

      +

      38.7.6.8 "freearg" 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.

      -

      38.7.6.9 "newfree" typemap

      +

      38.7.6.9 "newfree" typemap

      The "newfree" typemap is used in conjunction with the %newobject @@ -2953,7 +2972,7 @@ string *foo();

      See Object ownership and %newobject for further details.

      -

      38.7.6.10 "memberin" typemap

      +

      38.7.6.10 "memberin" typemap

      The "memberin" typemap is used to copy data from an @@ -2971,21 +2990,21 @@ example:

      already provides a default implementation for arrays, strings, and other objects.

      -

      38.7.6.11 "varin" typemap

      +

      38.7.6.11 "varin" typemap

      The "varin" typemap is used to convert objects in the target language to C for the purposes of assigning to a C/C++ global variable. This is implementation specific.

      -

      38.7.6.12 "varout" typemap

      +

      38.7.6.12 "varout" typemap

      The "varout" typemap is used to convert a C/C++ object to an object in the target language when reading a C/C++ global variable. This is implementation specific.

      -

      38.7.6.13 "throws" typemap

      +

      38.7.6.13 "throws" typemap

      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.

      -

      38.7.6.14 directorin typemap

      +

      38.7.6.14 directorin typemap

      Converts C++ objects in director @@ -3085,7 +3104,7 @@ referring to the class itself. -

      38.7.6.15 directorout typemap

      +

      38.7.6.15 directorout typemap

      Converts Ruby objects in director @@ -3158,7 +3177,7 @@ exception.

      -

      38.7.6.16 directorargout typemap

      +

      38.7.6.16 directorargout typemap

      Output argument processing in director @@ -3216,19 +3235,19 @@ referring to the instance of the class itself -

      38.7.6.17 ret typemap

      +

      38.7.6.17 ret typemap

      Cleanup of function return values

      -

      38.7.6.18 globalin typemap

      +

      38.7.6.18 globalin typemap

      Setting of C global variables

      -

      38.7.7 Typemap variables

      +

      38.7.7 Typemap variables

      @@ -3278,7 +3297,7 @@ so that their values can be properly assigned.

      The Ruby name of the wrapper function being created.
      -

      38.7.8 Useful Functions

      +

      38.7.8 Useful Functions

      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.

      -

      38.7.8.1 C Datatypes to Ruby Objects

      +

      38.7.8.1 C Datatypes to Ruby Objects

      @@ -3335,7 +3354,7 @@ SWIG_From_float(float)
      -

      38.7.8.2 Ruby Objects to C Datatypes

      +

      38.7.8.2 Ruby Objects to C Datatypes

      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 -

      38.7.8.3 Macros for VALUE

      +

      38.7.8.3 Macros for VALUE

      RSTRING_LEN(str)

      @@ -3426,7 +3445,7 @@ versions do not, but return a status value to indicate success (SWIG_OK
      pointer to array storage
      -

      38.7.8.4 Exceptions

      +

      38.7.8.4 Exceptions

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

      38.7.8.5 Iterators

      +

      38.7.8.5 Iterators

      void rb_iter_break()

      @@ -3551,14 +3570,14 @@ VALUE), VALUE value)

      Equivalent to Ruby's throw.
      -

      38.7.9 Typemap Examples

      +

      38.7.9 Typemap Examples

      This section includes a few examples of typemaps. For more examples, you might look at the examples in the Example/ruby directory.

      -

      38.7.10 Converting a Ruby array to a char **

      +

      38.7.10 Converting a Ruby array to a char **

      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.

      -

      38.7.11 Collecting arguments in a hash

      +

      38.7.11 Collecting arguments in a hash

      Ruby's solution to the "keyword arguments" capability of some @@ -3837,7 +3856,7 @@ memory leak. Fortunately, this typemap is a lot easier to write:

      program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

      -

      38.7.12 Pointer handling

      +

      38.7.12 Pointer handling

      Occasionally, it might be necessary to convert pointer values @@ -3896,7 +3915,7 @@ For example:

      } -

      38.7.12.1 Ruby Datatype Wrapping

      +

      38.7.12.1 Ruby Datatype Wrapping

      VALUE Data_Wrap_Struct(VALUE class, void @@ -3923,7 +3942,7 @@ as above. type c-type from the data object obj and assigns that pointer to ptr. -

      38.7.13 Example: STL Vector to Ruby Array

      +

      38.7.13 Example: STL Vector to Ruby Array

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

      38.8 Docstring Features

      +

      38.8 Docstring Features

      @@ -4049,7 +4068,7 @@ generate ri documentation from a c wrap file, you could do:

      $ rdoc -r file_wrap.c -

      38.8.1 Module docstring

      +

      38.8.1 Module docstring

      @@ -4079,7 +4098,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." %module(docstring=DOCSTRING) xrc -

      38.8.2 %feature("autodoc")

      +

      38.8.2 %feature("autodoc")

      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.

      -

      38.8.2.1 %feature("autodoc", "0")

      +

      38.8.2.1 %feature("autodoc", "0")

      @@ -4124,7 +4143,7 @@ Then Ruby code like this will be generated: ... -

      38.8.2.2 %feature("autodoc", "1")

      +

      38.8.2.2 %feature("autodoc", "1")

      @@ -4144,7 +4163,7 @@ this: ... -

      38.8.2.3 %feature("autodoc", "2")

      +

      38.8.2.3 %feature("autodoc", "2")

      @@ -4156,7 +4175,7 @@ parameter types with the "2" option will result in Ruby code like this:

      -

      38.8.2.4 %feature("autodoc", "3")

      +

      38.8.2.4 %feature("autodoc", "3")

      @@ -4171,13 +4190,13 @@ this:

      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
       
       Parameters:
      -	x - int
      -	y - int
      -	foo - Foo
      -	bar - Bar
      + x - int + y - int + foo - Foo + bar - Bar -

      38.8.2.5 %feature("autodoc", "docstring")

      +

      38.8.2.5 %feature("autodoc", "docstring")

      @@ -4193,7 +4212,7 @@ generated string. For example: void GetPosition(int* OUTPUT, int* OUTPUT); -

      38.8.3 %feature("docstring")

      +

      38.8.3 %feature("docstring")

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

      -

      38.9 Advanced Topics

      +

      38.9 Advanced Topics

      -

      38.9.1 Operator overloading

      +

      38.9.1 Operator overloading

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

      -

      38.9.2 Creating Multi-Module Packages

      +

      38.9.2 Creating Multi-Module Packages

      The chapter on Working @@ -4514,7 +4533,7 @@ irb(main):005:0> c.getX() 5.0 -

      38.9.3 Specifying Mixin Modules

      +

      38.9.3 Specifying Mixin Modules

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

      -

      38.10 Memory Management

      +

      38.10 Memory Management

      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.

      -

      38.10.1 Mark and Sweep Garbage Collector

      +

      38.10.1 Mark and Sweep Garbage Collector

      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.

      -

      38.10.2 Object Ownership

      +

      38.10.2 Object Ownership

      As described above, memory management depends on clearly @@ -4781,7 +4799,7 @@ public:

      This code can be seen in swig/examples/ruby/tracking.

      -

      38.10.3 Object Tracking

      +

      38.10.3 Object Tracking

      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.

      -

      38.10.4 Mark Functions

      +

      38.10.4 Mark Functions

      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.

      -

      38.10.5 Free Functions

      +

      38.10.5 Free Functions

      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:

      -
      Zoo::~Zoo() {
      - IterType iter = this->animals.begin();
      - IterType end = this->animals.end();
      -
      - for(iter; iter != end; ++iter) {
      - Animal* animal = *iter;
      - delete animal;
      - }
      -}
      +
      +Zoo::~Zoo() {
      +  IterType iter = this->animals.begin();
      +  IterType end = this->animals.end();
      + 
      +  for(iter; iter != end; ++iter) {
      +    Animal* animal = *iter;
      +    delete animal;
      +  }
      +}
      +

      When we use these objects in IRB we see:

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

      -

      38.10.6 Embedded Ruby and the C++ Stack

      +

      38.10.6 Embedded Ruby and the C++ Stack

      As has been said, the Ruby GC runs and marks objects before diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index 774e00b23..3c8565fdc 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -1,12 +1,13 @@ - + SWIG Basics + -

      5 SWIG Basics

      +

      5 SWIG Basics

    • Pointers and complex objects
        @@ -40,7 +41,7 @@
      • Passing structures by value
      • Return by value
      • Linking to structure variables -
      • Linking to char * +
      • Linking to char *
      • Arrays
      • Creating read-only variables
      • Renaming and ignoring declarations @@ -94,7 +95,7 @@ Specific details about each target language are described in later chapters.

        -

        5.1 Running SWIG

        +

        5.1 Running SWIG

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

        5.1.1 Input format

        +

        5.1.1 Input format

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

        -

        5.1.2 SWIG Output

        +

        5.1.2 SWIG Output

        @@ -263,7 +270,7 @@ as the output directory for the language files is the same directory as the generated C/C++ file if not overridden with -outdir.

        -

        5.1.3 Comments

        +

        5.1.3 Comments

        @@ -273,7 +280,7 @@ documentation files. However, this feature is currently under repair and will reappear in a later SWIG release.

        -

        5.1.4 C Preprocessor

        +

        5.1.4 C Preprocessor

        @@ -297,7 +304,7 @@ make it more powerful than the normal C preprocessor. These extensions are described in the "Preprocessor" chapter.

        -

        5.1.5 SWIG Directives

        +

        5.1.5 SWIG Directives

        @@ -328,7 +335,7 @@ included in C header files using conditional compilation like this: it is parsing an input file.

        -

        5.1.6 Parser Limitations

        +

        5.1.6 Parser Limitations

        @@ -426,7 +433,7 @@ does not utilize a separate typedef-name terminal symbol as described on p. 234 of K&R).

        -

        5.2 Wrapping Simple C Declarations

        +

        5.2 Wrapping Simple C Declarations

        @@ -489,7 +496,7 @@ environments, and semantics, it is not always possible to do so. The next few sections describe various aspects of this mapping.

        -

        5.2.1 Basic Type Handling

        +

        5.2.1 Basic Type Handling

        @@ -614,7 +621,7 @@ will use the same internal representation (e.g., UCS-2 vs. UCS-4). You may need to write some special conversion functions.

        -

        5.2.2 Global Variables

        +

        5.2.2 Global Variables

        @@ -669,7 +676,7 @@ Earlier versions of SWIG incorrectly handled const and created constants instead.

        -

        5.2.3 Constants

        +

        5.2.3 Constants

        @@ -758,7 +765,7 @@ is only used when you want to add constants to the scripting language interface that are not defined in the original header file.

        -

        5.2.4 A brief word about const

        +

        5.2.4 A brief word about const

        @@ -860,7 +867,7 @@ const int spam = 42;

    • -

      5.2.5 A cautionary tale of char *

      +

      5.2.5 A cautionary tale of char *

      @@ -899,7 +906,7 @@ input values. However, it must be noted that you could change the behavior of using typemaps.

      -

      5.3 Pointers and complex objects

      +

      5.3 Pointers and complex objects

      @@ -907,7 +914,7 @@ Most C programs manipulate arrays, structures, and other types of objects. This discusses the handling of these datatypes.

      -

      5.3.1 Simple pointers

      +

      5.3.1 Simple pointers

      @@ -973,7 +980,7 @@ simplified and less prone to error.

    -

    5.3.2 Run time pointer type checking

    +

    5.3.2 Run time pointer type checking

    @@ -995,7 +1002,7 @@ as sentinel values or to denote a missing/empty value. Therefore, SWIG leaves NULL pointer checking up to the application.

    -

    5.3.3 Derived types, structs, and classes

    +

    5.3.3 Derived types, structs, and classes

    @@ -1036,15 +1043,14 @@ expect :

     # Copy a file 
     def filecopy(source,target):
    -	f1 = fopen(source,"r")
    -	f2 = fopen(target,"w")
    -	buffer = malloc(8192)
    -	nbytes = fread(buffer,8192,1,f1)
    -	while (nbytes > 0):
    -		fwrite(buffer,8192,1,f2)
    -		nbytes = fread(buffer,8192,1,f1)
    -	free(buffer)
    -
    +  f1 = fopen(source,"r")
    +  f2 = fopen(target,"w")
    +  buffer = malloc(8192)
    +  nbytes = fread(buffer,8192,1,f1)
    +  while (nbytes > 0):
    +    fwrite(buffer,8192,1,f2)
    +          nbytes = fread(buffer,8192,1,f1)
    +  free(buffer)
     

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

    -

    5.3.4 Undefined datatypes

    +

    5.3.4 Undefined datatypes

    @@ -1112,7 +1118,7 @@ The only way to fix this problem is to make sure you properly declare type names -

    5.3.5 Typedef

    +

    5.3.5 Typedef

    @@ -1201,7 +1207,7 @@ The corresponding wrapper function will accept arguments of type unsigned int * or size_t *.

    -

    5.4 Other Practicalities

    +

    5.4 Other Practicalities

    @@ -1211,7 +1217,7 @@ more difficult to map to a scripting language interface. This section describes some of these issues.

    -

    5.4.1 Passing structures by value

    +

    5.4.1 Passing structures by value

    @@ -1242,7 +1248,7 @@ to Vectors instead of Vectors. For the most part, this transformation is transparent so you might not notice.

    -

    5.4.2 Return by value

    +

    5.4.2 Return by value

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

    -

    5.4.3 Linking to structure variables

    +

    5.4.3 Linking to structure variables

    @@ -1314,10 +1320,10 @@ gets mapped to an underlying pair of set/get functions like this :

     Vector *unit_i_get() {
    -	return &unit_i;
    +  return &unit_i;
     }
     void unit_i_set(Vector *value) {
    -	unit_i = *value;
    +  unit_i = *value;
     }
     
    @@ -1329,7 +1335,7 @@ C++ classes must supply a properly defined copy constructor in order for assignment to work correctly.

    -

    5.4.4 Linking to char *

    +

    5.4.4 Linking to char *

    @@ -1352,16 +1358,16 @@ SWIG generates the following code:

     /* C mode */
     void foo_set(char *value) {
    -   if (foo) free(foo);
    -   foo = (char *) malloc(strlen(value)+1);
    -   strcpy(foo,value);
    +  if (foo) free(foo);
    +  foo = (char *) malloc(strlen(value)+1);
    +  strcpy(foo,value);
     }
     
     /* C++ mode.  When -c++ option is used */
     void foo_set(char *value) {
    -   if (foo) delete [] foo;
    -   foo = new char[strlen(value)+1];
    -   strcpy(foo,value);
    +  if (foo) delete [] foo;
    +  foo = new char[strlen(value)+1];
    +  strcpy(foo,value);
     }
     
    @@ -1376,8 +1382,8 @@ exactly like you want. For example:
     %inline %{
       void set_foo(char *value) {
    -       strncpy(foo,value, 50);
    -   }
    +    strncpy(foo,value, 50);
    +  }
     %}
     
    @@ -1458,7 +1464,7 @@ value is not released. -

    5.4.5 Arrays

    +

    5.4.5 Arrays

    @@ -1533,10 +1539,10 @@ a few simple assist functions like this:

     %inline %{
     void a_set(int i, int j, int val) {
    -   a[i][j] = val;
    +  a[i][j] = val;
     }
     int a_get(int i, int j) {
    -   return a[i][j];
    +  return a[i][j];
     }
     %}
     
    @@ -1553,11 +1559,11 @@ some helper functions in your interface. For example: %inline %{ /* Create any sort of [size] array */ int *int_array(int size) { - return (int *) malloc(size*sizeof(int)); + return (int *) malloc(size*sizeof(int)); } /* Create a two-dimension array [size][10] */ int (*int_array_10(int size))[10] { - return (int (*)[10]) malloc(size*10*sizeof(int)); + return (int (*)[10]) malloc(size*10*sizeof(int)); } %} @@ -1582,10 +1588,10 @@ code:
     char *pathname_get() {
    -   return pathname;
    +  return pathname;
     }
     void pathname_set(char *value) {
    -   strncpy(pathname,value,256);
    +  strncpy(pathname,value,256);
     }
     
    @@ -1594,7 +1600,7 @@ void pathname_set(char *value) { In the target language, the value can be set like a normal variable.

    -

    5.4.6 Creating read-only variables

    +

    5.4.6 Creating read-only variables

    @@ -1604,11 +1610,11 @@ directive as shown :

     // File : interface.i
     
    -int 	a; 			// Can read/write
    +int a;       // Can read/write
     %immutable;
    -int	b,c,d			// Read only variables
    +int b,c,d;   // Read only variables
     %mutable;
    -double	x,y			// read/write
    +double x,y;  // read/write
     

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

    -

    5.4.7 Renaming and ignoring declarations

    +

    5.4.7 Renaming and ignoring declarations

    -

    5.4.7.1 Simple renaming of specific identifiers

    +

    5.4.7.1 Simple renaming of specific identifiers

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

    -

    5.4.7.2 Advanced renaming support

    +

    5.4.7.2 Advanced renaming support

    @@ -1883,6 +1889,13 @@ and a more descriptive one, but the two functions are otherwise equivalent: literally, e.g. %rename("strip:[wx]") wxPrintPrint + + 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]") + PrintClsPrint + 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.

    -

    5.4.7.3 Limiting global renaming rules

    +

    5.4.7.3 Limiting global renaming rules

    @@ -2069,7 +2082,7 @@ wrap C++ overloaded functions and methods or C++ methods which use default argum

    -

    5.4.7.4 Ignoring everything then wrapping a few selected symbols

    +

    5.4.7.4 Ignoring everything then wrapping a few selected symbols

    @@ -2111,7 +2124,7 @@ members of the class, so when the chosen class is unignored, all of its methods -

    5.4.8 Default/optional arguments

    +

    5.4.8 Default/optional arguments

    @@ -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
     
     
    @@ -2148,7 +2161,7 @@ Please refer to the section on def in the C++ chapter for further details.

    -

    5.4.9 Pointers to functions and callbacks

    +

    5.4.9 Pointers to functions and callbacks

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

    -

    5.5 Structures and unions

    +

    5.5 Structures and unions

    @@ -2319,7 +2332,7 @@ to an individual member. For example, the declaration :

     struct Vector {
    -	double x,y,z;
    +  double x,y,z;
     }
     
     
    @@ -2329,22 +2342,22 @@ gets transformed into the following set of accessor functions :

     double Vector_x_get(struct Vector *obj) {
    -	return obj->x;
    +  return obj->x;
     }
     double Vector_y_get(struct Vector *obj) { 
    -	return obj->y;
    +  return obj->y;
     }
     double Vector_z_get(struct Vector *obj) { 
    -	return obj->z;
    +  return obj->z;
     }
     void Vector_x_set(struct Vector *obj, double value) {
    -	obj->x = value;
    +  obj->x = value;
     }
     void Vector_y_set(struct Vector *obj, double value) {
    -	obj->y = value;
    +  obj->y = value;
     }
     void Vector_z_set(struct Vector *obj, double value) {
    -	obj->z = value;
    +  obj->z = value;
     }
     
    @@ -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.

    -

    5.5.1 Typedef and structures

    +

    5.5.1 Typedef and structures

    @@ -2392,7 +2405,7 @@ programs :

     typedef struct {
    -	double x,y,z;
    +  double x,y,z;
     } Vector;
     
     
    @@ -2407,7 +2420,7 @@ that the use of typedef allows SWIG to drop the
     double Vector_x_get(Vector *obj) {
    -	return obj->x;
    +  return obj->x;
     }
     
    @@ -2417,7 +2430,7 @@ If two different names are used like this :

     typedef struct vector_struct {
    -	double x,y,z;
    +  double x,y,z;
     } Vector;
     
     
    @@ -2429,7 +2442,7 @@ vector_struct
    , SWIG knows that this is the same as Vector and it generates the appropriate type-checking code.

    -

    5.5.2 Character strings and structures

    +

    5.5.2 Character strings and structures

    @@ -2443,8 +2456,8 @@ will be released, and the new contents allocated. For example :

    %module mymodule ... struct Foo { - char *name; - ... + char *name; + ... } @@ -2454,14 +2467,15 @@ This results in the following accessor functions :

     char *Foo_name_get(Foo *obj) {
    -	return Foo->name;
    +  return Foo->name;
     }
     
     char *Foo_name_set(Foo *obj, char *c) {
    -	if (obj->name) free(obj->name);
    -	obj->name = (char *) malloc(strlen(c)+1);
    -	strcpy(obj->name,c);
    -	return obj->name;
    +  if (obj->name)
    +    free(obj->name);
    +  obj->name = (char *) malloc(strlen(c)+1);
    +  strcpy(obj->name,c);
    +  return obj->name;
     }
     
    @@ -2476,7 +2490,7 @@ Note: If the -c++ option is used, new and delete are perform memory allocation.

    -

    5.5.3 Array members

    +

    5.5.3 Array members

    @@ -2498,7 +2512,7 @@ discussed in a later chapter. In many cases, the warning message is harmless.

    -

    5.5.4 Structure data members

    +

    5.5.4 Structure data members

    @@ -2508,12 +2522,12 @@ Occasionally, a structure will contain data members that are themselves structur

     typedef struct Foo {
    -   int x;
    +  int x;
     } Foo;
     
     typedef struct Bar {
    -   int y;
    -   Foo f;           /* struct member */
    +  int y;
    +  Foo f;           /* struct member */
     } Bar;
     
    @@ -2527,10 +2541,10 @@ The accessors to the member variable as a pointer are effectively wrapped as fol
     Foo *Bar_f_get(Bar *b) {
    -   return &b->f;
    +  return &b->f;
     }
     void Bar_f_set(Bar *b, Foo *value) {
    -   b->f = *value;
    +  b->f = *value;
     }
     
    @@ -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;".

    -

    5.5.5 C constructors and destructors

    +

    5.5.5 C constructors and destructors

    @@ -2693,7 +2707,7 @@ the target languages, and it is highly recommended you don't use them.

    -

    5.5.6 Adding member functions to C structures

    +

    5.5.6 Adding member functions to C structures

    @@ -2713,7 +2727,7 @@ the following declaration :

    /* file : vector.h */ ... typedef struct Vector { - double x,y,z; + double x,y,z; } Vector; @@ -2731,23 +2745,23 @@ You can make a Vector look a lot like a class by writing a SWIG interfa %include "vector.h" // Just grab original C header file %extend Vector { // Attach these functions to struct Vector - Vector(double x, double y, double z) { - Vector *v; - v = (Vector *) malloc(sizeof(Vector)); - v->x = x; - v->y = y; - v->z = z; - return v; - } - ~Vector() { - free($self); - } - double magnitude() { - return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z); - } - void print() { - printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z); - } + Vector(double x, double y, double z) { + Vector *v; + v = (Vector *) malloc(sizeof(Vector)); + v->x = x; + v->y = y; + v->z = z; + return v; + } + ~Vector() { + free($self); + } + double magnitude() { + return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z); + } + void print() { + printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z); + } }; @@ -2786,12 +2800,12 @@ of the Vector structure. For example:

    %} typedef struct Vector { - double x,y,z; - %extend { - Vector(double x, double y, double z) { ... } - ~Vector() { ... } - ... - } + double x,y,z; + %extend { + Vector(double x, double y, double z) { ... } + ~Vector() { ... } + ... + } } Vector; @@ -2805,19 +2819,19 @@ example :

    /* Vector methods */ #include "vector.h" Vector *new_Vector(double x, double y, double z) { - Vector *v; - v = (Vector *) malloc(sizeof(Vector)); - v->x = x; - v->y = y; - v->z = z; - return v; + Vector *v; + v = (Vector *) malloc(sizeof(Vector)); + v->x = x; + v->y = y; + v->z = z; + return v; } void delete_Vector(Vector *v) { - free(v); + free(v); } double Vector_magnitude(Vector *v) { - return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); + return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } // File : vector.i @@ -2828,13 +2842,13 @@ double Vector_magnitude(Vector *v) { %} typedef struct Vector { - double x,y,z; - %extend { - Vector(int,int,int); // This calls new_Vector() - ~Vector(); // This calls delete_Vector() - double magnitude(); // This will call Vector_magnitude() - ... - } + double x,y,z; + %extend { + Vector(int,int,int); // This calls new_Vector() + ~Vector(); // This calls delete_Vector() + double magnitude(); // This will call Vector_magnitude() + ... + } } Vector; @@ -2846,13 +2860,13 @@ For example:
     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
     
     
     typedef struct {
    -	double value;
    +  double value;
     } Double;
     %extend Double { ...  } /* Okay */
     
    @@ -2966,7 +2980,7 @@ be used to extend a structure with more than just methods, a more suitable directive name has been chosen.

    -

    5.5.7 Nested structures

    +

    5.5.7 Nested structures

    @@ -2974,13 +2988,13 @@ Occasionally, a C program will involve structures like this :

     typedef struct Object {
    -	int objtype;
    -	union {
    -		int 	ivalue;
    -		double	dvalue;
    -		char	*strvalue;
    -		void	*ptrvalue;
    -	} intRep;
    +  int objtype;
    +  union {
    +    int ivalue;
    +    double dvalue;
    +    char *strvalue;
    +    void *ptrvalue;
    +  } intRep;
     } Object;
     
     
    @@ -2992,15 +3006,15 @@ following:

     typedef union {
    -	int 		ivalue;
    -	double		dvalue;
    -	char		*strvalue;
    -	void		*ptrvalue;
    +  int ivalue;
    +  double dvalue;
    +  char *strvalue;
    +  void *ptrvalue;
     } Object_intRep;
     
     typedef struct Object {
    -	int objType;
    -	Object_intRep intRep;
    +  int objType;
    +  Object_intRep intRep;
     } Object;
     
     
    @@ -3012,16 +3026,16 @@ structures. In this case, functions like this would be created :

     Object_intRep *Object_intRep_get(Object *o) {
    -	return (Object_intRep *) &o->intRep;
    +  return (Object_intRep *) &o->intRep;
     }
     int Object_intRep_ivalue_get(Object_intRep *o) {
    -	return o->ivalue;
    +  return o->ivalue;
     }
     int Object_intRep_ivalue_set(Object_intRep *o, int value) {
    -	return (o->ivalue = value);
    +  return (o->ivalue = value);
     }
     double Object_intRep_dvalue_get(Object_intRep *o) {
    -	return o->dvalue;
    +  return o->dvalue;
     }
     ... etc ...
     
    @@ -3050,7 +3064,7 @@ Finally, note that nesting is handled differently in C++ mode,
     see Nested classes.
     

    -

    5.5.8 Other things to note about structure wrapping

    +

    5.5.8 Other things to note about structure wrapping

    @@ -3070,7 +3084,7 @@ in terms of high-level accessor functions such as this,

     double Vector_x_get(Vector *v) {
    -   return v->x;
    +  return v->x;
     }
     
    @@ -3087,15 +3101,15 @@ the following function is generated instead: static int _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - struct Vector *arg1 ; - double result ; - - if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&arg0, - SWIGTYPE_p_Vector) == TCL_ERROR) - return TCL_ERROR; - result = (double ) (arg1->x); - Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result)); - return TCL_OK; + struct Vector *arg1 ; + double result ; + + if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&arg0, + SWIGTYPE_p_Vector) == TCL_ERROR) + return TCL_ERROR; + result = (double ) (arg1->x); + Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result)); + return TCL_OK; }
    @@ -3112,7 +3126,7 @@ interface described here, most of SWIG's language modules use it in some way or another.

    -

    5.6 Code Insertion

    +

    5.6 Code Insertion

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

    -

    5.6.1 The output of SWIG

    +

    5.6.1 The output of SWIG

    @@ -3158,7 +3172,7 @@ the module upon loading. -

    5.6.2 Code insertion blocks

    +

    5.6.2 Code insertion blocks

    @@ -3170,23 +3184,23 @@ the wrapper file is as shown:

     %begin %{
    -   ... code in begin section ...
    +  ... code in begin section ...
     %}
     
     %runtime %{
    -   ... code in runtime section ...
    +  ... code in runtime section ...
     %}
     
     %header %{
    -   ... code in header section ...
    +  ... code in header section ...
     %}
     
     %wrapper %{
    -   ... code in wrapper section ...
    +  ... code in wrapper section ...
     %}
     
     %init %{
    -   ... code in init section ...
    +  ... code in init section ...
     %}
     
    @@ -3228,7 +3242,7 @@ program. For example :

    %{ /* Create a new vector */ static Vector *new_Vector() { - return (Vector *) malloc(sizeof(Vector)); + return (Vector *) malloc(sizeof(Vector)); } %} @@ -3236,7 +3250,7 @@ static Vector *new_Vector() { Vector *new_Vector();
    -

    5.6.3 Inlined code blocks

    +

    5.6.3 Inlined code blocks

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

    -

    5.6.4 Initialization blocks

    +

    5.6.4 Initialization blocks

    @@ -3274,11 +3288,11 @@ initialization on module loading, you could write this:

     %init %{
    -	init_variables();
    +  init_variables();
     %}
     
    -

    5.7 An Interface Building Strategy

    +

    5.7 An Interface Building Strategy

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

    -

    5.7.1 Preparing a C program for SWIG

    +

    5.7.1 Preparing a C program for SWIG

    @@ -3340,7 +3354,7 @@ to the swig-devel mailing list or to SWIG bug tracker.

    -

    5.7.2 The SWIG interface file

    +

    5.7.2 The SWIG interface file

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

    -

    5.7.3 Why use separate interface files?

    +

    5.7.3 Why use separate interface files?

    @@ -3422,7 +3436,7 @@ and immediately see what is available without having to dig it out of header files. -

    5.7.4 Getting the right header files

    +

    5.7.4 Getting the right header files

    @@ -3442,7 +3456,7 @@ include certain header files by using a %{,%} block like this: ... -

    5.7.5 What to do with main()

    +

    5.7.5 What to do with main()

    diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index d138073d9..24eaac0b5 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -1,12 +1,13 @@ - + SWIG and C++ + -

    6 SWIG and C++

    +

    6 SWIG and C++

      @@ -75,7 +76,7 @@ how SWIG wraps ANSI C. Support for C++ builds upon ANSI C wrapping and that material will be useful in understanding this chapter.

      -

      6.1 Comments on C++ Wrapping

      +

      6.1 Comments on C++ Wrapping

      @@ -117,7 +118,7 @@ crossing language boundaries and provides many opportunities to shoot yourself in the foot. You will just have to be careful.

      -

      6.2 Approach

      +

      6.2 Approach

      @@ -158,7 +159,7 @@ proxy classes. More detailed coverage can be found in the documentation for each target language.

      -

      6.3 Supported C++ features

      +

      6.3 Supported C++ features

      @@ -197,7 +198,7 @@ in future releases. However, we make no promises. Also, submitting a bug repor good way to get problems fixed (wink).

      -

      6.4 Command line options and compilation

      +

      6.4 Command line options and compilation

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

      6.5 Proxy classes

      +

      6.5 Proxy classes

      @@ -243,7 +244,7 @@ wrapped by a Python proxy class. Or if you're building a Java module, each C++ class is wrapped by a Java proxy class.

      -

      6.5.1 Construction of proxy classes

      +

      6.5.1 Construction of proxy classes

      @@ -255,11 +256,11 @@ C++ class like this:

       class Foo {
      -public:
      -      Foo();
      -     ~Foo();
      -      int  bar(int x);
      -      int  x;
      +  public:
      +    Foo();
      +    ~Foo();
      +    int  bar(int x);
      +    int  x;
       };
       
      @@ -271,24 +272,24 @@ Using C++ as pseudocode, a proxy class looks something like this:
       class FooProxy {
      -private:
      -      Foo    *self;
      -public:
      -      FooProxy() {
      -            self = new_Foo();
      -      }
      -     ~FooProxy() {
      -            delete_Foo(self);
      -      }
      -      int bar(int x) {
      -            return Foo_bar(self,x);
      -      }
      -      int x_get() {
      -            return Foo_x_get(self);
      -      }
      -      void x_set(int x) {
      -            Foo_x_set(self,x);
      -      }
      +  private:
      +    Foo    *self;
      +  public:
      +    FooProxy() {
      +      self = new_Foo();
      +    }
      +    ~FooProxy() {
      +      delete_Foo(self);
      +    }
      +    int bar(int x) {
      +      return Foo_bar(self,x);
      +    }
      +    int x_get() {
      +      return Foo_x_get(self);
      +    }
      +    void x_set(int x) {
      +      Foo_x_set(self,x);
      +    }
       };
       
      @@ -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.

    -

    6.5.2 Resource management in proxies

    +

    6.5.2 Resource management in proxies

    @@ -337,10 +338,10 @@ C++ code:

     class Foo {
     public:
    -      Foo();
    -     ~Foo();
    -      int bar(int x);
    -      int x;
    +  Foo();
    +  ~Foo();
    +  int bar(int x);
    +  int x;
     };
     
     class Spam {
    @@ -406,45 +407,45 @@ roughly like this:
     
     class FooProxy {
    -public:
    -      Foo    *self;
    -      int     thisown;
    +  public:
    +    Foo    *self;
    +    int     thisown;
     
    -      FooProxy() {
    -            self = new_Foo();
    -            thisown = 1;       // Newly created object
    -      }
    -     ~FooProxy() {
    -            if (thisown) delete_Foo(self);
    -      }
    -      ...
    -      // Ownership control API
    -      void disown() {
    -           thisown = 0;
    -      }
    -      void acquire() {
    -           thisown = 1;
    -      }
    +    FooProxy() {
    +      self = new_Foo();
    +      thisown = 1;       // Newly created object
    +    }
    +    ~FooProxy() {
    +      if (thisown) delete_Foo(self);
    +    }
    +    ...
    +    // Ownership control API
    +    void disown() {
    +      thisown = 0;
    +    }
    +    void acquire() {
    +      thisown = 1;
    +    }
     };
     
     class FooPtrProxy: public FooProxy {
     public:
    -      FooPtrProxy(Foo *s) {
    -          self = s;
    -          thisown = 0;
    -      }
    +  FooPtrProxy(Foo *s) {
    +    self = s;
    +    thisown = 0;
    +  }
     };
     
     class SpamProxy {
    -     ...
    -     FooProxy *value_get() {
    -          return FooPtrProxy(Spam_value_get(self));
    -     }
    -     void value_set(FooProxy *v) {
    -          Spam_value_set(self,v->self);
    -          v->disown();
    -     }
    -     ...
    +  ...
    +  FooProxy *value_get() {
    +    return FooPtrProxy(Spam_value_get(self));
    +  }
    +  void value_set(FooProxy *v) {
    +    Spam_value_set(self,v->self);
    +    v->disown();
    +  }
    +  ...
     };
     
    @@ -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.

    -

    6.5.3 Language specific details

    +

    6.5.3 Language specific details

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

    -

    6.6 Simple C++ wrapping

    +

    6.6 Simple C++ wrapping

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

    -

    6.6.1 Constructors and destructors

    +

    6.6.1 Constructors and destructors

    @@ -529,15 +530,15 @@ functions such as the following :

     List * new_List(void) {
    -	return new List;
    +  return new List;
     }
     void delete_List(List *l) {
    -	delete l;
    +  delete l;
     }
     
     
    -

    6.6.2 Default constructors, copy constructors and implicit destructors

    +

    6.6.2 Default constructors, copy constructors and implicit destructors

    @@ -686,7 +687,7 @@ leaks, and so it is strongly recommended to not use them.

    -

    6.6.3 When constructor wrappers aren't created

    +

    6.6.3 When constructor wrappers aren't created

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

    -

    6.6.4 Copy constructors

    +

    6.6.4 Copy constructors

    @@ -865,7 +866,7 @@ constructor is set to new_CopyFoo(). This is the same as in older versions.

    -

    6.6.5 Member functions

    +

    6.6.5 Member functions

    @@ -873,7 +874,7 @@ All member functions are roughly translated into accessor functions like this :<

     int List_search(List *obj, char *value) {
    -	return obj->search(value);
    +  return obj->search(value);
     }
     
     
    @@ -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.

    -

    6.6.6 Static members

    +

    6.6.6 Static members

    @@ -901,7 +902,7 @@ transformations. For example, the static member function in the generated wrapper code.

    -

    6.6.7 Member data

    +

    6.6.7 Member data

    @@ -911,11 +912,11 @@ structures. A pair of accessor functions are effectively created. For example

     int List_length_get(List *obj) {
    -	return obj->length;
    +  return obj->length;
     }
     int List_length_set(List *obj, int value) {
    -	obj->length = value;
    -	return value;
    +  obj->length = value;
    +  return value;
     }
     
     
    @@ -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.

    -

    6.7 Default arguments

    +

    6.7 Default arguments

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

    -

    6.8 Protection

    +

    6.8 Protection

    @@ -1219,7 +1220,7 @@ until you explicitly give a `public:' declaration (This is the same convention used by C++).

    -

    6.9 Enums and constants

    +

    6.9 Enums and constants

    @@ -1230,7 +1231,7 @@ into constants with the classname as a prefix. For example :

     class Swig {
     public:
    -	enum {ALE, LAGER, PORTER, STOUT};
    +  enum {ALE, LAGER, PORTER, STOUT};
     };
     
     
    @@ -1249,7 +1250,7 @@ Swig_STOUT = Swig::STOUT Members declared as const are wrapped as read-only members and do not create constants.

    -

    6.10 Friends

    +

    6.10 Friends

    @@ -1261,9 +1262,9 @@ you have this code:

     class Foo {
     public:
    -     ...
    -     friend void blah(Foo *f);
    -     ...
    +  ...
    +  friend void blah(Foo *f);
    +  ...
     };
     
    @@ -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.

    -

    6.11 References and pointers

    +

    6.11 References and pointers

    @@ -1320,7 +1321,7 @@ a declaration like this :

     class Foo {
     public:
    -	double bar(double &a);
    +  double bar(double &a);
     }
     
    @@ -1330,7 +1331,7 @@ has a low-level accessor
     double Foo_bar(Foo *obj, double *a) {
    -	obj->bar(*a);
    +  obj->bar(*a);
     }
     
    @@ -1363,7 +1364,7 @@ For example:
     class Bar {
     public:
    -     Foo &spam();
    +  Foo &spam();
     };
     
    @@ -1375,8 +1376,8 @@ Generates an accessor like this:
     Foo *Bar_spam(Bar *obj) {
    -   Foo &result = obj->spam();
    -   return &result;
    +  Foo &result = obj->spam();
    +  return &result;
     }
     
    @@ -1410,7 +1411,7 @@ templates and the STL. This was first added in SWIG-1.3.12.

    -

    6.12 Pass and return by value

    +

    6.12 Pass and return by value

    @@ -1432,10 +1433,10 @@ following:

     Vector *wrap_cross_product(Vector *a, Vector *b) {
    -   Vector x = *a;
    -   Vector y = *b;
    -   Vector r = cross_product(x,y);
    -   return new Vector(r);
    +  Vector x = *a;
    +  Vector y = *b;
    +  Vector r = cross_product(x,y);
    +  return new Vector(r);
     }
    @@ -1454,10 +1455,10 @@ called the "Fulton Transform". This produces a wrapper that looks like this:
     Vector cross_product(Vector *a, Vector *b) {
    -   SwigValueWrapper<Vector> x = *a;
    -   SwigValueWrapper<Vector> y = *b;
    -   SwigValueWrapper<Vector> r = cross_product(x,y);
    -   return new Vector(r);
    +  SwigValueWrapper<Vector> x = *a;
    +  SwigValueWrapper<Vector> y = *b;
    +  SwigValueWrapper<Vector> r = cross_product(x,y);
    +  return new Vector(r);
     }
     
    @@ -1514,7 +1515,7 @@ classes that don't define a default constructor. It is not used for C++ pointers or references.

    -

    6.13 Inheritance

    +

    6.13 Inheritance

    @@ -1549,24 +1550,24 @@ the full C++ code has been omitted.

    class Shape { public: - double x,y; - virtual double area() = 0; - virtual double perimeter() = 0; - void set_location(double x, double y); + double x,y; + virtual double area() = 0; + virtual double perimeter() = 0; + void set_location(double x, double y); }; class Circle : public Shape { public: - Circle(double radius); - ~Circle(); - double area(); - double perimeter(); + Circle(double radius); + ~Circle(); + double area(); + double perimeter(); }; class Square : public Shape { public: - Square(double size); - ~Square(); - double area(); - double perimeter(); + Square(double size); + ~Square(); + double area(); + double perimeter(); } @@ -1671,7 +1672,7 @@ Similarly, typedef allows unnamed structures to be used as base classes
     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

    +

    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.

    -

    6.15 Wrapping Overloaded Functions and Methods

    +

    6.15 Wrapping Overloaded Functions and Methods

    @@ -1843,10 +1844,10 @@ constructors. For example, if you supply SWIG with overloaded functions like th

     void foo(int x) {
    -   printf("x is %d\n", x);
    +  printf("x is %d\n", x);
     }
     void foo(char *x) {
    -   printf("x is '%s'\n", x);
    +  printf("x is '%s'\n", x);
     }
     
    @@ -1874,10 +1875,10 @@ this code,
     class Foo {
     public:
    -     Foo();
    -     Foo(const Foo &);   // Copy constructor
    -     void bar(int x);
    -     void bar(char *s, int y);
    +  Foo();
    +  Foo(const Foo &);   // Copy constructor
    +  void bar(int x);
    +  void bar(char *s, int y);
     };
     
    @@ -1895,7 +1896,7 @@ it might be used like this -

    6.15.1 Dispatch function generation

    +

    6.15.1 Dispatch function generation

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

    -

    6.15.2 Ambiguity in Overloading

    +

    6.15.2 Ambiguity in Overloading

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

    -

    6.15.3 Ambiguity resolution and renaming

    +

    6.15.3 Ambiguity resolution and renaming

    @@ -2192,9 +2193,9 @@ void foo(char *c); // Stays 'foo' (not renamed) class Spam { public: - void foo(int); // Becomes 'foo_i' - void foo(double); // Becomes 'foo_d' - ... + void foo(int); // Becomes 'foo_i' + void foo(double); // Becomes 'foo_d' + ... }; @@ -2226,23 +2227,23 @@ an entire class hierarchy with only a few declarations. For example: class Spam { public: - virtual void foo(int); // Renamed to foo_i - virtual void foo(double); // Renamed to foo_d - ... + virtual void foo(int); // Renamed to foo_i + virtual void foo(double); // Renamed to foo_d + ... }; class Bar : public Spam { public: - virtual void foo(int); // Renamed to foo_i - virtual void foo(double); // Renamed to foo_d -... + virtual void foo(int); // Renamed to foo_i + virtual void foo(double); // Renamed to foo_d + ... }; class Grok : public Bar { public: - virtual void foo(int); // Renamed to foo_i - virtual void foo(double); // Renamed to foo_d -... + virtual void foo(int); // Renamed to foo_i + virtual void foo(double); // Renamed to foo_d + ... }; @@ -2255,18 +2256,18 @@ class definition itself. For example:

     class Spam {
    -   %rename(foo_i) foo(int);
    -   %rename(foo_d) foo(double);
    +  %rename(foo_i) foo(int);
    +  %rename(foo_d) foo(double);
     public:
    -   virtual void foo(int);      // Renamed to foo_i
    -   virtual void foo(double);   // Renamed to foo_d
    -   ...
    +  virtual void foo(int);      // Renamed to foo_i
    +  virtual void foo(double);   // Renamed to foo_d
    +  ...
     };
     
     class Bar : public Spam {
     public:
    -   virtual void foo(int);      // Renamed to foo_i
    -   virtual void foo(double);   // Renamed to foo_d
    +  virtual void foo(int);      // Renamed to foo_i
    +  virtual void foo(double);   // Renamed to foo_d
     ...
     };
     
    @@ -2405,9 +2406,9 @@ For example, if you have a class like this:

     class Spam {
     public:
    -   ...
    -   void bar() const;
    -   ...
    +  ...
    +  void bar() const;
    +  ...
     };
     
    @@ -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:

     class Spam {
     public:
    -   ...
    -   void bar(int i=-1, double d=0.0);
    -   ...
    +  ...
    +  void bar(int i=-1, double d=0.0);
    +  ...
     };
     
    @@ -2567,7 +2569,7 @@ to wrapping methods with default arguments was introduced. -

    6.15.4 Comments on overloading

    +

    6.15.4 Comments on overloading

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

    -

    6.16 Wrapping overloaded operators

    +

    6.16 Wrapping overloaded operators

    @@ -2613,7 +2615,7 @@ public: } Complex operator*(const Complex &c) const { return Complex(rpart*c.rpart - ipart*c.ipart, - rpart*c.ipart + c.rpart*ipart); + rpart*c.ipart + c.rpart*ipart); } Complex operator-() const { return Complex(-rpart, -ipart); @@ -2658,9 +2660,9 @@ something like this pseudocode:

     _wrap_Complex___add__(args) {
    -   ... get args ...
    -   obj->operator+(args);
    -   ...
    +  ... get args ...
    +  obj->operator+(args);
    +  ...
     }
     
    @@ -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.
  • -

    6.17 Class extension

    +

    6.17 Class extension

    @@ -2786,17 +2807,17 @@ example : class Vector { public: - double x,y,z; - Vector(); - ~Vector(); - ... bunch of C++ methods ... - %extend { - char *__str__() { - static char temp[256]; - sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z); - return &temp[0]; - } - } + double x,y,z; + Vector(); + ~Vector(); + ... bunch of C++ methods ... + %extend { + char *__str__() { + static char temp[256]; + sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z); + return &temp[0]; + } + } }; @@ -2867,7 +2888,7 @@ be used to extend a structure with more than just methods, a more suitable directive name has been chosen.

    -

    6.18 Templates

    +

    6.18 Templates

    @@ -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) { ... };
    +  ...
     };
     
    @@ -3326,10 +3347,10 @@ To expand the template, simply use %template inside the class.
     class Foo {
     public:
    -     template<class T> void bar(T x, T y) { ... };
    -     ...
    -     %template(barint)    bar<int>;
    -     %template(bardouble) bar<double>;
    +  template<class T> void bar(T x, T y) { ... };
    +  ...
    +  %template(barint)    bar<int>;
    +  %template(bardouble) bar<double>;
     };
     
    @@ -3342,13 +3363,13 @@ Or, if you want to leave the original class definition alone, just do this:
     class Foo {
     public:
    -     template<class T> void bar(T x, T y) { ... };
    -     ...
    +  template<class T> void bar(T x, T y) { ... };
    +  ...
     };
     ...
     %extend Foo {
    -     %template(barint)    bar<int>;
    -     %template(bardouble) bar<double>;
    +  %template(barint)    bar<int>;
    +  %template(bardouble) bar<double>;
     };
     
    @@ -3361,8 +3382,8 @@ or simply
     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:
     
     template<class T1, class T2> struct pair {
    -   T1 first;
    -   T2 second;
    -   pair() : first(T1()), second(T2()) { }
    -   pair(const T1 &x, const T2 &y) : first(x), second(y) { }
    -   template<class U1, class U2> pair(const pair<U1,U2> &x) 
    -                                        : first(x.first),second(x.second) { }
    +  T1 first;
    +  T2 second;
    +  pair() : first(T1()), second(T2()) { }
    +  pair(const T1 &x, const T2 &y) : first(x), second(y) { }
    +  template<class U1, class U2> pair(const pair<U1,U2> &x)
    +                                       : first(x.first),second(x.second) { }
     };
     
    @@ -3460,7 +3481,7 @@ in the template class itself. For example:
     %extend pair {
    -   %template(pair) pair<T1,T2>;        // Generate default copy constructor
    +  %template(pair) pair<T1,T2>;        // Generate default copy constructor
     };
     
    @@ -3482,13 +3503,13 @@ Alternatively, you could expand the constructor template in selected instantiati // Create a default constructor only %extend pair<int,int> { - %template(paird) pair<int,int>; // Default constructor + %template(paird) pair<int,int>; // Default constructor }; // Create default and conversion constructors %extend pair<double,double> { - %template(paird) pair<double,dobule>; // Default constructor - %template(pairc) pair<int,int>; // Conversion constructor + %template(paird) pair<double,dobule>; // Default constructor + %template(pairc) pair<int,int>; // Conversion constructor };
    @@ -3502,8 +3523,8 @@ instead:
     // Create default and conversion constructors 
     %extend pair<double,double> {
    -   %template(pair) pair<double,dobule>;   // Default constructor
    -   %template(pair) pair<int,int>;         // Conversion constructor
    +  %template(pair) pair<double,dobule>;   // Default constructor
    +  %template(pair) pair<int,int>;         // Conversion constructor
     };
     
    @@ -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.
     

    -

    6.19 Namespaces

    +

    6.19 Namespaces

    @@ -3720,15 +3741,15 @@ encapsulate common functionality. For example:

     namespace math {
    -   double sin(double);
    -   double cos(double);
    +  double sin(double);
    +  double cos(double);
     
    -   class Complex {
    -      double im,re;
    -   public:
    -      ...
    -   };
    -   ...
    +  class Complex {
    +    double im,re;
    +  public:
    +    ...
    +  };
    +  ...
     };
     
    @@ -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,
     %module foo
     namespace foo {
    -   void bar(int);
    -   void spam();
    +  void bar(int);
    +  void spam();
     }
     
     namespace bar {
    -   void blah();
    +  void blah();
     }
     
     
    @@ -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.

    -

    6.19.1 The nspace feature for namespaces

    +

    6.19.1 The nspace feature for namespaces

    @@ -4231,7 +4252,7 @@ namespace MyWorld { Compatibility Note: The nspace feature was first introduced in SWIG-2.0.0.

    -

    6.20 Renaming templated types in namespaces

    +

    6.20 Renaming templated types in namespaces

    @@ -4309,7 +4330,7 @@ namespace Space { -

    6.21 Exception specifications

    +

    6.21 Exception specifications

    @@ -4344,7 +4365,7 @@ f = Foo() try: f.blah() except Error,e: - # e is a wrapped instance of "Error" + # e is a wrapped instance of "Error" @@ -4360,7 +4381,7 @@ Consult the "Exception hand The next section details a way of simulating an exception specification or replacing an existing one.

    -

    6.22 Exception handling with %catches

    +

    6.22 Exception handling with %catches

    @@ -4410,7 +4431,7 @@ just a single catch handler for the base class, EBase will be generated

    -

    6.23 Pointers to Members

    +

    6.23 Pointers to Members

    @@ -4460,7 +4481,7 @@ when checking types. However, no such support is currently provided for member pointers.

    -

    6.24 Smart pointers and operator->()

    +

    6.24 Smart pointers and operator->()

    @@ -4548,13 +4569,13 @@ code produces wrappers like this:

     int Foo_x_get(Foo *f) {
    -   return (*f)->x;
    +  return (*f)->x;
     }
     void Foo_x_set(Foo *f, int value) {
    -   (*f)->x = value;
    +  (*f)->x = value;
     }
     void Foo_bar(Foo *f) {
    -   (*f)->bar();
    +  (*f)->bar();
     }
     
    @@ -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

    +

    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 -

    6.26 Using declarations and inheritance

    +

    6.26 Using declarations and inheritance

    @@ -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); }; -

    6.27 Nested classes

    +

    6.27 Nested classes

    @@ -5071,7 +5093,7 @@ Nested class warnings could also not be suppressed using %warnfilter.

    -

    6.28 A brief rant about const-correctness

    +

    6.28 A brief rant about const-correctness

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

    -

    6.29 Where to go for more information

    +

    6.29 Where to go for more information

    diff --git a/Doc/Manual/Scilab.html b/Doc/Manual/Scilab.html index cb4a3af90..a1970e934 100644 --- a/Doc/Manual/Scilab.html +++ b/Doc/Manual/Scilab.html @@ -1,14 +1,15 @@ - + SWIG and Scilab + -

    39 SWIG and Scilab

    +

    39 SWIG and Scilab

    -

    39.3 A basic tour of C/C++ wrapping

    +

    39.3 A basic tour of C/C++ wrapping

    -

    39.3.1 Overview

    +

    39.3.1 Overview

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

    -

    39.3.2 Identifiers

    +

    39.3.2 Identifiers

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

    -

    39.3.3 Functions

    +

    39.3.3 Functions

    @@ -368,7 +369,7 @@ ans = 24. -

    39.3.3.1 Argument passing

    +

    39.3.3.1 Argument passing

    @@ -421,7 +422,7 @@ In Scilab, parameters are passed by value. The output (and inout) parameters are 7. -

    39.3.3.2 Multiple output arguments

    +

    39.3.3.2 Multiple output arguments

    @@ -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) { -

    39.3.4 Global variables

    +

    39.3.4 Global variables

    @@ -538,10 +540,10 @@ It works the same:

    -

    39.3.5 Constants and enumerations

    +

    39.3.5 Constants and enumerations

    -

    39.3.5.1 Constants

    +

    39.3.5.1 Constants

    @@ -682,7 +684,7 @@ are mapped to Scilab variables, with the same name: 3.14 -

    39.3.5.2 Enumerations

    +

    39.3.5.2 Enumerations

    @@ -747,15 +749,29 @@ typedef enum { RED, BLUE, GREEN } color; -

    39.3.6 Pointers

    +

    39.3.6 Pointers

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

    +--> example_Init();
    +
     --> f = fopen("junk", "w");
     --> typeof(f)
      ans  =
     
    -  pointer
    +  _p_FILE
     
     --> fputs("Hello World", f);
     --> fclose(f);
     
    +

    +Note: the type name _p_FILE which means "pointer to FILE". +

    +

    The user of a pointer is responsible for freeing it or, like in the example, closing any resources associated with it (just as is required in a C program).

    -

    39.3.6.1 Utility functions

    +

    39.3.6.1 Utility functions

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

    39.3.6.2 Null pointers

    + +

    39.3.6.2 Null pointers:

    -

    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
     
    -

    39.3.7 Structures

    +

    39.3.7 Structures

    @@ -872,6 +904,7 @@ Several functions are generated:

  • a destructor function delete_Foo() to release the struct pointer.
  • +

    Usage example:

    @@ -930,8 +963,21 @@ ans = 20. +

    +Note: the pointer to the struct works as described in Pointers. For example, the type of the struct pointer can be get with typeof, as following: +

    -

    39.3.8 C++ classes

    +
    +--> example_Init();
    +--> b = new_Bar();
    +--> typeof(b)
    + ans  =
    +
    +    _p_Bar
    +--> delete_Bar(b);
    +
    + +

    39.3.8 C++ classes

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

    39.3.9 C++ inheritance

    @@ -1056,7 +1120,47 @@ But we can use either use the get_perimeter() function of the parent cl 18.84 -

    39.3.10 Pointers, references, values, and arrays

    +

    39.3.10 C++ overloading

    + + +

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

    + +
    +%module example
    +
    +void magnify(Square *square, double factor) {
    +    square->size *= factor;
    +};
    +
    +void magnify(Circle *circle, double factor) {
    +    square->radius *= factor;
    +};
    +
    + +
    +--> example_Init();
    +--> c = new_Circle(3);
    +--> s = new_Square(2);
    +
    +--> magnify(c, 10);
    +--> Circle_get_radius(c)
    + ans  =
    +
    +   30;
    +--> magnify(s, 10);
    +--> Square_get_size(s)
    + ans  =
    +
    +   20;
    +
    + + +

    39.3.11 Pointers, references, values, and arrays

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

    -

    39.3.11 C++ templates

    +

    39.3.12 C++ templates

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

    -

    39.3.12 C++ operators

    +

    39.3.13 C++ operators

    @@ -1227,7 +1330,7 @@ private: -

    39.3.13 C++ namespaces

    +

    39.3.14 C++ namespaces

    @@ -1301,11 +1404,11 @@ namespace Bar {

    -Note: the nspace feature is not supported. +Note: the nspace feature is not supported.

    -

    39.3.14 C++ exceptions

    +

    39.3.15 C++ exceptions

    @@ -1388,17 +1491,17 @@ More complex or custom exception types require specific exception typemaps to be See the SWIG C++ documentation for more details.

    -

    39.3.15 C++ STL

    +

    39.3.16 C++ STL

    The Standard Template Library (STL) is partially supported. See STL for more details.

    -

    39.4 Type mappings and libraries

    +

    39.4 Type mappings and libraries

    -

    39.4.1 Default primitive type mappings

    +

    39.4.1 Default primitive type mappings

    @@ -1447,15 +1550,9 @@ The default behaviour is for SWIG to generate code that will give a runtime erro -

    39.4.2 Default type mappings for non-primitive types

    -

    -The default mapped type for C/C++ non-primitive types is the Scilab pointer, for example for C structs, C++ classes, etc... -

    - - -

    39.4.3 Arrays

    +

    39.4.2 Arrays

    @@ -1510,7 +1607,7 @@ void printArray(int values[], int len) { [ 0 1 2 3 ] -

    39.4.4 Pointer-to-pointers

    +

    39.4.3 Pointer-to-pointers

    @@ -1583,7 +1680,7 @@ void print_matrix(double **M, int nbRows, int nbCols) { -

    39.4.5 Matrices

    +

    39.4.4 Matrices

    @@ -1676,7 +1773,7 @@ The remarks made earlier for arrays also apply here:

  • There is no control while converting double values to integers, double values are truncated without any checking or warning.
  • -

    39.4.6 STL

    +

    39.4.5 STL

    @@ -1876,15 +1973,15 @@ ans = --> delete_PersonPtrSet(p); -

    39.5 Module initialization

    +

    39.5 Module initialization

    The wrapped module contains an initialization function to:

      -
    • initialize the SWIG runtime, which is necessary when working with the STL
    • -
    • initialize in Scilab the module constants and enumerations declared with %scilabconst()
    • +
    • initialize the SWIG runtime, needed for pointer type tracking or when working with the STL
    • +
    • initialize the module constants and enumerations declared with %scilabconst()

    @@ -1900,7 +1997,7 @@ For example, to initialize the module example: --> example_Init(); -

    39.6 Building modes

    +

    39.6 Building modes

    @@ -1915,7 +2012,7 @@ To produce a dynamic module, when generating the wrapper, there are two possibil

  • the builder mode. In this mode, Scilab is responsible of building. -

    39.6.1 No-builder mode

    +

    39.6.1 No-builder mode

    @@ -1928,7 +2025,7 @@ This mode is the best option to use when you have to integrate the module build

    -

    39.6.2 Builder mode

    +

    39.6.2 Builder mode

    @@ -1968,14 +2065,14 @@ The command is: $ swig -scilab -builder -buildercflags -I/opt/foo/include -builderldflags "-L/opt/foo/lib -lfoo" -buildersources baa1.cxx,baa2.cxx example.i -

    39.7 Generated scripts

    +

    39.7 Generated scripts

    In this part we give some details about the generated Scilab scripts.

    -

    39.7.1 Builder script

    +

    39.7.1 Builder script

    @@ -2000,7 +2097,7 @@ ilib_build(ilib_name,table,files,libs);

  • table: two column string matrix containing a table of pairs of 'scilab function name', 'C function name'.
  • -

    39.7.2 Loader script

    +

    39.7.2 Loader script

    @@ -2039,7 +2136,7 @@ clear get_file_path; -

    39.8 Other resources

    +

    39.8 Other resources

      diff --git a/Doc/Manual/Scripting.html b/Doc/Manual/Scripting.html index c714fa0d7..18af78a68 100644 --- a/Doc/Manual/Scripting.html +++ b/Doc/Manual/Scripting.html @@ -1,12 +1,13 @@ - + Scripting Languages + -

      4 Scripting Languages

      +

      4 Scripting Languages

        @@ -37,7 +38,7 @@ programming and the mechanisms by which scripting language interpreters access C and C++ code.

        -

        4.1 The two language view of the world

        +

        4.1 The two language view of the world

        @@ -68,7 +69,7 @@ languages can be used for rapid prototyping, interactive debugging, scripting, and access to high-level data structures such associative arrays.

        -

        4.2 How does a scripting language talk to C?

        +

        4.2 How does a scripting language talk to C?

        @@ -93,7 +94,7 @@ function, arguments, and so forth. The next few sections illustrate the process.

        -

        4.2.1 Wrapper functions

        +

        4.2.1 Wrapper functions

        @@ -101,8 +102,10 @@ Suppose you have an ordinary C function like this :

         int fact(int n) {
        -	if (n <= 1) return 1;
        -	else return n*fact(n-1);
        +  if (n <= 1)
        +    return 1;
        +  else
        +    return n*fact(n-1);
         }
         
        @@ -123,18 +126,17 @@ As an example, the Tcl wrapper function for the fact() function above example might look like the following :

        -int wrap_fact(ClientData clientData, Tcl_Interp *interp,
        -		int argc, char *argv[]) {
        -	int result;
        -	int arg0;
        -	if (argc != 2) {
        -		interp->result = "wrong # args";
        -		return TCL_ERROR;
        -	}
        -	arg0 = atoi(argv[1]);
        -	result = fact(arg0);
        -	sprintf(interp->result,"%d", result);
        -	return TCL_OK;
        +int wrap_fact(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) {
        +  int result;
        +  int arg0;
        +  if (argc != 2) {
        +    interp->result = "wrong # args";
        +    return TCL_ERROR;
        +  }
        +  arg0 = atoi(argv[1]);
        +  result = fact(arg0);
        +  sprintf(interp->result,"%d", result);
        +  return TCL_OK;
         }
         
         
        @@ -148,9 +150,9 @@ requires code like the following :

         int Wrap_Init(Tcl_Interp *interp) {
        -	Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL,
        -				(Tcl_CmdDeleteProc *) NULL);
        -	return TCL_OK;
        +  Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL,
        +                    (Tcl_CmdDeleteProc *) NULL);
        +  return TCL_OK;
         }
         
        @@ -165,7 +167,7 @@ Python. Both require special wrappers to be written and both need additional initialization code. Only the specific details are different.

        -

        4.2.2 Variable linking

        +

        4.2.2 Variable linking

        @@ -201,7 +203,7 @@ typing $Foo = 4 would call the underlying set function to change the value.

        -

        4.2.3 Constants

        +

        4.2.3 Constants

        @@ -222,7 +224,7 @@ functions for creating variables so installing constants is usually a trivial exercise.

        -

        4.2.4 Structures and classes

        +

        4.2.4 Structures and classes

        @@ -243,9 +245,9 @@ representation of a structure. For example,

         struct Vector {
        -	Vector();
        -	~Vector();
        -	double x,y,z;
        +  Vector();
        +  ~Vector();
        +  double x,y,z;
         };
         
         
        @@ -283,7 +285,7 @@ internals of an object, the interpreter does not need to know anything about the actual representation of a Vector.

        -

        4.2.5 Proxy classes

        +

        4.2.5 Proxy classes

        @@ -298,9 +300,9 @@ have the following C++ definition :

         class Vector {
         public:
        -	Vector();
        -	~Vector();
        -	double x,y,z;
        +  Vector();
        +  ~Vector();
        +  double x,y,z;
         };
         
        @@ -345,7 +347,7 @@ affect both objects equally and for all practical purposes, it appears as if you are simply manipulating a C/C++ object.

        -

        4.3 Building scripting language extensions

        +

        4.3 Building scripting language extensions

        @@ -358,7 +360,7 @@ recompile the scripting language interpreter with your extensions added to it.

        -

        4.3.1 Shared libraries and dynamic loading

        +

        4.3.1 Shared libraries and dynamic loading

        @@ -400,7 +402,7 @@ changing the link line to the following :

        c++ -shared example.o example_wrap.o -o example.so
      -

      4.3.2 Linking with shared libraries

      +

      4.3.2 Linking with shared libraries

      @@ -447,7 +449,7 @@ the path using linker options instead.

    -

    4.3.3 Static linking

    +

    4.3.3 Static linking

    diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 4bf40c969..8417bec15 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -1,16 +1,19 @@ - + SWIG-3.0 Documentation + -

    SWIG-3.0 Documentation

    +

    SWIG-3.0 Documentation

    -Last update : SWIG-3.0.7 (in progress) +

    +Last update : SWIG-3.0.11 (in progress) +

    -

    Sections

    +

    Sections

    -

    SWIG Core Documentation

    +

    SWIG Core Documentation

    -

    Language Module Documentation

    +

    Language Module Documentation

    -

    Developer Documentation

    +

    Developer Documentation

    • Extending SWIG
    • diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index 874a5325a..af4880217 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -1,12 +1,13 @@ - + SWIG and Tcl + -

      40 SWIG and Tcl

      +

      40 SWIG and Tcl

        @@ -83,7 +84,7 @@ Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but this is no longer supported.

        -

        40.1 Preliminaries

        +

        40.1 Preliminaries

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

        -

        40.1.1 Getting the right header files

        +

        40.1.1 Getting the right header files

        @@ -127,7 +128,7 @@ this is the case, you should probably make a symbolic link so that tcl.h -

        40.1.2 Compiling a dynamic module

        +

        40.1.2 Compiling a dynamic module

        @@ -163,7 +164,7 @@ The name of the module is specified using the %module directive or the -module command line option.

        -

        40.1.3 Static linking

        +

        40.1.3 Static linking

        @@ -207,8 +208,8 @@ $ swig -tcl example.i $ gcc example.c example_wrap.c \ -Xlinker -export-dynamic \ -DHAVE_CONFIG_H -I/usr/local/include/ \ - -L/usr/local/lib -ltcl -lm -ldl \ - -o mytclsh + -L/usr/local/lib -ltcl -lm -ldl \ + -o mytclsh

      @@ -229,7 +230,7 @@ minimal in most situations (and quite frankly not worth the extra hassle in the opinion of this author).

      -

      40.1.4 Using your module

      +

      40.1.4 Using your module

      @@ -357,7 +358,7 @@ to the default system configuration (this requires root access and you will need the man pages).

      -

      40.1.5 Compilation of C++ extensions

      +

      40.1.5 Compilation of C++ extensions

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

      -

      40.1.6 Compiling for 64-bit platforms

      +

      40.1.6 Compiling for 64-bit platforms

      @@ -467,7 +468,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      40.1.7 Setting a package prefix

      +

      40.1.7 Setting a package prefix

      @@ -486,7 +487,7 @@ option will append the prefix to the name when creating a command and call it "Foo_bar".

      -

      40.1.8 Using namespaces

      +

      40.1.8 Using namespaces

      @@ -508,7 +509,7 @@ When the -namespace option is used, objects in the module are always accessed with the namespace name such as Foo::bar.

      -

      40.2 Building Tcl/Tk Extensions under Windows 95/NT

      +

      40.2 Building Tcl/Tk Extensions under Windows 95/NT

      @@ -519,7 +520,7 @@ covers the process of using SWIG with Microsoft Visual C++. although the procedure may be similar with other compilers.

      -

      40.2.1 Running SWIG from Developer Studio

      +

      40.2.1 Running SWIG from Developer Studio

      @@ -577,7 +578,7 @@ MSDOS > tclsh80 % -

      40.2.2 Using NMAKE

      +

      40.2.2 Using NMAKE

      @@ -625,11 +626,11 @@ CFLAGS = /Z7 /Od /c /nologo TCL_INCLUDES = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win TCLLIB = d:\tcl8.0a2\win\tcl80.lib -tcl:: - ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE) - $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE) - set LIB=$(TOOLS)\lib - $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj +tcl: + ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE) + $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE) + set LIB=$(TOOLS)\lib + $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj @@ -640,7 +641,7 @@ to get you started. With a little practice, you'll be making lots of Tcl extensions.

      -

      40.3 A tour of basic C/C++ wrapping

      +

      40.3 A tour of basic C/C++ wrapping

      @@ -651,7 +652,7 @@ classes. This section briefly covers the essential aspects of this wrapping.

      -

      40.3.1 Modules

      +

      40.3.1 Modules

      @@ -685,7 +686,7 @@ To fix this, supply an extra argument to load like this: -

      40.3.2 Functions

      +

      40.3.2 Functions

      @@ -710,7 +711,7 @@ like you think it does: % -

      40.3.3 Global variables

      +

      40.3.3 Global variables

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

      40.3.4 Constants and enums

      +

      40.3.4 Constants and enums

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

      -

      40.3.5 Pointers

      +

      40.3.5 Pointers

      @@ -948,12 +949,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) { @@ -970,7 +971,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

      -

      40.3.6 Structures

      +

      40.3.6 Structures

      @@ -980,7 +981,7 @@ This provides a very natural interface. For example,

       struct Vector {
      -	double x,y,z;
      +  double x,y,z;
       };
       
       
      @@ -1027,12 +1028,12 @@ can also be forced to be read-only using the %immutable directive. For
       struct Foo {
      -   ...
      -   %immutable;
      -   int x;        /* Read-only members */
      -   char *name;
      -   %mutable;
      -   ...
      +  ...
      +  %immutable;
      +  int x;        /* Read-only members */
      +  char *name;
      +  %mutable;
      +  ...
       };
       
      @@ -1099,11 +1100,11 @@ pointer. For example, suppose you have two structures like this:
       struct Foo {
      -   int a;
      +  int a;
       };
       
       struct Bar {
      -   Foo f;
      +  Foo f;
       };
       
      @@ -1252,7 +1253,7 @@ Note: Tcl only destroys the underlying object if it has ownership. See the memory management section that appears shortly.

      -

      40.3.7 C++ classes

      +

      40.3.7 C++ classes

      @@ -1301,9 +1302,8 @@ To illustrate, suppose you have a class like this:

       class Spam {
       public:
      -   static void foo();
      -   static int bar;
      -
      +  static void foo();
      +  static int bar;
       };
       
      @@ -1319,7 +1319,7 @@ In Tcl, the static member is accessed as follows: -

      40.3.8 C++ inheritance

      +

      40.3.8 C++ inheritance

      @@ -1368,7 +1368,7 @@ For instance: It is safe to use multiple inheritance with SWIG.

      -

      40.3.9 Pointers, references, values, and arrays

      +

      40.3.9 Pointers, references, values, and arrays

      @@ -1422,7 +1422,7 @@ to hold the result and a pointer is returned (Tcl will release this memory when the return value is garbage collected).

      -

      40.3.10 C++ overloaded functions

      +

      40.3.10 C++ overloaded functions

      @@ -1545,7 +1545,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      40.3.11 C++ operators

      +

      40.3.11 C++ operators

      @@ -1647,7 +1647,7 @@ There are ways to make this operator appear as part of the class using the % Keep reading.

      -

      40.3.12 C++ namespaces

      +

      40.3.12 C++ namespaces

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

      -

      40.3.13 C++ templates

      +

      40.3.13 C++ templates

      @@ -1730,12 +1730,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(); }; @@ -1763,7 +1763,7 @@ More details can be found in the SWIG and C++ -

      40.3.14 C++ Smart Pointers

      +

      40.3.14 C++ Smart Pointers

      @@ -1775,9 +1775,9 @@ that implements operator->() like this:

       template<class T> class SmartPtr {
      -   ...
      -   T *operator->();
      -   ...
      +  ...
      +  T *operator->();
      +  ...
       }
       
      @@ -1790,8 +1790,8 @@ Then, if you have a class like this,
       class Foo {
       public:
      -     int x;
      -     int bar();
      +  int x;
      +  int bar();
       };
       
      @@ -1847,7 +1847,7 @@ simply use the __deref__() method. For example: -

      40.4 Further details on the Tcl class interface

      +

      40.4 Further details on the Tcl class interface

      @@ -1860,7 +1860,7 @@ of low-level details were omitted. This section provides a brief overview of how the proxy classes work.

      -

      40.4.1 Proxy classes

      +

      40.4.1 Proxy classes

      @@ -1873,9 +1873,9 @@ have a class like this

       class Foo {
       public:
      -     int x;
      -     int spam(int);
      -     ...
      +  int x;
      +  int spam(int);
      +  ...
       
      @@ -1925,7 +1925,7 @@ function. This allows objects to be encapsulated objects that look a lot like as shown in the last section.

      -

      40.4.2 Memory management

      +

      40.4.2 Memory management

      @@ -2064,10 +2064,10 @@ change the ownership of an object. For instance, consider code like this:

       class Node {
      -   Object *value;
      +  Object *value;
       public:
      -   void set_value(Object *v) { value = v; }
      -   ...
      +  void set_value(Object *v) { value = v; }
      +  ...
       };
       
      @@ -2113,7 +2113,7 @@ typemaps--an advanced topic discussed later.

      -

      40.5 Input and output parameters

      +

      40.5 Input and output parameters

      @@ -2124,7 +2124,7 @@ example:

       void add(int x, int y, int *result) {
      -   *result = x + y;
      +  *result = x + y;
       }
       
      @@ -2136,7 +2136,7 @@ or perhaps
       int sub(int *x, int *y) {
      -   return *x+*y;
      +  return *x+*y;
       }
       
      @@ -2197,7 +2197,7 @@ If a function mutates one of its parameters like this,
       void negate(int *x) {
      -   *x = -(*x);
      +  *x = -(*x);
       }
       
      @@ -2301,7 +2301,7 @@ set c [lindex $dim 1] -

      40.6 Exception handling

      +

      40.6 Exception handling

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

      -

      40.7 Typemaps

      +

      40.7 Typemaps

      @@ -2452,7 +2452,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Tcl interface.

      -

      40.7.1 What is a typemap?

      +

      40.7.1 What is a typemap?

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

      40.7.2 Tcl typemaps

      +

      40.7.2 Tcl typemaps

      @@ -2707,7 +2710,7 @@ Initialize an argument to a value before any conversions occur. Examples of these methods will appear shortly.

      -

      40.7.3 Typemap variables

      +

      40.7.3 Typemap variables

      @@ -2778,7 +2781,7 @@ properly assigned. The Tcl name of the wrapper function being created. -

      40.7.4 Converting a Tcl list to a char **

      +

      40.7.4 Converting a Tcl list to a char **

      @@ -2793,36 +2796,36 @@ used as a char ** object. // This tells SWIG to treat char ** as a special case %typemap(in) char ** { - Tcl_Obj **listobjv; - int nitems; - int i; - if (Tcl_ListObjGetElements(interp, $input, &nitems, &listobjv) == TCL_ERROR) { - return TCL_ERROR; - } - $1 = (char **) malloc((nitems+1)*sizeof(char *)); - for (i = 0; i < nitems; i++) { - $1[i] = Tcl_GetStringFromObj(listobjv[i],0); - } - $1[i] = 0; + Tcl_Obj **listobjv; + int nitems; + int i; + if (Tcl_ListObjGetElements(interp, $input, &nitems, &listobjv) == TCL_ERROR) { + return TCL_ERROR; + } + $1 = (char **) malloc((nitems+1)*sizeof(char *)); + for (i = 0; i < nitems; i++) { + $1[i] = Tcl_GetStringFromObj(listobjv[i],0); + } + $1[i] = 0; } // This gives SWIG some cleanup code that will get called after the function call %typemap(freearg) char ** { - if ($1) { - free($1); - } + if ($1) { + free($1); + } } // Now a 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; -} + } %} %include "tclsh.i" @@ -2840,7 +2843,7 @@ argv[2] = Larry 3 -

      40.7.5 Returning values in arguments

      +

      40.7.5 Returning values in arguments

      @@ -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 : % -

      40.7.6 Useful functions

      +

      40.7.6 Useful functions

      @@ -2958,7 +2961,7 @@ int Tcl_IsShared(Tcl_Obj *obj); -

      40.7.7 Standard typemaps

      +

      40.7.7 Standard typemaps

      @@ -2975,10 +2978,10 @@ work)

       %typemap(in) int, short, long {
      -   int temp;
      -   if (Tcl_GetIntFromObj(interp, $input, &temp) == TCL_ERROR)
      -      return TCL_ERROR;
      -   $1 = ($1_ltype) temp;
      +  int temp;
      +  if (Tcl_GetIntFromObj(interp, $input, &temp) == TCL_ERROR)
      +    return TCL_ERROR;
      +  $1 = ($1_ltype) temp;
       }
       
      @@ -2988,7 +2991,7 @@ work)
       %typemap(out) int, short, long {
      -   Tcl_SetIntObj($result,(int) $1);
      +  Tcl_SetIntObj($result,(int) $1);
       }
       
      @@ -3000,10 +3003,10 @@ work)
       %typemap(in) float, double {
      -   double temp;
      -   if (Tcl_GetDoubleFromObj(interp, $input, &temp) == TCL_ERROR)
      -       return TCL_ERROR;
      -   $1 = ($1_ltype) temp;
      +  double temp;
      +  if (Tcl_GetDoubleFromObj(interp, $input, &temp) == TCL_ERROR)
      +    return TCL_ERROR;
      +  $1 = ($1_ltype) temp;
       }
       
      @@ -3013,7 +3016,7 @@ work)
       %typemap(out) float, double {
      -   Tcl_SetDoubleObj($result, $1);
      +  Tcl_SetDoubleObj($result, $1);
       }
       
      @@ -3025,9 +3028,8 @@ work)
       %typemap(in) char * {
      -   int len;
      -   $1 = Tcl_GetStringFromObj(interp, &len);
      -   }
      +  int len;
      +  $1 = Tcl_GetStringFromObj(interp, &len);
       }
       
      @@ -3043,7 +3045,7 @@ work) -

      40.7.8 Pointer handling

      +

      40.7.8 Pointer handling

      @@ -3086,7 +3088,9 @@ is usually accessed as follows:

       Foo *f;
      -if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
      +if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0))) {
      +  SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +}
       
       Tcl_Obj *;
       obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
      @@ -3101,7 +3105,9 @@ variable $1_descriptor.  For example:
       
       %typemap(in) Foo * {
      -   if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
      +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) {
      +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +  }
       }
       
      @@ -3114,12 +3120,14 @@ For example:
       %typemap(in) Foo * {
      -   if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
      +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $descriptor(Foo *), 0))) {
      +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
      +  }
       }
       
      -

      40.8 Turning a SWIG module into a Tcl Package.

      +

      40.8 Turning a SWIG module into a Tcl Package.

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

      +

      40.9 Building new kinds of Tcl interfaces (in Tcl)

      @@ -3264,14 +3272,14 @@ Our script allows easy array access as follows :

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

      -

      40.9.1 Proxy classes

      +

      40.9.1 Proxy classes

      @@ -3411,7 +3419,7 @@ short, but clever Tcl script can be combined with SWIG to do many interesting things.

      -

      40.10 Tcl/Tk Stubs

      +

      40.10 Tcl/Tk Stubs

      diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index 5f484531b..8aa5abb3f 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -1,12 +1,13 @@ - + Typemaps + -

      11 Typemaps

      +

      11 Typemaps

  • Common typemap methods
  • Typemaps and overloading -
  • More about %apply and %clear +
  • More about %apply and %clear
  • Passing data between typemaps
  • C++ "this" pointer
  • Where to go for more information? @@ -95,7 +99,7 @@ -

    11.1 Introduction

    +

    11.1 Introduction

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

    -

    11.1.1 Type conversion

    +

    11.1.1 Type conversion

    @@ -160,16 +164,16 @@ Inside the wrapper function, you might see these functions used like this:

     PyObject *wrap_factorial(PyObject *self, PyObject *args) {
    -    int       arg1;
    -    int       result;
    -    PyObject *obj1;
    -    PyObject *resultobj;
    +  int       arg1;
    +  int       result;
    +  PyObject *obj1;
    +  PyObject *resultobj;
     
    -    if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL;
    -    arg1 = PyInt_AsLong(obj1);
    -    result = factorial(arg1);
    -    resultobj = PyInt_FromLong(result);
    -    return resultobj;
    +  if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL;
    +  arg1 = PyInt_AsLong(obj1);
    +  result = factorial(arg1);
    +  resultobj = PyInt_FromLong(result);
    +  return resultobj;
     }
     
    @@ -205,7 +209,7 @@ to read the extension documentation for your favorite language to know how it works (an exercise left to the reader).

    -

    11.1.2 Typemaps

    +

    11.1.2 Typemaps

    @@ -218,12 +222,12 @@ a special %typemap directive is used. For example:

     /* Convert from Python --> C */
     %typemap(in) int {
    -    $1 = PyInt_AsLong($input);
    +  $1 = PyInt_AsLong($input);
     }
     
     /* Convert from C --> Python */
     %typemap(out) int {
    -    $result = PyInt_FromLong($1);
    +  $result = PyInt_FromLong($1);
     }
     
    @@ -266,33 +270,33 @@ A wrapper function would look approximately like this:
     PyObject *wrap_gcd(PyObject *self, PyObject *args) {
    -   int arg1;
    -   int arg2;
    -   int result;
    -   PyObject *obj1;
    -   PyObject *obj2;
    -   PyObject *resultobj;
    +  int arg1;
    +  int arg2;
    +  int result;
    +  PyObject *obj1;
    +  PyObject *obj2;
    +  PyObject *resultobj;
     
    -   if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL;
    +  if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL;
     
    -   /* "in" typemap, argument 1 */   
    -   {
    -      arg1 = PyInt_AsLong(obj1);
    -   }
    +  /* "in" typemap, argument 1 */
    +  {
    +    arg1 = PyInt_AsLong(obj1);
    +  }
     
    -   /* "in" typemap, argument 2 */
    -   {
    -      arg2 = PyInt_AsLong(obj2);
    -   }
    +  /* "in" typemap, argument 2 */
    +  {
    +    arg2 = PyInt_AsLong(obj2);
    +  }
     
    -   result = gcd(arg1,arg2);
    +  result = gcd(arg1,arg2);
     
    -   /* "out" typemap, return value */
    -   {
    -      resultobj = PyInt_FromLong(result);
    -   }
    +  /* "out" typemap, return value */
    +  {
    +    resultobj = PyInt_FromLong(result);
    +  }
     
    -   return resultobj;
    +  return resultobj;
     }
     
    @@ -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.

    -

    11.1.3 Pattern matching

    +

    11.1.3 Pattern matching

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

    -

    11.1.4 Reusing typemaps

    +

    11.1.4 Reusing typemaps

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

    -

    11.1.5 What can be done with typemaps?

    +

    11.1.5 What can be done with typemaps?

    @@ -485,7 +489,7 @@ int foo(int x, double y, char *s);

    • Input argument conversion ("in" typemap).
    • -
    • Input argument type checking ("typecheck" typemap).
    • +
    • Input argument type checking for types used in overloaded methods ("typecheck" typemap).
    • Output argument handling ("argout" typemap).
    • Input argument value checking ("check" typemap).
    • Input argument initialization ("arginit" typemap).
    • @@ -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.

      -

      11.1.6 What can't be done with typemaps?

      +

      11.1.6 What can't be done with typemaps?

      @@ -633,13 +637,13 @@ function instead. For example: %rename(foo) wrap_foo; %inline %{ void wrap_foo(char *s, int x) { - foo(x,s); + foo(x,s); } %}

    -

    11.1.7 Similarities to Aspect Oriented Programming

    +

    11.1.7 Similarities to Aspect Oriented Programming

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

    -

    11.1.8 The rest of this chapter

    +

    11.1.8 The rest of this chapter

    @@ -677,14 +681,14 @@ of "The C Programming Language" by Kernighan and Ritchie or "The C++ Programming Language" by Stroustrup before going any further.

    -

    11.2 Typemap specifications

    +

    11.2 Typemap specifications

    This section describes the behavior of the %typemap directive itself.

    -

    11.2.1 Defining a typemap

    +

    11.2.1 Defining a typemap

    @@ -747,7 +751,7 @@ code : { ... }

    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.

    -

    11.2.2 Typemap scope

    +

    11.2.2 Typemap scope

    @@ -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.
     };
     
    -

    11.2.3 Copying a typemap

    +

    11.2.3 Copying a typemap

    @@ -905,7 +909,7 @@ The patterns for %apply follow the same rules as for %typemap.

    -

    11.2.4 Deleting a typemap

    +

    11.2.4 Deleting a typemap

    @@ -938,7 +942,7 @@ For example: after the clear operation.

    -

    11.2.5 Placement of typemaps

    +

    11.2.5 Placement of typemaps

    @@ -949,22 +953,22 @@ example:

     %typemap(in) int {
    -   ...
    +  ...
     }
     
     namespace std {
    -    class string;
    -    %typemap(in) string {
    -        ...
    -    }
    +  class string;
    +  %typemap(in) string {
    +    ...
    +  }
     }
     
     class Bar {
     public:
    -    typedef const int & const_reference;
    -    %typemap(out) const_reference {
    -         ...
    -    }
    +  typedef const int & const_reference;
    +  %typemap(out) const_reference {
    +    ...
    +  }
     };
     
    @@ -978,10 +982,10 @@ code
     namespace std {
    -    class string;
    -    %typemap(in) string {
    -       ...
    -    }
    +  class string;
    +  %typemap(in) string {
    +    ...
    +  }
     }
     
    @@ -993,17 +997,17 @@ is really defining a typemap for the type std::string. You could have
     namespace std {
    -    class string;
    -    %typemap(in) string {          /* std::string */
    -       ...
    -    }
    +  class string;
    +  %typemap(in) string {          /* std::string */
    +    ...
    +  }
     }
     
     namespace Foo {
    -    class string;
    -    %typemap(in) string {          /* Foo::string */
    -       ...
    -    }
    +  class string;
    +  %typemap(in) string {          /* Foo::string */
    +    ...
    +  }
     }
     
    @@ -1018,7 +1022,7 @@ It should be noted that for scoping to work, SWIG has to know that stringclass string.

    -

    11.3 Pattern matching rules

    +

    11.3 Pattern matching rules

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

    -

    11.3.1 Basic matching rules

    +

    11.3.1 Basic matching rules

    @@ -1092,23 +1096,23 @@ shows how some of the basic rules are applied:

     %typemap(in) int *x {
    -   ... typemap 1
    +  ... typemap 1
     }
     
     %typemap(in) int * {
    -   ... typemap 2
    +  ... typemap 2
     }
     
     %typemap(in) const int *z {
    -   ... typemap 3
    +  ... typemap 3
     }
     
     %typemap(in) int [4] {
    -   ... typemap 4
    +  ... typemap 4
     }
     
     %typemap(in) int [ANY] {
    -   ... typemap 5
    +  ... typemap 5
     }
     
     void A(int *x);        // int *x rule       (typemap 1)
    @@ -1125,7 +1129,7 @@ void F(int x[1000]);   // int [ANY] rule    (typemap 5)
     stripped all qualifiers in one step.
     

    -

    11.3.2 Typedef reductions matching

    +

    11.3.2 Typedef reductions matching

    @@ -1137,7 +1141,7 @@ for the reduced type. To illustrate, suppose you had code like this:

     %typemap(in) int {
    -   ... typemap 1
    +  ... typemap 1
     }
     
     typedef int Integer;
    @@ -1181,11 +1185,11 @@ typedef double  pdouble;     // Positive double
     
     // typemap 1
     %typemap(in) double {
    -   ... get a double ...
    +  ... get a double ...
     }
     // typemap 2
     %typemap(in) pdouble {
    -   ... get a positive double ...
    +  ... get a positive double ...
     }
     double sin(double x);           // typemap 1
     pdouble sqrt(pdouble x);        // typemap 2
    @@ -1300,7 +1304,7 @@ void go(Struct aStruct);
     
    -

    11.3.3 Default typemap matching rules

    +

    11.3.3 Default typemap matching rules

    @@ -1438,7 +1442,7 @@ Finally the best way to view the typemap matching rules in action is via the -

    11.3.4 Multi-arguments typemaps

    +

    11.3.4 Multi-arguments typemaps

    @@ -1449,11 +1453,11 @@ any typemaps specified for a single type. For example:

     %typemap(in) (char *buffer, int len) {
    -   // typemap 1
    +  // typemap 1
     }
     
     %typemap(in) char *buffer {
    -   // typemap 2
    +  // typemap 2
     }
     
     void foo(char *buffer, int len, int count); // (char *buffer, int len)
    @@ -1468,7 +1472,7 @@ but all subsequent arguments must match exactly.
     

    -

    11.3.5 Matching rules compared to C++ templates

    +

    11.3.5 Matching rules compared to C++ templates

    @@ -1627,7 +1631,7 @@ are similar to those for specialized template handling.

    -

    11.3.6 Debugging typemap pattern matching

    +

    11.3.6 Debugging typemap pattern matching

    @@ -1800,7 +1804,7 @@ void set_value(const char* val) {} %typemap(check) const char* val = char* NON_NULL; %typemap(arginit, noblock=1) const char* val { - $1 = ""; + $1 = ""; } void set_value(const char* val); @@ -1840,7 +1844,7 @@ Also the types may be displayed slightly differently - char const * and

  • -

    11.4 Code generation rules

    +

    11.4 Code generation rules

    @@ -1848,7 +1852,7 @@ This section describes rules by which typemap code is inserted into the generated wrapper code.

    -

    11.4.1 Scope

    +

    11.4.1 Scope

    @@ -1858,7 +1862,7 @@ When a typemap is defined like this:

     %typemap(in) int {
    -   $1 = PyInt_AsLong($input);
    +  $1 = PyInt_AsLong($input);
     }
     
    @@ -1871,12 +1875,12 @@ wrapper code will look like this:
     wrap_whatever() {
    -    ...
    -    // Typemap code
    -    {                    
    -       arg1 = PyInt_AsLong(obj1);
    -    }
    -    ...
    +  ...
    +  // Typemap code
    +  {
    +    arg1 = PyInt_AsLong(obj1);
    +  }
    +  ...
     }
     
    @@ -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.

    -

    11.4.2 Declaring new local variables

    +

    11.4.2 Declaring new local variables

    @@ -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:
     wrap_foo() {
    -   std::string temp;    <--- Declaration of temp goes here
    -   ...
    +  std::string temp;    <--- Declaration of temp goes here
    +  ...
     
    -   /* Typemap code */
    -   {
    -      ...
    -      temp.assign(s,len);
    -      ...
    -   } 
    -   ...
    +  /* Typemap code */
    +  {
    +    ...
    +    temp.assign(s,len);
    +    ...
    +  }
    +  ...
     }
     
    @@ -2017,35 +2021,35 @@ generated code would actually look like this:
     wrap_foo() {
    -   int *arg1;    /* Actual arguments */
    -   int *arg2;
    -   int *arg3;
    -   std::string temp1;    /* Locals declared in the typemap */
    -   std::string temp2;
    -   std::string temp3;
    -   ...
    -   {
    -       char *s;
    -       unsigned int len;
    -       ...
    -       temp1.assign(s,len);
    -       arg1 = *temp1;
    -   }
    -   {
    -       char *s;
    -       unsigned int len;
    -       ...
    -       temp2.assign(s,len);
    -       arg2 = &temp2;
    -   }
    -   {
    -       char *s;
    -       unsigned int len;
    -       ...
    -       temp3.assign(s,len);
    -       arg3 = &temp3;
    -   }
    -   ...
    +  int *arg1;    /* Actual arguments */
    +  int *arg2;
    +  int *arg3;
    +  std::string temp1;    /* Locals declared in the typemap */
    +  std::string temp2;
    +  std::string temp3;
    +  ...
    +  {
    +    char *s;
    +    unsigned int len;
    +    ...
    +    temp1.assign(s,len);
    +    arg1 = *temp1;
    +  }
    +  {
    +    char *s;
    +    unsigned int len;
    +    ...
    +    temp2.assign(s,len);
    +    arg2 = &temp2;
    +  }
    +  {
    +    char *s;
    +    unsigned int len;
    +    ...
    +    temp3.assign(s,len);
    +    arg3 = &temp3;
    +  }
    +  ...
     }
     
    @@ -2093,7 +2097,7 @@ each type must have its own local variable declaration. -

    11.4.3 Special variables

    +

    11.4.3 Special variables

    @@ -2233,7 +2237,7 @@ This is useful when a typemap might match multiple C datatype. For example:

     %typemap(in)  int, short, long {
    -   $1 = ($1_ltype) PyInt_AsLong($input);
    +  $1 = ($1_ltype) PyInt_AsLong($input);
     }
     
    @@ -2281,8 +2285,8 @@ If necessary, type related substitutions can also be used when declaring locals.
     %typemap(in) int * ($*1_type temp) {
    -    temp = PyInt_AsLong($input);
    -    $1 = &temp;
    +  temp = PyInt_AsLong($input);
    +  $1 = &temp;
     }
     
    @@ -2296,7 +2300,7 @@ kinds of pointers. For example, if you wrote this,
     %typemap(in) int [10][20] {
    -   $1_ltype temp;
    +  $1_ltype temp;
     }
     
    @@ -2322,10 +2326,10 @@ casts to get the correct type when needed. For example:
     %typemap(in) int [10][20] {
    -   void *temp;
    -   ...
    -   (($1_ltype) temp)[i][j] = x;    /* set a value */
    -   ...
    +  void *temp;
    +  ...
    +  (($1_ltype) temp)[i][j] = x;    /* set a value */
    +  ...
     }
     
    @@ -2337,15 +2341,15 @@ Another approach, which only works for arrays is to use the $1_basetype
     %typemap(in) int [10][20] {
    -   $1_basetype temp[10][20];
    -   ...
    -   temp[i][j] = x;    /* set a value */
    -   ...
    +  $1_basetype temp[10][20];
    +  ...
    +  temp[i][j] = x;    /* set a value */
    +  ...
     }
     
    -

    11.4.4 Special variable macros

    +

    11.4.4 Special variable macros

    @@ -2357,7 +2361,7 @@ it is done during the SWIG parsing/compilation stages. The following special variable macros are available across all language modules.

    -

    11.4.4.1 $descriptor(type)

    +

    11.4.4.1 $descriptor(type)

    @@ -2368,7 +2372,7 @@ For example, $descriptor(std::vector<int> *) will expand into Run-time type checker usage section.

    -

    11.4.4.2 $typemap(method, typepattern)

    +

    11.4.4.2 $typemap(method, typepattern)

    @@ -2425,7 +2429,77 @@ The result is the following expansion -

    11.5 Common typemap methods

    + +

    11.4.5 Special variables and typemap attributes

    + + +

    +As of SWIG-3.0.7 typemap attributes will also expand special variables and special variable macros. +

    + +

    +Example usage showing the expansion in the 'out' attribute (C# specific) as well as the main typemap body: +

    + +
    +
    +%typemap(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"
    +
    +
    + +

    11.4.6 Special variables combined with special variable macros

    + + +

    +Special variables can also be used within special variable macros. +The special variables are expanded before they are used in the special variable macros. +

    + +

    +Consider the following C# typemaps: +

    + +
    +
    +%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) unsigned int "uint"
    +%typemap(cstype, out="$typemap(cstype, unsigned int)") unsigned int& "$typemap(cstype, unsigned int)"
    +
    +
    + +

    +which then expands to: +

    + +
    +
    +%typemap(cstype) unsigned int "uint"
    +%typemap(cstype, out="uint") unsigned int& "uint"
    +
    +
    + + +

    11.5 Common typemap methods

    @@ -2433,7 +2507,7 @@ The set of typemaps recognized by a language module may vary. However, the following typemap methods are nearly universal:

    -

    11.5.1 "in" typemap

    +

    11.5.1 "in" typemap

    @@ -2444,7 +2518,7 @@ to C. For example:

     %typemap(in) int {
    -   $1 = PyInt_AsLong($input);
    +  $1 = PyInt_AsLong($input);
     }
     
    @@ -2474,7 +2548,7 @@ specified. The numinputs attributes facilitates this. For example:
     // Ignored argument.
     %typemap(in, numinputs=0) int *out (int temp) {
    -    $1 = &temp;
    +  $1 = &temp;
     }
     
    @@ -2493,7 +2567,7 @@ Usually numinputs is not specified, whereupon the default value is 1, t is the same as the old "ignore" typemap.

    -

    11.5.2 "typecheck" typemap

    +

    11.5.2 "typecheck" typemap

    @@ -2504,7 +2578,7 @@ to see whether or not it matches a specific type. For example:

     %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
    -   $1 = PyInt_Check($input) ? 1 : 0;
    +  $1 = PyInt_Check($input) ? 1 : 0;
     }
     
    @@ -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.

    -

    11.5.3 "out" typemap

    +

    11.5.3 "out" typemap

    @@ -2530,7 +2605,7 @@ into the target language. For example:

     %typemap(out) int {
    -   $result = PyInt_FromLong($1);
    +  $result = PyInt_FromLong($1);
     }
     
    @@ -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.

    -

    11.5.4 "arginit" typemap

    +

    11.5.4 "arginit" typemap

    @@ -2564,12 +2639,12 @@ For example:

     // Set argument to NULL before any conversion occurs
     %typemap(arginit) int *data {
    -   $1 = NULL;
    +  $1 = NULL;
     }
     
    -

    11.5.5 "default" typemap

    +

    11.5.5 "default" typemap

    @@ -2580,7 +2655,7 @@ argument. For example:

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

    -

    11.5.6 "check" typemap

    +

    11.5.6 "check" typemap

    @@ -2614,14 +2689,14 @@ converted. For example:

     %typemap(check) int positive {
    -   if ($1 <= 0) {
    -       SWIG_exception(SWIG_ValueError,"Expected positive value.");
    -   }
    +  if ($1 <= 0) {
    +    SWIG_exception(SWIG_ValueError,"Expected positive value.");
    +  }
     }
     
    -

    11.5.7 "argout" typemap

    +

    11.5.7 "argout" typemap

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

    -

    11.5.8 "freearg" typemap

    +

    11.5.8 "freearg" typemap

    @@ -2682,12 +2757,12 @@ For example:

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

    -

    11.5.9 "newfree" typemap

    +

    11.5.9 "newfree" typemap

    @@ -2712,10 +2787,10 @@ of a function. For example:

     %typemap(newfree) string * {
    -   delete $1;
    +  delete $1;
     }
     %typemap(out) string * {
    -   $result = PyString_FromString($1->c_str());
    +  $result = PyString_FromString($1->c_str());
     }
     ...
     
    @@ -2729,7 +2804,46 @@ string *foo();
     See Object ownership and %newobject for further details.
     

    -

    11.5.10 "memberin" typemap

    +

    11.5.10 "ret" typemap

    + + +

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

    + +
    +
    +%typemap(ret) stringheap_t %{
    +  free($1);
    +%}
    +
    +typedef char * string_t;
    +typedef char * stringheap_t;
    +
    +string_t MakeString1();
    +stringheap_t MakeString2();
    +
    +
    + +

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

    + +

    11.5.11 "memberin" typemap

    @@ -2741,7 +2855,7 @@ cases. For example:

     %typemap(memberin) int [4] {
    -   memmove($1, $input, 4*sizeof(int));
    +  memmove($1, $input, 4*sizeof(int));
     }
     
    @@ -2751,7 +2865,7 @@ It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

    -

    11.5.11 "varin" typemap

    +

    11.5.12 "varin" typemap

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

    -

    11.5.12 "varout" typemap

    +

    11.5.13 "varout" typemap

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

    -

    11.5.13 "throws" typemap

    +

    11.5.14 "throws" typemap

    @@ -2797,12 +2911,11 @@ with the catch block comprising the "throws" typemap content.

     ...
     try {
    -    bar();
    +  bar();
     }
     catch(char const *_e) {
    -    PyErr_SetString(PyExc_RuntimeError, _e);
    -    SWIG_fail;
    -    
    +  PyErr_SetString(PyExc_RuntimeError, _e);
    +  SWIG_fail;
     }
     ...
     
    @@ -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.

    -

    11.6 Some typemap examples

    +

    11.6 Some typemap examples

    @@ -2821,7 +2934,7 @@ This section contains a few examples. Consult language module documentation for more examples.

    -

    11.6.1 Typemaps for arrays

    +

    11.6.1 Typemaps for arrays

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

     %typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
    -   ... convert a 2d array ...
    +  ... convert a 2d array ...
     }
     
    @@ -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:
     struct SomeObject {
    -	float  value[4];
    -        ...
    +  float  value[4];
    +  ...
     };
     
    @@ -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.

    -

    11.6.2 Implementing constraints with typemaps

    +

    11.6.2 Implementing constraints with typemaps

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

    -

    11.7 Typemaps for multiple target languages

    +

    11.7 Typemaps for multiple target languages

    @@ -3158,7 +3271,7 @@ The example above also shows a common approach of issuing a warning for an as ye %typemap(ruby,in) int "$1 = NUM2INT($input);".

    -

    11.8 Optimal code generation when returning by value

    +

    11.8 Optimal code generation when returning by value

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

    -

    11.9 Multi-argument typemaps

    +

    11.9 Multi-argument typemaps

    @@ -3371,7 +3484,7 @@ list of strings like this:

    ->>> foo(["ale","lager","stout"])
    +>>> foo(["ale", "lager", "stout"])
     
    @@ -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.

    -

    11.10 Typemap warnings

    +

    11.10 Typemap warnings

    @@ -3623,7 +3746,7 @@ See the information in the issuing warnings

    -

    11.11 Typemap fragments

    +

    11.11 Typemap fragments

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

    -

    11.11.1 Fragment type specialization

    +

    11.11.1 Fragment type specialization

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

    +

    11.11.2 Fragments and automatic typemap specialization

    @@ -3955,7 +4078,7 @@ The interested (or very brave) reader can take a look at the fragments.swg file

    -

    11.12 The run-time type checker

    +

    11.12 The run-time type checker

    @@ -3981,7 +4104,7 @@ language modules.

  • Modules can be unloaded from the type system.
  • -

    11.12.1 Implementation

    +

    11.12.1 Implementation

    @@ -4016,15 +4139,18 @@ For example:

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

    -if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;
    +if (!SWIG_IsOK(SWIG_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_Foo, 0))) {
    +  SWIG_exception_fail(SWIG_TypeError, "in method 'GrabVal', expecting type Foo");
    +}
     
    @@ -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.

    -

    11.12.2 Usage

    +

    11.12.2 Usage

    This section covers how to use these functions from typemaps. To learn how to @@ -4182,7 +4313,9 @@ similar to this:

     %typemap(in) Foo * {
    -  if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) return NULL;
    +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) {
    +    SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
    +  }
     }
     
    @@ -4215,12 +4348,12 @@ descriptor name for any C datatype. For example:
     %typemap(in) Foo * {
    -  if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) {
    -     Bar *temp;
    -     if ((SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar *)) == -1) {
    -         return NULL;
    -     }
    -     $1 = (Foo *) temp;
    +  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) {
    +    Bar *temp;
    +    if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar *), 0))) {
    +      SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo or Bar");
    +    }
    +    $1 = (Foo *)temp;
       }
     }
     
    @@ -4261,7 +4394,7 @@ probably just look at the output of SWIG to get a better sense for how types are managed.

    -

    11.13 Typemaps and overloading

    +

    11.13 Typemaps and overloading

    @@ -4306,32 +4439,32 @@ For example, the above functions would produce something roughly like this:

     // wrapper pseudocode
     _wrap_foo_0(argc, args[]) {       // foo(int)
    -   int arg1;
    -   int result;
    -   ...
    -   arg1 = FromInteger(args[0]);
    -   result = foo(arg1);
    -   return ToInteger(result);
    +  int arg1;
    +  int result;
    +  ...
    +  arg1 = FromInteger(args[0]);
    +  result = foo(arg1);
    +  return ToInteger(result);
     }
     
     _wrap_foo_1(argc, args[]) {       // foo(double)
    -   double arg1;
    -   int result;
    -   ...
    -   arg1 = FromDouble(args[0]);
    -   result = foo(arg1);
    -   return ToInteger(result);
    +  double arg1;
    +  int result;
    +  ...
    +  arg1 = FromDouble(args[0]);
    +  result = foo(arg1);
    +  return ToInteger(result);
     }
     
     _wrap_foo_2(argc, args[]) {       // foo(char *, int)
    -   char *arg1;
    -   int   arg2;
    -   int result;
    -   ...
    -   arg1 = FromString(args[0]);
    -   arg2 = FromInteger(args[1]);
    -   result = foo(arg1,arg2);
    -   return ToInteger(result);
    +  char *arg1;
    +  int   arg2;
    +  int result;
    +  ...
    +  arg1 = FromString(args[0]);
    +  arg2 = FromInteger(args[1]);
    +  result = foo(arg1,arg2);
    +  return ToInteger(result);
     }
     
     
    @@ -4344,20 +4477,20 @@ Next, a dynamic dispatch function is generated:
     _wrap_foo(argc, args[]) {
    -   if (argc == 1) {
    -       if (IsInteger(args[0])) {
    -           return _wrap_foo_0(argc,args);
    -       } 
    -       if (IsDouble(args[0])) {
    -           return _wrap_foo_1(argc,args);
    -       }
    -   }
    -   if (argc == 2) {
    -       if (IsString(args[0]) && IsInteger(args[1])) {
    -          return _wrap_foo_2(argc,args);
    -       }
    -   }
    -   error("No matching function!\n");
    +  if (argc == 1) {
    +    if (IsInteger(args[0])) {
    +      return _wrap_foo_0(argc,args);
    +    }
    +    if (IsDouble(args[0])) {
    +      return _wrap_foo_1(argc,args);
    +    }
    +  }
    +  if (argc == 2) {
    +    if (IsString(args[0]) && IsInteger(args[1])) {
    +      return _wrap_foo_2(argc,args);
    +    }
    +  }
    +  error("No matching function!\n");
     }
     
    @@ -4438,22 +4571,22 @@ The following excerpt from the Python module illustrates this: /* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */ %typecheck(SWIG_TYPECHECK_INTEGER) - int, short, long, - unsigned int, unsigned short, unsigned long, - signed char, unsigned char, - long long, unsigned long long, - const int &, const short &, const long &, - const unsigned int &, const unsigned short &, const unsigned long &, - const long long &, const unsigned long long &, - enum SWIGTYPE, - bool, const bool & + int, short, long, + unsigned int, unsigned short, unsigned long, + signed char, unsigned char, + long long, unsigned long long, + const int &, const short &, const long &, + const unsigned int &, const unsigned short &, const unsigned long &, + const long long &, const unsigned long long &, + enum SWIGTYPE, + bool, const bool & { $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; } %typecheck(SWIG_TYPECHECK_DOUBLE) - float, double, - const float &, const double & + float, double, + const float &, const double & { $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; } @@ -4466,38 +4599,13 @@ The following excerpt from the Python module illustrates this: $1 = PyString_Check($input) ? 1 : 0; } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { - void *ptr; - if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == -1) { - $1 = 0; - PyErr_Clear(); - } else { - $1 = 1; - } +%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE * { + void *vptr = 0; + int res = SWIG_ConvertPtr($input, &vptr, $1_descriptor, 0); + $1 = SWIG_IsOK(res) ? 1 : 0; } -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { - void *ptr; - if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0) == -1) { - $1 = 0; - PyErr_Clear(); - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_VOIDPTR) void * { - void *ptr; - if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0) == -1) { - $1 = 0; - PyErr_Clear(); - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_POINTER) PyObject * -{ +%typecheck(SWIG_TYPECHECK_POINTER) PyObject * { $1 = ($input != 0); } @@ -4529,11 +4637,11 @@ Here is an example,
     // Typemap for a C++ string
     %typemap(in) std::string {
    -    if (PyString_Check($input)) {
    -         $1 = std::string(PyString_AsString($input));
    -     } else {
    -         SWIG_exception(SWIG_TypeError, "string expected");
    -     }
    +  if (PyString_Check($input)) {
    +    $1 = std::string(PyString_AsString($input));
    +  } else {
    +    SWIG_exception(SWIG_TypeError, "string expected");
    +  }
     }
     // Copy the typecheck code for "char *".  
     %typemap(typecheck) std::string = char *;
    @@ -4552,7 +4660,7 @@ If you write a typecheck typemap and omit the precedence level, for example comm
     
     %typemap(typecheck /*,precedence=SWIG_TYPECHECK_INTEGER*/) int {
    -   $1 = PyInt_Check($input) ? 1 : 0;
    +  $1 = PyInt_Check($input) ? 1 : 0;
     }
     
    @@ -4592,7 +4700,7 @@ Subsequent "in" typemaps would then perform more extensive type-checking. -

    11.14 More about %apply and %clear

    +

    11.14 More about %apply and %clear

    @@ -4604,10 +4712,10 @@ a set of typemaps like this:

     %typemap(in,numinputs=0) int *OUTPUT (int temp) {
    -   $1 = &temp;
    +  $1 = &temp;
     }
     %typemap(argout) int *OUTPUT {
    -   // return value somehow
    +  // return value somehow
     }
     
    @@ -4648,15 +4756,15 @@ For example:
     %typemap(in) int *INPUT (int temp) {
    -   temp = ... get value from $input ...;
    -   $1 = &temp;
    +  temp = ... get value from $input ...;
    +  $1 = &temp;
     }
     
     %typemap(check) int *POSITIVE {
    -   if (*$1 <= 0) {
    -      SWIG_exception(SWIG_ValueError,"Expected a positive number!\n");
    -      return NULL;
    -   }
    +  if (*$1 <= 0) {
    +    SWIG_exception(SWIG_ValueError,"Expected a positive number!\n");
    +    return NULL;
    +  }
     }
     
     ...
    @@ -4678,7 +4786,7 @@ example:
     
    -

    11.15 Passing data between typemaps

    +

    11.15 Passing data between typemaps

    @@ -4694,13 +4802,13 @@ to them. For example, you could do this:

     %typemap(in) int *(int temp) {
    -   temp = (int) PyInt_AsLong($input);
    -   $1 = &temp;
    +  temp = (int) PyInt_AsLong($input);
    +  $1 = &temp;
     }
     
     %typemap(argout) int * {
    -   PyObject *o = PyInt_FromLong(temp$argnum);
    -   ...
    +  PyObject *o = PyInt_FromLong(temp$argnum);
    +  ...
     }
     
    @@ -4715,7 +4823,7 @@ sure that the typemaps sharing information have exactly the same types and names

    -

    11.16 C++ "this" pointer

    +

    11.16 C++ "this" pointer

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

    -

    11.17 Where to go for more information?

    +

    11.17 Where to go for more information?

    diff --git a/Doc/Manual/Varargs.html b/Doc/Manual/Varargs.html index dac1ad7bc..7f15d6d27 100644 --- a/Doc/Manual/Varargs.html +++ b/Doc/Manual/Varargs.html @@ -1,12 +1,13 @@ - + Variable Length Arguments + -

    14 Variable Length Arguments

    +

    14 Variable Length Arguments

      @@ -42,7 +43,7 @@ added in SWIG-1.3.12. Most other wrapper generation tools have wisely chosen to avoid this issue.

      -

      14.1 Introduction

      +

      14.1 Introduction

      @@ -125,21 +126,21 @@ example:

       List make_list(const char *s, ...) {
      -    va_list ap;
      -    List    x;
      -    ...
      -    va_start(ap, s);
      -    while (s) {
      -       x.append(s);
      -       s = va_arg(ap, const char *);
      -    }
      -    va_end(ap);
      -    return x;
      +  va_list ap;
      +  List    x;
      +  ...
      +  va_start(ap, s);
      +  while (s) {
      +    x.append(s);
      +    s = va_arg(ap, const char *);
      +  }
      +  va_end(ap);
      +  return x;
       }
       
      -

      14.2 The Problem

      +

      14.2 The Problem

      @@ -187,12 +188,12 @@ In contrast, suppose you attempted to make some kind of wrapper around

       int wrap_printf(const char *fmt, ...) {
      -   va_list ap;
      -   va_start(ap,fmt);
      -   ...
      -   printf(fmt,ap);
      -   ...
      -   va_end(ap);
      +  va_list ap;
      +  va_start(ap,fmt);
      +  ...
      +  printf(fmt,ap);
      +  ...
      +  va_end(ap);
       };
       
      @@ -232,7 +233,7 @@ can also support real varargs wrapping (with stack-frame manipulation) if you are willing to get hands dirty. Keep reading.

      -

      14.3 Default varargs support

      +

      14.3 Default varargs support

      @@ -301,7 +302,7 @@ Read on for further solutions.

      -

      14.4 Argument replacement using %varargs

      +

      14.4 Argument replacement using %varargs

      @@ -412,7 +413,7 @@ mixed argument types such as printf(). Providing general purpose wrappers to such functions presents special problems (covered shortly).

      -

      14.5 Varargs and typemaps

      +

      14.5 Varargs and typemaps

      @@ -470,15 +471,15 @@ like this:

       wrap_printf() {
      -   char *arg1;
      -   void *arg2;
      -   int   result;
      +  char *arg1;
      +  void *arg2;
      +  int   result;
       
      -   arg1 = "%s";
      -   arg2 = (void *) PyString_AsString(arg2obj);
      -   ...
      -   result = printf(arg1,arg2);
      -   ...
      +  arg1 = "%s";
      +  arg2 = (void *) PyString_AsString(arg2obj);
      +  ...
      +  result = printf(arg1,arg2);
      +  ...
       }
       
      @@ -516,7 +517,7 @@ like this: argc = PyTuple_Size(varargs); if (argc > 10) { PyErr_SetString(PyExc_ValueError, "Too many arguments"); - return NULL; + SWIG_fail; } for (i = 0; i < argc; i++) { PyObject *pyobj = PyTuple_GetItem(varargs, i); @@ -524,16 +525,16 @@ like this: %#if PY_VERSION_HEX>=0x03000000 PyObject *pystr; if (!PyUnicode_Check(pyobj)) { - PyErr_SetString(PyExc_ValueError, "Expected a string"); - return NULL; + PyErr_SetString(PyExc_ValueError, "Expected a string"); + SWIG_fail; } pystr = PyUnicode_AsUTF8String(pyobj); str = strdup(PyBytes_AsString(pystr)); Py_XDECREF(pystr); %#else if (!PyString_Check(pyobj)) { - PyErr_SetString(PyExc_ValueError, "Expected a string"); - return NULL; + PyErr_SetString(PyExc_ValueError, "Expected a string"); + SWIG_fail; } str = PyString_AsString(pyobj); %#endif @@ -589,7 +590,7 @@ really want to elevate your guru status and increase your job security, continue to the next section.

      -

      14.6 Varargs wrapping with libffi

      +

      14.6 Varargs wrapping with libffi

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

      14.7 Wrapping of va_list

      +

      14.7 Wrapping of va_list

      @@ -895,7 +896,7 @@ int my_vprintf(const char *fmt, ...) {

    -

    14.8 C++ Issues

    +

    14.8 C++ Issues

    @@ -911,12 +912,12 @@ and it fully supports classes much like the %rename directive. For exa class Foo { public: - virtual void bar(char *arg, ...); // gets varargs above + virtual void bar(char *arg, ...); // gets varargs above }; class Spam: public Foo { public: - virtual void bar(char *arg, ...); // gets varargs above + virtual void bar(char *arg, ...); // gets varargs above }; @@ -951,9 +952,9 @@ are placed in arg2, arg3, and so forth. For example:

     %feature("action") Foo::bar {
    -   ...
    -   result = arg1->bar(arg2, arg3, etc.);
    -   ...
    +  ...
    +  result = arg1->bar(arg2, arg3, etc.);
    +  ...
     }
     
    @@ -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.

    -

    14.9 Discussion

    +

    14.9 Discussion

    @@ -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:
     
     #ifdef USE_LIBFFI
     %feature("action") printf {
    -   ...
    +  ...
     }
     #endif
     #ifdef USE_OTHERFFI
    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html
    index 2336120d3..e7b291f21 100644
    --- a/Doc/Manual/Warnings.html
    +++ b/Doc/Manual/Warnings.html
    @@ -1,12 +1,13 @@
    -
    +
     
     
     Warning Messages
     
    +
     
     
     
    -

    15 Warning Messages

    +

    15 Warning Messages

      @@ -35,7 +36,7 @@ -

      15.1 Introduction

      +

      15.1 Introduction

      @@ -55,7 +56,7 @@ where the generated wrapper code will probably compile, but it may not work like you expect.

      -

      15.2 Warning message suppression

      +

      15.2 Warning message suppression

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

    -

    15.3 Enabling extra warnings

    +

    15.3 Enabling extra warnings

    @@ -220,7 +221,7 @@ that is, any warnings suppressed or added in %warnfilter, #pragma S or the -w option.

    -

    15.4 Issuing a warning message

    +

    15.4 Issuing a warning message

    @@ -258,7 +259,7 @@ Warning messages can be associated with typemaps using the

     %typemap(in, warning="901:You are really going to regret this usage of $1_type $1_name") blah * {
    -   ...
    +  ...
     }
     
    @@ -274,7 +275,7 @@ example.i:24: Warning 901: You are really going to regret this usage of blah * s -

    15.5 Symbolic symbols

    +

    15.5 Symbolic symbols

    @@ -309,7 +310,7 @@ or -

    15.6 Commentary

    +

    15.6 Commentary

    @@ -326,7 +327,7 @@ no obvious recovery. There is no mechanism for suppressing error messages.

    -

    15.7 Warnings as errors

    +

    15.7 Warnings as errors

    @@ -335,7 +336,7 @@ option. This will cause SWIG to exit with a non successful exit code if a warning is encountered.

    -

    15.8 Message output format

    +

    15.8 Message output format

    @@ -354,10 +355,10 @@ $ swig -python -Fmicrosoft example.i example.i(4) : Syntax error in input(1). -

    15.9 Warning number reference

    +

    15.9 Warning number reference

    -

    15.9.1 Deprecated features (100-199)

    +

    15.9.1 Deprecated features (100-199)

      @@ -385,7 +386,7 @@ example.i(4) : Syntax error in input(1).
    • 126. The 'nestedworkaround' feature is deprecated.
    -

    15.9.2 Preprocessor (200-299)

    +

    15.9.2 Preprocessor (200-299)

      @@ -397,7 +398,7 @@ example.i(4) : Syntax error in input(1).
    • 206. Unexpected tokens after #directive directive.
    -

    15.9.3 C/C++ Parser (300-399)

    +

    15.9.3 C/C++ Parser (300-399)

      @@ -474,7 +475,7 @@ example.i(4) : Syntax error in input(1).
    • 395. operator delete[] ignored.
    -

    15.9.4 Types and typemaps (400-499)

    +

    15.9.4 Types and typemaps (400-499)

      @@ -505,7 +506,7 @@ example.i(4) : Syntax error in input(1). -

      15.9.5 Code generation (500-599)

      +

      15.9.5 Code generation (500-599)

        @@ -534,7 +535,7 @@ example.i(4) : Syntax error in input(1).
      • 523. Use of an illegal destructor name 'name' in %extend is deprecated, the destructor name should be 'name'.
      -

      15.9.6 Language module specific (700-899)

      +

      15.9.6 Language module specific (700-899)

        @@ -545,7 +546,7 @@ example.i(4) : Syntax error in input(1).
      • 810. No jni typemap defined for type (Java).
      • 811. No jtype typemap defined for type (Java).
      • 812. No jstype typemap defined for type (Java). -
      • 813. Warning for classname: Base baseclass ignored. Multiple inheritance is not supported in Java. (Java). +
      • 813. Warning for classname, base baseclass ignored. Multiple inheritance is not supported in Java. (Java).
      • 814.
      • 815. No javafinalize typemap defined for type (Java).
      • 816. No javabody typemap defined for type (Java). @@ -565,7 +566,7 @@ example.i(4) : Syntax error in input(1).
      • 830. No ctype typemap defined for type (C#).
      • 831. No cstype typemap defined for type (C#).
      • 832. No cswtype typemap defined for type (C#). -
      • 833. Warning for classname: Base baseclass ignored. Multiple inheritance is not supported in C#. (C#). +
      • 833. Warning for classname, base baseclass ignored. Multiple inheritance is not supported in C#. (C#).
      • 834.
      • 835. No csfinalize typemap defined for type (C#).
      • 836. No csbody typemap defined for type (C#). @@ -581,18 +582,18 @@ example.i(4) : Syntax error in input(1).
        -
      • 870. Warning for classname: Base baseclass ignored. Multiple inheritance is not supported in PHP. +
      • 870. Warning for classname: Base baseclass ignored. Multiple inheritance is not supported in PHP. (Php).
      • 871. Unrecognized pragma pragma. (Php).
      -

      15.9.7 User defined (900-999)

      +

      15.9.7 User defined (900-999)

      These numbers can be used by your own application.

      -

      15.10 History

      +

      15.10 History

      diff --git a/Doc/Manual/Windows.html b/Doc/Manual/Windows.html index d85737e52..b95105bdd 100644 --- a/Doc/Manual/Windows.html +++ b/Doc/Manual/Windows.html @@ -1,12 +1,13 @@ - + Getting started on Windows + -

      3 Getting started on Windows

      +

      3 Getting started on Windows

        @@ -52,7 +53,7 @@ Usage within the Unix like environments MinGW and Cygwin is also detailed.

        -

        3.1 Installation on Windows

        +

        3.1 Installation on Windows

        @@ -63,7 +64,7 @@ SWIG does not come with the usual Windows type installation program, however it

      • Set environment variables as described in the SWIG Windows Examples section in order to run examples using Visual C++.
      -

      3.1.1 Windows Executable

      +

      3.1.1 Windows Executable

      @@ -72,7 +73,7 @@ If you want to build your own swig.exe have a look at 3.2 SWIG Windows Examples +

      3.2 SWIG Windows Examples

      @@ -87,7 +88,7 @@ Alternatively run the examples using Cygwin More information on each of the examples is available with the examples distributed with SWIG (Examples/index.html). -

      3.2.1 Instructions for using the Examples with Visual Studio

      +

      3.2.1 Instructions for using the Examples with Visual Studio

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

      -

      3.2.1.1 C#

      +

      3.2.1.1 C#

      @@ -115,7 +116,7 @@ The accompanying C# and C++ project files are automatically used by the solution

      -

      3.2.1.2 Java

      +

      3.2.1.2 Java

      @@ -129,7 +130,7 @@ JAVA_BIN: D:\jdk1.3\bin

      -

      3.2.1.3 Perl

      +

      3.2.1.3 Perl

      @@ -143,7 +144,7 @@ PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib

      -

      3.2.1.4 Python

      +

      3.2.1.4 Python

      @@ -157,13 +158,13 @@ PYTHON_LIB: D:\python21\libs\python21.lib

      -

      3.2.1.5 TCL

      +

      3.2.1.5 TCL

      TCL_INCLUDE : Set this to the directory containing tcl.h
      TCL_LIB : Set this to the TCL library including path for linking

      -Example using ActiveTcl 8.3.3.3
      +Example using ActiveTcl 8.3.3.3
      TCL_INCLUDE: D:\tcl\include
      TCL_LIB: D:\tcl\lib\tcl83.lib
      @@ -171,7 +172,7 @@ TCL_LIB: D:\tcl\lib\tcl83.lib

      -

      3.2.1.6 R

      +

      3.2.1.6 R

      @@ -185,7 +186,7 @@ R_LIB: C:\Program Files\R\R-2.5.1\bin\Rdll.lib

      -

      3.2.1.7 Ruby

      +

      3.2.1.7 Ruby

      @@ -199,21 +200,21 @@ RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib

      -

      3.2.2 Instructions for using the Examples with other compilers

      +

      3.2.2 Instructions for using the Examples with other compilers

      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.

      -

      3.3 SWIG on Cygwin and MinGW

      +

      3.3 SWIG on Cygwin and MinGW

      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.

      -

      3.3.1 Building swig.exe on Windows

      +

      3.3.1 Building swig.exe on Windows

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

      -

      3.3.1.1 Building swig.exe using MinGW and MSYS

      +

      3.3.1.1 Building swig.exe using MinGW and MSYS

      @@ -341,7 +342,7 @@ make -

      3.3.1.2 Building swig.exe using Cygwin

      +

      3.3.1.2 Building swig.exe using Cygwin

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

      -

      3.3.1.3 Building swig.exe alternatives

      +

      3.3.1.3 Building swig.exe alternatives

      @@ -362,7 +363,7 @@ file in order to build swig.exe from the Visual C++ IDE.

      -

      3.3.2 Running the examples on Windows using Cygwin

      +

      3.3.2 Running the examples on Windows using Cygwin

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

      -

      3.4 Microsoft extensions and other Windows quirks

      +

      3.4 Microsoft extensions and other Windows quirks

      diff --git a/Doc/Manual/fixstyle.py b/Doc/Manual/fixstyle.py index 1007d5949..a36096890 100644 --- a/Doc/Manual/fixstyle.py +++ b/Doc/Manual/fixstyle.py @@ -1,6 +1,6 @@ #!/usr/bin/python -# Adds the SWIG stylesheet to the generated documentation on a single page +# Replace the inline htmldoc stylesheet with the SWIG stylesheet import sys import string @@ -14,11 +14,16 @@ swigstyle = "\n" + open("style.css").read() lines = data.splitlines() result = [ ] +skip = False for s in lines: - if s == "": + result.append(s) + skip = False data = "\n".join(result) diff --git a/Doc/Manual/index.html b/Doc/Manual/index.html index fbe105a7e..26cc81ea1 100644 --- a/Doc/Manual/index.html +++ b/Doc/Manual/index.html @@ -1,10 +1,11 @@ - + SWIG-3.0 Documentation + -

      SWIG-3.0 Documentation

      +

      SWIG-3.0 Documentation

      The SWIG documentation is available in one of the following formats.
        diff --git a/Doc/Manual/linkchecker.config b/Doc/Manual/linkchecker.config index a947b278a..9317a8940 100644 --- a/Doc/Manual/linkchecker.config +++ b/Doc/Manual/linkchecker.config @@ -1,5 +1,3 @@ -[checking] -anchors=1 - [filtering] ignorewarnings=http-robots-denied +ignorewarnings=https-certificate-error diff --git a/Doc/Manual/makechap.py b/Doc/Manual/makechap.py index 8225bfc79..61994e2a0 100644 --- a/Doc/Manual/makechap.py +++ b/Doc/Manual/makechap.py @@ -21,7 +21,7 @@ import string ############################################################################### # Regexs for -alink = re.compile(r"", re.IGNORECASE) +alink = re.compile(r".*", re.IGNORECASE) heading = re.compile(r"(_nn\d)", re.IGNORECASE) def getheadingname(m): @@ -38,6 +38,19 @@ def getheadingname(m): headingname = "%s_nn%d" % (filenamebase, nameindex) return headingname +# Return heading - 1.1. Introduction in the examples below: +# old style example:

        1.1 Introduction

        +# new style example:

        1.1 Introduction

        +def getheadingtext(m, s): + prevheadingtext_newstyle = m.group(2) + prevheadingtext_oldstyle = m.group(3) + if len(prevheadingtext_oldstyle) == 0 and len(prevheadingtext_newstyle) == 0: + raise RuntimeError("No heading text in line:\n%s" % s) + if len(prevheadingtext_oldstyle) > 0 and len(prevheadingtext_newstyle) > 0: + raise RuntimeError("Two heading texts, only one should be specified in line:\n%s" % s) + prevheadingtext = prevheadingtext_oldstyle if len(prevheadingtext_oldstyle) > 0 else prevheadingtext_newstyle + return prevheadingtext + ############################################################################### # Main program ############################################################################### @@ -59,11 +72,11 @@ name = "" # Regexs for

        ,...

        sections -h1 = re.compile(r".*?

        ()*[\d\.\s]*(.*?)

        ", re.IGNORECASE) -h2 = re.compile(r".*?

        ()*[\d\.\s]*(.*?)

        ", re.IGNORECASE) -h3 = re.compile(r".*?

        ()*[\d\.\s]*(.*?)

        ", re.IGNORECASE) -h4 = re.compile(r".*?

        ()*[\d\.\s]*(.*?)

        ", re.IGNORECASE) -h5 = re.compile(r".*?
        ()*[\d\.\s]*(.*?)
        ", re.IGNORECASE) +h1 = re.compile(r".*?

        (\s*[\d\s]*(.*?))*[\d\s]*(.*?)

        ", re.IGNORECASE) +h2 = re.compile(r".*?

        (\s*[\d\.\s]*(.*?))*[\d\.\s]*(.*?)

        ", re.IGNORECASE) +h3 = re.compile(r".*?

        (\s*[\d\.\s]*(.*?))*[\d\.\s]*(.*?)

        ", re.IGNORECASE) +h4 = re.compile(r".*?

        (\s*[\d\.\s]*(.*?))*[\d\.\s]*(.*?)

        ", re.IGNORECASE) +h5 = re.compile(r".*?
        (\s*[\d\.\s]*(.*?))*[\d\.\s]*(.*?)
        ", re.IGNORECASE) data = open(filename).read() # Read data open(filename+".bak","w").write(data) # Make backup @@ -95,10 +108,10 @@ for s in lines: m = h1.match(s) if m: - prevheadingtext = m.group(2) + prevheadingtext = getheadingtext(m, s) nameindex += 1 headingname = getheadingname(m) - result.append("""

        %d %s

        """ % (headingname,num,prevheadingtext)) + result.append("""

        %d %s

        """ % (headingname,num,prevheadingtext)) result.append("@INDEX@") section = 0 subsection = 0 @@ -109,11 +122,11 @@ for s in lines: continue m = h2.match(s) if m: - prevheadingtext = m.group(2) + prevheadingtext = getheadingtext(m, s) nameindex += 1 section += 1 headingname = getheadingname(m) - result.append("""

        %d.%d %s

        """ % (headingname,num,section, prevheadingtext)) + result.append("""

        %d.%d %s

        """ % (headingname,num,section, prevheadingtext)) if subsubsubsection: index += "
      \n" @@ -132,11 +145,11 @@ for s in lines: continue m = h3.match(s) if m: - prevheadingtext = m.group(2) + prevheadingtext = getheadingtext(m, s) nameindex += 1 subsection += 1 headingname = getheadingname(m) - result.append("""

      %d.%d.%d %s

      """ % (headingname,num,section, subsection, prevheadingtext)) + result.append("""

      %d.%d.%d %s

      """ % (headingname,num,section, subsection, prevheadingtext)) if subsubsubsection: index += "
    \n" @@ -151,12 +164,12 @@ for s in lines: continue m = h4.match(s) if m: - prevheadingtext = m.group(2) + prevheadingtext = getheadingtext(m, s) nameindex += 1 subsubsection += 1 headingname = getheadingname(m) - result.append("""

    %d.%d.%d.%d %s

    """ % (headingname,num,section, subsection, subsubsection, prevheadingtext)) + result.append("""

    %d.%d.%d.%d %s

    """ % (headingname,num,section, subsection, subsubsection, prevheadingtext)) if subsubsubsection: index += "\n" @@ -169,11 +182,11 @@ for s in lines: continue m = h5.match(s) if m: - prevheadingtext = m.group(2) + prevheadingtext = getheadingtext(m, s) nameindex += 1 subsubsubsection += 1 headingname = getheadingname(m) - result.append("""
    %d.%d.%d.%d.%d %s
    """ % (headingname,num,section, subsection, subsubsection, subsubsubsection, prevheadingtext)) + result.append("""
    %d.%d.%d.%d.%d %s
    """ % (headingname,num,section, subsection, subsubsection, subsubsubsection, prevheadingtext)) if subsubsubsection == 1: index += "
      \n" diff --git a/Doc/Manual/maketoc.py b/Doc/Manual/maketoc.py index d8c4aa759..dc8626434 100644 --- a/Doc/Manual/maketoc.py +++ b/Doc/Manual/maketoc.py @@ -6,12 +6,14 @@ chs = open("chapters").readlines() f = open("Contents.html","w") print >>f, """ - + SWIG Users Manual + +

      SWIG Users Manual

      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

      sections in the SWIG manual. -# This patch should only be used until the 1.9 branch of htmldoc -# stabilizes, since the 1.9 branch includes true CSS1 support. -# -# This patch only affects the PDF generation, an unpatched htmldoc -# creates the one-page html documentation just fine. -# -diff -Naur htmldoc-1.8.27/htmldoc/htmldoc.cxx htmldoc-1.8.27-margin-left/htmldoc/htmldoc.cxx ---- htmldoc-1.8.27/htmldoc/htmldoc.cxx 2006-03-30 14:01:20.000000000 +0100 -+++ htmldoc-1.8.27-margin-left/htmldoc/htmldoc.cxx 2013-05-11 10:11:47.428435647 +0100 -@@ -65,6 +65,8 @@ - const char *__XOS2RedirRoot(const char *); - } - #endif -+ -+extern void parse_style(char *); - - - /* -@@ -1115,6 +1117,7 @@ - else if (compare_strings(argv[i], "--version", 6) == 0) - { - puts(SVERSION); -+ puts("Patched with margin-left.patch"); - return (0); - } - else if (compare_strings(argv[i], "--webpage", 3) == 0) -@@ -2403,6 +2406,10 @@ - } - else if (strcmp(temp, "--cookies") == 0) - file_cookies(temp2); -+ else if (strcmp(temp, "--stylesheet") == 0) -+ { -+ parse_style(temp2); -+ } - } - } - -diff -Naur htmldoc-1.8.27/htmldoc/Makefile htmldoc-1.8.27-margin-left/htmldoc/Makefile ---- htmldoc-1.8.27/htmldoc/Makefile 2005-10-28 21:32:59.000000000 +0100 -+++ htmldoc-1.8.27-margin-left/htmldoc/Makefile 2013-05-11 09:39:04.392367869 +0100 -@@ -36,7 +36,7 @@ - OBJS = gui.o file.o html.o htmldoc.o htmllib.o htmlsep.o \ - http.o http-addr.o http-addrlist.o http-support.o image.o \ - iso8859.o license.o md5.o progress.o ps-pdf.o rc4.o \ -- snprintf.o string.o toc.o util.o -+ snprintf.o string.o toc.o util.o style.o - - - # -diff -Naur htmldoc-1.8.27/htmldoc/ps-pdf.cxx htmldoc-1.8.27-margin-left/htmldoc/ps-pdf.cxx ---- htmldoc-1.8.27/htmldoc/ps-pdf.cxx 2006-08-01 17:58:50.000000000 +0100 -+++ htmldoc-1.8.27-margin-left/htmldoc/ps-pdf.cxx 2013-05-11 09:37:40.096364957 +0100 -@@ -160,6 +160,7 @@ - # undef page_t - #endif // __hpux - -+extern int lookup_div_class(uchar *); - - /* - * Output options... -@@ -4230,9 +4231,24 @@ - para->child = para->last_child = NULL; - } - -- parse_doc(t->child, left, right, bottom, top, x, y, page, NULL, -+ { -+ int num_indent = 0; -+ uchar *cname; -+ -+ if (cname = htmlGetVariable(t, (uchar *)"class")) { -+ num_indent = lookup_div_class(cname); -+ *left += 5.0f * num_indent; -+ *x = *left; -+ } -+ -+ parse_doc(t->child, left, right, bottom, top, x, y, page, NULL, - needspace); - -+ if (num_indent > 0) { -+ *left -= 5.0f * num_indent; -+ } -+ } -+ - if (para->child != NULL) - { - parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace); -diff -Naur htmldoc-1.8.27/htmldoc/style.cxx htmldoc-1.8.27-margin-left/htmldoc/style.cxx ---- htmldoc-1.8.27/htmldoc/style.cxx 1970-01-01 01:00:00.000000000 +0100 -+++ htmldoc-1.8.27-margin-left/htmldoc/style.cxx 2013-05-11 09:37:40.096364957 +0100 -@@ -0,0 +1,185 @@ -+/* Extreamly simple parsing routines for CSS style sheets. -+ * We only parse div.class { } sections, and only look -+ * for margin-left: em; -+ * -+ * Copyright (C) 2005 John Lenz -+ * -+ * Released under GNU GPL v2 or above. -+ */ -+ -+#include -+#include -+#include -+#include -+#include -+ -+#include "types.h" -+ -+#define BUFF_SIZE 512 -+ -+struct div_entry { -+ uchar class_name[BUFF_SIZE]; -+ int indent; -+ struct div_entry *next; -+}; -+ -+static struct div_entry *head = 0; -+ -+/* These are the parsing states */ -+#define IGNORE_TILL_SEMI 0 -+#define IGNORE_TILL_CLOSE_BRACE 1 -+#define READING_DIV 2 -+#define READING_CLASS 3 -+#define READING_ATTRIBUTE 4 -+#define READING_NUM 5 -+#define CHECKING_ONLY_DIV 6 -+ -+static int at_eof = 0; -+ -+static int strucmp(uchar *a, uchar *b) { -+ int i; -+ for (i = 0; a[i] && b[i]; i++) { -+ if (a[i] < b[i]) return -1; -+ if (a[i] > b[i]) return 1; -+ } -+ /* This isn't right, but who cares...*/ -+ if (a[i] || b[i]) return 1; -+ return 0; -+} -+ -+static int read_word(FILE *f, const char *word) { -+ char c; -+ for (int idx = 0; word[idx]; idx++) { -+ c = getc(f); -+ if (c == EOF) { -+ at_eof = 1; -+ return 0; -+ } -+ if (c != word[idx]) -+ return 0; -+ } -+ return 1; -+} -+ -+int lookup_div_class(uchar *name) { -+ struct div_entry *node = head; -+ -+ while (node) { -+ if (strucmp(node->class_name, name) == 0) -+ return node->indent; -+ node = node->next; -+ } -+ -+ return 0; -+} -+ -+void parse_style(char *fname) { -+ FILE *f; -+ char c; -+ int state; -+ struct div_entry *cur = 0; -+ int class_idx = 0; -+ char num[BUFF_SIZE]; -+ int num_idx = 0; -+ -+ if (!fname) return; -+ -+ f = fopen(fname, "r"); -+ if (!f) { -+ fprintf(stderr, "Unable to parse style\n"); -+ return; -+ } -+ -+ state = READING_DIV; -+ while (!at_eof && (c = getc(f)) != EOF) { -+ switch (state) { -+ -+ case IGNORE_TILL_SEMI: -+ if (c == ';') -+ state = READING_ATTRIBUTE; -+ break; -+ -+ case IGNORE_TILL_CLOSE_BRACE: -+ if (c == '}') -+ state = READING_DIV; -+ break; -+ -+ case READING_DIV: -+ if (c != ' ' && c != '\t' && c != '\n') { -+ if (c == 'd' && read_word(f, "iv.")) { -+ state = READING_CLASS; -+ cur = (struct div_entry *) malloc(sizeof(struct div_entry)); -+ memset(cur, 0, sizeof(struct div_entry)); -+ class_idx = 0; -+ } else -+ state = IGNORE_TILL_CLOSE_BRACE; -+ } -+ break; -+ -+ case READING_CLASS: -+ if (isalpha(c)) { -+ if (class_idx >= BUFF_SIZE-1) { -+ fprintf(stderr, "class size %s too long\n", cur->class_name); -+ free(cur); -+ state = IGNORE_TILL_CLOSE_BRACE; -+ } else { -+ cur->class_name[class_idx++] = c; -+ } -+ } else { -+ if (c == '{') { -+ cur->next = head; -+ head = cur; -+ state = READING_ATTRIBUTE; -+ } else -+ state = CHECKING_ONLY_DIV; -+ } -+ break; -+ -+ case READING_ATTRIBUTE: -+ if (c != ' ' && c != '\t' && c != '\n') { -+ if (c == '}') -+ state = READING_DIV; -+ else { -+ if (c == 'm' && read_word(f, "argin-left:")) { -+ num_idx = 0; -+ memset(num, 0, sizeof(num)); -+ state = READING_NUM; -+ } else { -+ state = IGNORE_TILL_SEMI; -+ } -+ } -+ } -+ break; -+ -+ case READING_NUM: -+ if (isdigit(c)) { -+ if (num_idx >= BUFF_SIZE - 1) { -+ fprintf(stderr, "Number too long\n"); -+ state = IGNORE_TILL_SEMI; -+ } else { -+ num[num_idx++] = c; -+ } -+ } else if (c != ' ' && c != '\t') { -+ if (num_idx > 0 && c == 'e' && read_word(f, "m")) -+ cur->indent = atoi(num); -+ state = IGNORE_TILL_SEMI; -+ } -+ break; -+ -+ case CHECKING_ONLY_DIV: -+ if (c != ' ' && c != '\t' && c != '\n') { -+ if (c == '{') { -+ cur->next = head; -+ head = cur; -+ state = READING_ATTRIBUTE; -+ } else { -+ free(cur); -+ state = IGNORE_TILL_CLOSE_BRACE; -+ } -+ } -+ break; -+ } -+ } -+ -+ fclose(f); -+} diff --git a/Doc/Manual/style.css b/Doc/Manual/style.css index 02329e56f..45e51e35b 100644 --- a/Doc/Manual/style.css +++ b/Doc/Manual/style.css @@ -32,6 +32,7 @@ div.code { margin-left: 4em; margin-right: 4em; background-color: #F0FFFF; + font-family: "Courier New", Courier, "Courier 10 Pitch", monospace; } div.targetlang { @@ -41,9 +42,9 @@ div.targetlang { margin-left: 4em; margin-right: 4em; background-color: #d7f6bb; + font-family: "Courier New", Courier, "Courier 10 Pitch", monospace; } - div.shell { border-style: solid; border-width: 1px; @@ -51,6 +52,7 @@ div.shell { margin-left: 4em; margin-right: 4em; background-color: #DCDCDC; + font-family: "Courier New", Courier, "Courier 10 Pitch", monospace; } div.diagram { @@ -60,6 +62,7 @@ div.diagram { margin-left: 4em; margin-right: 4em; background-color: #FFEBCD; + font-family: "Courier New", Courier, "Courier 10 Pitch", monospace; } ul li p { @@ -82,3 +85,8 @@ div.indent p { margin-right: 0; } +pre, code, tt { + font-family: "Courier New", Courier, "Courier 10 Pitch", monospace; +} + +body { font-family: serif; } diff --git a/Examples/Makefile.in b/Examples/Makefile.in index aea834625..4b4be5ad3 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -58,7 +58,13 @@ INTERFACE = INTERFACEDIR = INTERFACEPATH = $(SRCDIR)$(INTERFACEDIR)$(INTERFACE) SWIGOPT = -SWIG = swig + +# SWIG_LIB_DIR and SWIGEXE must be explicitly set by Makefiles using this Makefile +SWIG_LIB_DIR = ./Lib +SWIGEXE = swig +SWIG_LIB_SET = @SWIG_LIB_SET@ +SWIGTOOL = +SWIG = $(SWIG_LIB_SET) $(SWIGTOOL) $(SWIGEXE) LIBM = @LIBM@ LIBC = @LIBC@ @@ -133,6 +139,13 @@ distclean: rm -f d/example.mk rm -f xml/Makefile +################################################################## +# Very generic invocation of swig +################################################################## + +swiginvoke: + $(SWIG) $(SWIGOPT) + ################################################################## ##### Tcl/Tk ###### ################################################################## @@ -314,11 +327,11 @@ else endif PYTHON_SO = @PYTHON_SO@ -# SWIG option for Python +# SWIG option for Python3 ifeq (,$(PY3)) - SWIGPYTHON = $(SWIG) -python + SWIGOPTPY3 = else - SWIGPYTHON = $(SWIG) -python -py3 + SWIGOPTPY3 = -py3 endif PEP8 = @PEP8@ @@ -329,7 +342,7 @@ PEP8_FLAGS = --ignore=E402,E501,E30,W291,W391 # ---------------------------------------------------------------- python: $(SRCDIR_SRCS) - $(SWIGPYTHON) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(SWIG) -python $(SWIGOPTPY3) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PYTHON_INCLUDE) $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) @@ -338,7 +351,7 @@ python: $(SRCDIR_SRCS) # ----------------------------------------------------------------- python_cpp: $(SRCDIR_SRCS) - $(SWIGPYTHON) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(SWIG) -python $(SWIGOPTPY3) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) @@ -354,12 +367,12 @@ TKINTER = PYTHON_LIBOPTS = $(PYTHON_LINK) @LIBS@ $(TKINTER) $(SYSLIBS) python_static: $(SRCDIR_SRCS) - $(SWIGPYTHON) -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(SWIG) -python $(SWIGOPTPY3) -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) python_static_cpp: $(SRCDIR_SRCS) - $(SWIGPYTHON) -c++ -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(SWIG) -python $(SWIGOPTPY3) -c++ -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) @@ -377,7 +390,7 @@ PY2TO3 = 2to3 `2to3 -l | grep -v -E "Available|import$$" | awk '{print "-f "$$0} python_run: $(PYSCRIPT) ifneq (,$(PEP8)) - $(PEP8) $(PEP8_FLAGS) $(PYSCRIPT) + $(COMPILETOOL) $(PEP8) $(PEP8_FLAGS) $(PYSCRIPT) endif env PYTHONPATH=$$PWD $(RUNTOOL) $(PYTHON) $(PYSCRIPT) $(RUNPIPE) @@ -416,7 +429,7 @@ python_clean: ################################################################## # Make sure these locate your Octave installation -OCTAVE = OCTAVE_HISTFILE=/dev/null @OCTAVE@ +OCTAVE = @OCTAVE@ OCTAVE_CXX = $(DEFS) @OCTAVE_CPPFLAGS@ @OCTAVE_CXXFLAGS@ # Extra Octave specific dynamic linking options @@ -450,7 +463,7 @@ octave_cpp: $(SRCDIR_SRCS) # ----------------------------------------------------------------- octave_run: - $(RUNTOOL) $(OCTAVE) $(OCTAVE_SCRIPT) $(RUNPIPE) + OCTAVE_HISTFILE=/dev/null $(RUNTOOL) $(OCTAVE) $(OCTAVE_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -574,6 +587,7 @@ JAVASO =@JAVASO@ JAVALDSHARED = @JAVALDSHARED@ JAVACXXSHARED = @JAVACXXSHARED@ JAVACFLAGS = @JAVACFLAGS@ +JAVAFLAGS = @JAVAFLAGS@ JAVA = @JAVA@ JAVAC = @JAVAC@ -d . @@ -607,7 +621,7 @@ java_compile: $(SRCDIR_SRCS) # ----------------------------------------------------------------- java_run: - env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(JAVA) $(RUNME) $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(JAVA) $(JAVAFLAGS) $(RUNME) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1084,7 +1098,7 @@ ruby_cpp_static: $(SRCDIR_SRCS) # ----------------------------------------------------------------- ruby_run: - $(RUNTOOL) $(RUBY) -I. $(RUBY_SCRIPT) $(RUNPIPE) + $(RUNTOOL) $(RUBY) $(RUBYFLAGS) -I. $(RUBY_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1103,7 +1117,57 @@ ruby_clean: rm -f *.@OBJEXT@ *$(RUBY_SO) ################################################################## -##### PHP ###### +##### PHP5 ###### +################################################################## + +PHP5 = @PHP5@ +PHP5_INCLUDE = @PHP5INC@ +PHP5_SO = @PHP5_SO@ +PHP5_SCRIPT = $(SRCDIR)$(RUNME).php + +# ------------------------------------------------------------------- +# Build a PHP5 dynamically loadable module (C) +# ------------------------------------------------------------------- + +php5: $(SRCDIR_SRCS) + $(SWIG) -php5 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PHP5_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP5_SO) + +# -------------------------------------------------------------------- +# Build a PHP5 dynamically loadable module (C++) +# -------------------------------------------------------------------- + +php5_cpp: $(SRCDIR_SRCS) + $(SWIG) -php5 -cppext cxx -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP5_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP5_SO) + +# ----------------------------------------------------------------- +# Running a PHP5 example +# ----------------------------------------------------------------- + +php5_run: + $(RUNTOOL) $(PHP5) -n -q -d extension_dir=. -d safe_mode=Off $(PHP5_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +php5_version: + $(PHP5) -v | head -n 1 + +# ----------------------------------------------------------------- +# Cleaning the PHP5 examples +# ----------------------------------------------------------------- + +php5_clean: + rm -f *_wrap* *~ .~* example.php php_example.h + rm -f core @EXTRA_CLEAN@ + rm -f *.@OBJEXT@ *$(PHP5_SO) + +################################################################## +##### PHP7 ###### ################################################################## PHP = @PHP@ @@ -1116,7 +1180,7 @@ PHP_SCRIPT = $(SRCDIR)$(RUNME).php # ------------------------------------------------------------------- php: $(SRCDIR_SRCS) - $(SWIG) -php $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(SWIG) -php7 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) @@ -1125,7 +1189,7 @@ php: $(SRCDIR_SRCS) # -------------------------------------------------------------------- php_cpp: $(SRCDIR_SRCS) - $(SWIG) -php -cppext cxx -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(SWIG) -php7 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) @@ -1448,6 +1512,12 @@ lua_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(INCLUDES) $(LUA_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) +lua_externalhdr: + $(SWIG) -lua -external-runtime $(TARGET) + +lua_swig_cpp: + $(SWIG) -c++ -lua $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + # ----------------------------------------------------------------- # Build statically linked Lua interpreter # ----------------------------------------------------------------- @@ -1652,7 +1722,8 @@ R = R RCXXSRCS = $(INTERFACE:.i=_wrap.cpp) #Need to use _wrap.cpp for R build system as it does not understand _wrap.cxx RRSRC = $(INTERFACE:.i=.R) R_CFLAGS=-fPIC -R_SCRIPT=$(RUNME).R +R_OPT = --slave --quiet --no-save --no-restore +R_SCRIPT=$(SRCDIR)$(RUNME).R # need to compile .cxx files outside of R build system to make sure that # we get -fPIC @@ -1684,7 +1755,7 @@ endif # ----------------------------------------------------------------- r_run: - $(RUNTOOL) $(R) CMD BATCH $(R_SCRIPT) $(RUNPIPE) + $(RUNTOOL) $(R) $(R_OPT) -f $(R_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display diff --git a/Examples/android/class/Makefile b/Examples/android/class/Makefile index 574566623..8b5a090e9 100644 --- a/Examples/android/class/Makefile +++ b/Examples/android/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = example INTERFACE = example.i INTERFACEDIR = jni/ @@ -13,8 +14,9 @@ TARGETID = 1 check: build build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ PROJECTNAME='$(PROJECTNAME)' TARGETID='$(TARGETID)' android_cpp install: diff --git a/Examples/android/extend/Makefile b/Examples/android/extend/Makefile index fb974d22c..19d90ecca 100644 --- a/Examples/android/extend/Makefile +++ b/Examples/android/extend/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = example INTERFACE = example.i INTERFACEDIR = jni/ @@ -13,8 +14,9 @@ TARGETID = 1 check: build build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ PROJECTNAME='$(PROJECTNAME)' TARGETID='$(TARGETID)' android_cpp install: diff --git a/Examples/android/simple/Makefile b/Examples/android/simple/Makefile index 2bf41968a..46bcd93ca 100644 --- a/Examples/android/simple/Makefile +++ b/Examples/android/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = example INTERFACE = example.i INTERFACEDIR = jni/ @@ -13,8 +14,9 @@ TARGETID = 1 check: build build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ PROJECTNAME='$(PROJECTNAME)' TARGETID='$(TARGETID)' android install: diff --git a/Examples/chicken/class/Makefile b/Examples/chicken/class/Makefile index a37ea4a85..ea2d8b62e 100644 --- a/Examples/chicken/class/Makefile +++ b/Examples/chicken/class/Makefile @@ -1,17 +1,18 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = example.i -SRCS = -CXXSRCS = example.cxx -TARGET = class -INCLUDE = -SWIGOPT = -VARIANT = +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +INTERFACE = example.i +SRCS = +CXXSRCS = example.cxx +TARGET = class +INCLUDE = +SWIGOPT = +VARIANT = # uncomment the following lines to build a static exe (only pick one of the CHICKEN_MAIN lines) #CHICKEN_MAIN = runme-lowlevel.scm #CHICKEN_MAIN = runme-tinyclos.scm -#VARIANT = _static +#VARIANT = _static check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CHICKEN_SCRIPT='runme-lowlevel.scm' chicken_run @@ -22,14 +23,16 @@ build: $(TARGET) $(TARGET)_proxy $(TARGET): $(INTERFACE) $(SRCS) $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp + INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp $(TARGET)_proxy: $(INTERFACE) $(SRCS) $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT) -proxy' TARGET='$(TARGET)_proxy' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp + INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean diff --git a/Examples/chicken/constants/Makefile b/Examples/chicken/constants/Makefile index 7167e866b..2fdde0a58 100644 --- a/Examples/chicken/constants/Makefile +++ b/Examples/chicken/constants/Makefile @@ -1,12 +1,13 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = example.i -SRCS = -CXXSRCS = -TARGET = constants -INCLUDE = -SWIGOPT = -VARIANT = +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +INTERFACE = example.i +SRCS = +CXXSRCS = +TARGET = constants +INCLUDE = +SWIGOPT = +VARIANT = # uncomment the following two lines to build a static exe #CHICKEN_MAIN = runme.scm @@ -20,8 +21,9 @@ build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) + INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean diff --git a/Examples/chicken/egg/Makefile b/Examples/chicken/egg/Makefile index 55aa114eb..0137dc0a7 100644 --- a/Examples/chicken/egg/Makefile +++ b/Examples/chicken/egg/Makefile @@ -1,4 +1,6 @@ -SWIG = ../../../preinst-swig +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib check: build cd eggs/install && csi ../../test.scm @@ -14,7 +16,7 @@ single: single_wrap.cxx # compile the single module with -nounit single_wrap.cxx: single.i - $(SWIG) -chicken -c++ -proxy -nounit single.i + $(SWIGEXE) -chicken -c++ -proxy -nounit single.i # Now build both mod1 and mod2 into a single egg multi: mod1_wrap.cxx mod2_wrap.cxx @@ -23,10 +25,10 @@ multi: mod1_wrap.cxx mod2_wrap.cxx rm -f mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx mod1_wrap.cxx: mod1.i - $(SWIG) -chicken -c++ -proxy mod1.i + $(SWIGEXE) -chicken -c++ -proxy mod1.i mod2_wrap.cxx: mod2.i - $(SWIG) -chicken -c++ -proxy mod2.i + $(SWIGEXE) -chicken -c++ -proxy mod2.i clean: rm -rf eggs diff --git a/Examples/chicken/multimap/Makefile b/Examples/chicken/multimap/Makefile index e8192e9cd..551d1c74d 100644 --- a/Examples/chicken/multimap/Makefile +++ b/Examples/chicken/multimap/Makefile @@ -1,16 +1,17 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = example.i -SRCS = example.c -CXXSRCS = -TARGET = multimap -INCLUDE = -SWIGOPT = -VARIANT = +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +INTERFACE = example.i +SRCS = example.c +CXXSRCS = +TARGET = multimap +INCLUDE = +SWIGOPT = +VARIANT = # uncomment the following two lines to build a static exe #CHICKEN_MAIN = runme.scm -#VARIANT = _static +#VARIANT = _static check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run @@ -20,8 +21,9 @@ build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) + INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean diff --git a/Examples/chicken/overload/Makefile b/Examples/chicken/overload/Makefile index a9647d93e..019390192 100644 --- a/Examples/chicken/overload/Makefile +++ b/Examples/chicken/overload/Makefile @@ -1,16 +1,17 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = example.i -SRCS = -CXXSRCS = example.cxx -TARGET = overload -INCLUDE = -SWIGOPT = -proxy -unhideprimitive -VARIANT = +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +INTERFACE = example.i +SRCS = +CXXSRCS = example.cxx +TARGET = overload +INCLUDE = +SWIGOPT = -proxy -unhideprimitive +VARIANT = # uncomment the following lines to build a static exe #CHICKEN_MAIN = runme.scm -#VARIANT = _static +#VARIANT = _static check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run @@ -20,8 +21,9 @@ build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp + INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean diff --git a/Examples/chicken/simple/Makefile b/Examples/chicken/simple/Makefile index c07075efa..f5dd1a966 100644 --- a/Examples/chicken/simple/Makefile +++ b/Examples/chicken/simple/Makefile @@ -1,16 +1,17 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -INTERFACE = example.i -SRCS = example.c -CXXSRCS = -TARGET = simple -INCLUDE = -SWIGOPT = -VARIANT = +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +INTERFACE = example.i +SRCS = example.c +CXXSRCS = +TARGET = simple +INCLUDE = +SWIGOPT = +VARIANT = # uncomment the following two lines to build a static exe #CHICKEN_MAIN = runme.scm -#VARIANT = _static +#VARIANT = _static check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run @@ -20,8 +21,9 @@ build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ - SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) + INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean diff --git a/Examples/csharp/arrays/Makefile b/Examples/csharp/arrays/Makefile index e5d733d35..66b2c2171 100644 --- a/Examples/csharp/arrays/Makefile +++ b/Examples/csharp/arrays/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_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)' csharp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/callback/Makefile b/Examples/csharp/callback/Makefile index 4f4c84b9a..c7f264ecc 100644 --- a/Examples/csharp/callback/Makefile +++ b/Examples/csharp/callback/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/class/Makefile b/Examples/csharp/class/Makefile index 4f4c84b9a..c7f264ecc 100644 --- a/Examples/csharp/class/Makefile +++ b/Examples/csharp/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/enum/Makefile b/Examples/csharp/enum/Makefile index 4f4c84b9a..c7f264ecc 100644 --- a/Examples/csharp/enum/Makefile +++ b/Examples/csharp/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/extend/Makefile b/Examples/csharp/extend/Makefile index 4f4c84b9a..c7f264ecc 100644 --- a/Examples/csharp/extend/Makefile +++ b/Examples/csharp/extend/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/funcptr/Makefile b/Examples/csharp/funcptr/Makefile index 99cdfa38a..9af1d66ff 100644 --- a/Examples/csharp/funcptr/Makefile +++ b/Examples/csharp/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 = example.c TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_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)' csharp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/nested/Makefile b/Examples/csharp/nested/Makefile index 4f4c84b9a..c7f264ecc 100644 --- a/Examples/csharp/nested/Makefile +++ b/Examples/csharp/nested/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/reference/Makefile b/Examples/csharp/reference/Makefile index 4f4c84b9a..c7f264ecc 100644 --- a/Examples/csharp/reference/Makefile +++ b/Examples/csharp/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/simple/Makefile b/Examples/csharp/simple/Makefile index 99cdfa38a..9af1d66ff 100644 --- a/Examples/csharp/simple/Makefile +++ b/Examples/csharp/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_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)' csharp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/template/Makefile b/Examples/csharp/template/Makefile index 2d0e07009..010447fe2 100644 --- a/Examples/csharp/template/Makefile +++ b/Examples/csharp/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/csharp/variables/Makefile b/Examples/csharp/variables/Makefile index 99cdfa38a..9af1d66ff 100644 --- a/Examples/csharp/variables/Makefile +++ b/Examples/csharp/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_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)' csharp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile diff --git a/Examples/d/example.mk.in b/Examples/d/example.mk.in index a1d9a85fc..84b3ceb09 100644 --- a/Examples/d/example.mk.in +++ b/Examples/d/example.mk.in @@ -23,7 +23,8 @@ endif EXAMPLES_TOP = ../../.. SWIG_TOP = ../../../.. -SWIG = $(SWIG_TOP)/preinst-swig +SWIGEXE = $(SWIG_TOP)/swig +SWIG_LIB_DIR = $(SWIG_TOP)/$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib EXTRA_CFLAGS = EXTRA_CXXFLAGS = EXTRA_LDFLAGS = @@ -44,11 +45,17 @@ check: build build: mkdir -p $(VERSION_DIR) if [ -f $(SRCDIR)example.cxx ]; then \ - $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' EXTRA_CXXFLAGS='$(EXTRA_CXXFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' CXXSRCS='example.cxx' d_cpp; \ + $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' EXTRA_CXXFLAGS='$(EXTRA_CXXFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' CXXSRCS='example.cxx' d_cpp; \ elif [ -f $(SRCDIR)example.c ]; then \ - $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' SRCS='example.c' d; \ + $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' SRCS='example.c' d; \ else \ - $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' SRCS='' d; \ + $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' SRCS='' d; \ fi $(MAKE) -C $(VERSION_DIR) -f $(EXAMPLES_TOP)/Makefile SRCDIR='../$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile diff --git a/Examples/go/callback/Makefile b/Examples/go/callback/Makefile index bf5275f14..86047367c 100644 --- a/Examples/go/callback/Makefile +++ b/Examples/go/callback/Makefile @@ -1,6 +1,8 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = callback.cxx +GOSRCS = gocallback.go TARGET = example INTERFACE = example.i SWIGOPT = @@ -9,8 +11,16 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + if [ -n '$(SRCDIR)' ]; then \ + cp $(GOSRCS:%=$(SRCDIR)/%) .; \ + fi + @# Note: example.go gets generated by SWIG + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' GOSRCS='example.go $(GOSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: + if [ -n '$(SRCDIR)' ]; then \ + rm -f $(GOSRCS); \ + fi $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/callback/example.h b/Examples/go/callback/example.h index 1a0e8c432..74ddad954 100644 --- a/Examples/go/callback/example.h +++ b/Examples/go/callback/example.h @@ -20,4 +20,3 @@ public: void setCallback(Callback *cb) { delCallback(); _callback = cb; } void call() { if (_callback) _callback->run(); } }; - diff --git a/Examples/go/callback/gocallback.go b/Examples/go/callback/gocallback.go new file mode 100644 index 000000000..20fd0627a --- /dev/null +++ b/Examples/go/callback/gocallback.go @@ -0,0 +1,41 @@ +package example + +import ( + "fmt" +) + +type GoCallback interface { + Callback + deleteCallback() + IsGoCallback() +} + +type goCallback struct { + Callback +} + +func (p *goCallback) deleteCallback() { + DeleteDirectorCallback(p.Callback) +} + +func (p *goCallback) IsGoCallback() {} + +type overwrittenMethodsOnCallback struct { + p Callback +} + +func NewGoCallback() GoCallback { + om := &overwrittenMethodsOnCallback{} + p := NewDirectorCallback(om) + om.p = p + + return &goCallback{Callback: p} +} + +func DeleteGoCallback(p GoCallback) { + p.deleteCallback() +} + +func (p *goCallback) Run() { + fmt.Println("GoCallback.Run") +} diff --git a/Examples/go/callback/index.html b/Examples/go/callback/index.html index b053cf547..9a53065b0 100644 --- a/Examples/go/callback/index.html +++ b/Examples/go/callback/index.html @@ -12,67 +12,17 @@

      Implementing C++ callbacks in Go

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

      diff --git a/Examples/go/callback/runme.go b/Examples/go/callback/runme.go index 2eef77fdb..03ab0c5e2 100644 --- a/Examples/go/callback/runme.go +++ b/Examples/go/callback/runme.go @@ -16,26 +16,18 @@ func main() { caller.Call() caller.DelCallback() - callback = NewDirectorCallback(new(GoCallback)) + go_callback := NewGoCallback() fmt.Println() fmt.Println("Adding and calling a Go callback") - fmt.Println("------------------------------------") + fmt.Println("--------------------------------") - caller.SetCallback(callback) + caller.SetCallback(go_callback) caller.Call() caller.DelCallback() - // Test that a double delete does not occur as the object has - // already been deleted from the C++ layer. - DeleteDirectorCallback(callback) + DeleteGoCallback(go_callback) fmt.Println() fmt.Println("Go exit") } - -type GoCallback struct{} - -func (p *GoCallback) Run() { - fmt.Println("GoCallback.Run") -} diff --git a/Examples/go/check.list b/Examples/go/check.list index 5399b8979..b3f34b306 100644 --- a/Examples/go/check.list +++ b/Examples/go/check.list @@ -2,6 +2,7 @@ callback class constants +director enum extend funcptr diff --git a/Examples/go/class/Makefile b/Examples/go/class/Makefile index de067cdd8..f72c067e6 100644 --- a/Examples/go/class/Makefile +++ b/Examples/go/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = class.cxx TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: diff --git a/Examples/go/constants/Makefile b/Examples/go/constants/Makefile index 8fb07fd6b..b791fc9cf 100644 --- a/Examples/go/constants/Makefile +++ b/Examples/go/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: diff --git a/Examples/go/director/Makefile b/Examples/go/director/Makefile new file mode 100644 index 000000000..430cac834 --- /dev/null +++ b/Examples/go/director/Makefile @@ -0,0 +1,26 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = +GOSRCS = director.go +TARGET = example +INTERFACE = example.i +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + +build: + if [ -n '$(SRCDIR)' ]; then \ + cp $(GOSRCS:%=$(SRCDIR)/%) .; \ + fi + @# Note: example.go gets generated by SWIG + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' GOSRCS='example.go $(GOSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp + +clean: + if [ -n '$(SRCDIR)' ]; then \ + rm -f $(GOSRCS); \ + fi + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/director/director.go b/Examples/go/director/director.go new file mode 100644 index 000000000..4f99bfc6d --- /dev/null +++ b/Examples/go/director/director.go @@ -0,0 +1,72 @@ +package example + +// 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() +} diff --git a/Examples/go/director/director.h b/Examples/go/director/director.h new file mode 100644 index 000000000..339a9adcd --- /dev/null +++ b/Examples/go/director/director.h @@ -0,0 +1,41 @@ +#ifndef DIRECTOR_H +#define DIRECTOR_H + + +#include +#include + + +class FooBarAbstract +{ +public: + FooBarAbstract() {}; + virtual ~FooBarAbstract() {}; + + std::string FooBar() { + return this->Foo() + ", " + this->Bar(); + }; + +protected: + virtual std::string Foo() { + return "Foo"; + }; + + virtual std::string Bar() = 0; +}; + + +class FooBarCpp : public FooBarAbstract +{ +protected: + virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); + } + + virtual std::string Bar() { + return "C++ Bar"; + } +}; + + +#endif diff --git a/Examples/go/director/example.i b/Examples/go/director/example.i new file mode 100644 index 000000000..e832bd8c6 --- /dev/null +++ b/Examples/go/director/example.i @@ -0,0 +1,11 @@ +/* File : example.i */ +%module(directors="1") example + +%include "std_string.i" + +%header %{ +#include "director.h" +%} + +%feature("director") FooBarAbstract; +%include "director.h" diff --git a/Examples/go/director/index.html b/Examples/go/director/index.html new file mode 100644 index 000000000..b93e780e5 --- /dev/null +++ b/Examples/go/director/index.html @@ -0,0 +1,28 @@ + + +SWIG:Examples:go:director + + + + +SWIG/Examples/go/director/ +
      + +

      How to subclass a C++ class with a Go type

      + +

      +See the Go Director +Classes documentation subsection for an explanation of this example. +

      + +

      +

        +
      • director.go. Go source with the definition of the FooBarGo class. +
      • director.h. Header with the definition of the FooBarAbstract and FooBarCpp classes. +
      • example.i. SWIG interface file. +
      • runme.go. Sample Go program. +
      + +
      + + diff --git a/Examples/go/director/runme.go b/Examples/go/director/runme.go new file mode 100644 index 000000000..0d839bc88 --- /dev/null +++ b/Examples/go/director/runme.go @@ -0,0 +1,39 @@ +package main + +import ( + "./example" + "fmt" + "os" +) + +func Compare(name string, got string, exp string) error { + fmt.Printf("%s; Got: '%s'; Expected: '%s'\n", name, got, exp) + if got != exp { + return fmt.Errorf("%s returned unexpected string! Got: '%s'; Expected: '%s'\n", name, got, exp) + } + return nil +} + +func TestFooBarCpp() error { + fb := example.NewFooBarCpp() + defer example.DeleteFooBarCpp(fb) + return Compare("FooBarCpp.FooBar()", fb.FooBar(), "C++ Foo, C++ Bar") +} + +func TestFooBarGo() error { + fb := example.NewFooBarGo() + defer example.DeleteFooBarGo(fb) + return Compare("FooBarGo.FooBar()", fb.FooBar(), "Go Foo, Go Bar") +} + +func main() { + fmt.Println("Test output:") + fmt.Println("------------") + err := TestFooBarCpp() + err = TestFooBarGo() + fmt.Println("------------") + if err != nil { + fmt.Fprintf(os.Stderr, "Tests failed! Last error: %s\n", err.Error()) + os.Exit(1) + } +} diff --git a/Examples/go/enum/Makefile b/Examples/go/enum/Makefile index 2e2f1b2bd..15defe905 100644 --- a/Examples/go/enum/Makefile +++ b/Examples/go/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = enum.cxx TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: diff --git a/Examples/go/extend/Makefile b/Examples/go/extend/Makefile index 290694210..a3c520e72 100644 --- a/Examples/go/extend/Makefile +++ b/Examples/go/extend/Makefile @@ -1,6 +1,8 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = extend.cxx +GOSRCS = ceo.go TARGET = example INTERFACE = example.i SWIGOPT = @@ -9,8 +11,16 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + if [ -n '$(SRCDIR)' ]; then \ + cp $(GOSRCS:%=$(SRCDIR)/%) .; \ + fi + @# Note: example.go gets generated by SWIG + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' GOSRCS='example.go $(GOSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: + if [ -n '$(SRCDIR)' ]; then \ + rm -f $(GOSRCS); \ + fi $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/extend/ceo.go b/Examples/go/extend/ceo.go new file mode 100644 index 000000000..8f00c92f2 --- /dev/null +++ b/Examples/go/extend/ceo.go @@ -0,0 +1,37 @@ +package example + +type CEO interface { + Manager + deleteManager() + IsCEO() +} + +type ceo struct { + Manager +} + +func (p *ceo) deleteManager() { + DeleteDirectorManager(p.Manager) +} + +func (p *ceo) IsCEO() {} + +type overwrittenMethodsOnManager struct { + p Manager +} + +func NewCEO(name string) CEO { + om := &overwrittenMethodsOnManager{} + p := NewDirectorManager(om, name) + om.p = p + + return &ceo{Manager: p} +} + +func DeleteCEO(p CEO) { + p.deleteManager() +} + +func (p *ceo) GetPosition() string { + return "CEO" +} diff --git a/Examples/go/extend/example.h b/Examples/go/extend/example.h index ca1aed28f..0c3b721bd 100644 --- a/Examples/go/extend/example.h +++ b/Examples/go/extend/example.h @@ -44,7 +44,7 @@ public: const Employee *get_item(int i) { return list[i]; } - ~EmployeeList() { + ~EmployeeList() { std::vector::iterator i; std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl; for (i=list.begin(); i!=list.end(); i++) { diff --git a/Examples/go/extend/index.html b/Examples/go/extend/index.html index 471fa9cdc..31788b2aa 100644 --- a/Examples/go/extend/index.html +++ b/Examples/go/extend/index.html @@ -12,13 +12,16 @@

      Extending a simple C++ class in Go

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

      +

        -
      • example.h. Header file containing some enums. -
      • example.i. Interface file. +
      • ceo.go. Go source with the definition of the CEO class. +
      • example.h. Header with the definition of the Employee, Manager and EmployeeList classes. +
      • example.i. SWIG interface file.
      • runme.go. Sample Go program.
      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.
    • template. C++ templates.
    • callback. C++ callbacks using directors.
    • extend. Polymorphism using directors. +
    • 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):
    -% swig -go interface.i
    -% gcc -fpic -c interface_wrap.c
    -% gcc -shared interface_wrap.o $(OBJS) -o interfacemodule.so 
    -% 6g interface.go
    -% 6c interface_gc.c
    -% gopack grc interface.a interface.6 interface_gc.6
    -% 6l program.6
    +% swig -go -cgo interface.i
    +% mkdir -p gopath/src/interface
    +% cp interface_wrap.c interface_wrap.h interface.go gopath/src/interface
    +% GOPATH=`pwd`/gopath
    +% export GOPATH
    +% cd gopath/src/interface
    +% go build
    +% go tool compile $(SRCDIR)/runme.go
    +% go tool link -o runme runme.o
     
    @@ -58,10 +62,15 @@ the 6g or 8g compiler, the steps look like this
    -% swig -go interface.i
    -% gcc -c interface_wrap.c
    -% gccgo -c interface.go
    -% gccgo program.o interface.o interface_wrap.o
    +% swig -go -cgo interface.i
    +% mkdir -p gopath/src/interface
    +% cp interface_wrap.c interface_wrap.h interface.go gopath/src/interface
    +% GOPATH=`pwd`/gopath
    +% export GOPATH
    +% cd gopath/src/interface
    +% go build
    +% gccgo -c $(SRCDIR)/runme.go
    +% gccgo -o runme runme.o interface.a
     
    All of the examples were last tested with the following configuration -(10 May 2010): +(5 August 2015):
      -
    • Ubuntu Hardy -
    • gcc-4.2.4 +
    • Ubuntu Trusty +
    • gcc-4.8.4
    -Your mileage may vary. If you experience a problem, please let us know by +Your mileage may vary. If you experience a problem, please let us know by contacting us on the mailing lists. diff --git a/Examples/go/multimap/Makefile b/Examples/go/multimap/Makefile index 4d739162b..ba172611d 100644 --- a/Examples/go/multimap/Makefile +++ b/Examples/go/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = multimap.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/pointer/Makefile b/Examples/go/pointer/Makefile index 9f1f3fda0..20587fd95 100644 --- a/Examples/go/pointer/Makefile +++ b/Examples/go/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = pointer.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/reference/Makefile b/Examples/go/reference/Makefile index e136f6fae..d203fff6d 100644 --- a/Examples/go/reference/Makefile +++ b/Examples/go/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = reference.cxx TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: diff --git a/Examples/go/simple/Makefile b/Examples/go/simple/Makefile index 5bc16549d..89b936f3d 100644 --- a/Examples/go/simple/Makefile +++ b/Examples/go/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = simple.c TARGET = example INTERFACE = example.i @@ -8,7 +9,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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: diff --git a/Examples/go/template/Makefile b/Examples/go/template/Makefile index a1d674836..f79b083cb 100644 --- a/Examples/go/template/Makefile +++ b/Examples/go/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: diff --git a/Examples/go/variables/Makefile b/Examples/go/variables/Makefile index d0da605e0..cef1186af 100644 --- a/Examples/go/variables/Makefile +++ b/Examples/go/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = variables.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/guile/class/Makefile b/Examples/guile/class/Makefile index 48426a8fb..84a7b4322 100644 --- a/Examples/guile/class/Makefile +++ b/Examples/guile/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static_cpp clean: diff --git a/Examples/guile/constants/Makefile b/Examples/guile/constants/Makefile index d3f58ebdc..abe63d4b1 100644 --- a/Examples/guile/constants/Makefile +++ b/Examples/guile/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = my-guile INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented clean: diff --git a/Examples/guile/matrix/Makefile b/Examples/guile/matrix/Makefile index 9e541c36f..cfe0c8536 100644 --- a/Examples/guile/matrix/Makefile +++ b/Examples/guile/matrix/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = matrix.c vector.c TARGET = my-guile INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' GUILE_RUNOPTIONS='-e do-test' guile_augmented_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS='-lm' guile_augmented clean: diff --git a/Examples/guile/multimap/Makefile b/Examples/guile/multimap/Makefile index b8f5e9b5a..f87670219 100644 --- a/Examples/guile/multimap/Makefile +++ b/Examples/guile/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile static: - $(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)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static clean: diff --git a/Examples/guile/multivalue/Makefile b/Examples/guile/multivalue/Makefile index b8f5e9b5a..f87670219 100644 --- a/Examples/guile/multivalue/Makefile +++ b/Examples/guile/multivalue/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile static: - $(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)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static clean: diff --git a/Examples/guile/port/Makefile b/Examples/guile/port/Makefile index 0274dbf9b..09ee821f5 100644 --- a/Examples/guile/port/Makefile +++ b/Examples/guile/port/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my-guile INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented clean: diff --git a/Examples/guile/simple/Makefile b/Examples/guile/simple/Makefile index 517e41c64..d8fb2da81 100644 --- a/Examples/guile/simple/Makefile +++ b/Examples/guile/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my-guile INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented clean: diff --git a/Examples/guile/std_vector/Makefile b/Examples/guile/std_vector/Makefile index d7f5de217..1146242c2 100644 --- a/Examples/guile/std_vector/Makefile +++ b/Examples/guile/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static_cpp clean: diff --git a/Examples/java/callback/Makefile b/Examples/java/callback/Makefile index 13cfd1708..c76e09262 100644 --- a/Examples/java/callback/Makefile +++ b/Examples/java/callback/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/class/Makefile b/Examples/java/class/Makefile index 13cfd1708..c76e09262 100644 --- a/Examples/java/class/Makefile +++ b/Examples/java/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/constants/Makefile b/Examples/java/constants/Makefile index 637ce0ead..ddc2157a6 100644 --- a/Examples/java/constants/Makefile +++ b/Examples/java/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/enum/Makefile b/Examples/java/enum/Makefile index 13cfd1708..c76e09262 100644 --- a/Examples/java/enum/Makefile +++ b/Examples/java/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/extend/Makefile b/Examples/java/extend/Makefile index 13cfd1708..c76e09262 100644 --- a/Examples/java/extend/Makefile +++ b/Examples/java/extend/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/funcptr/Makefile b/Examples/java/funcptr/Makefile index c0b1927ca..4babc683d 100644 --- a/Examples/java/funcptr/Makefile +++ b/Examples/java/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 = example.c TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/multimap/Makefile b/Examples/java/multimap/Makefile index c0b1927ca..4babc683d 100644 --- a/Examples/java/multimap/Makefile +++ b/Examples/java/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/native/Makefile b/Examples/java/native/Makefile index fa67e48a4..b43a7d152 100644 --- a/Examples/java/native/Makefile +++ b/Examples/java/native/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/nested/Makefile b/Examples/java/nested/Makefile index 13cfd1708..c76e09262 100644 --- a/Examples/java/nested/Makefile +++ b/Examples/java/nested/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/pointer/Makefile b/Examples/java/pointer/Makefile index c0b1927ca..4babc683d 100644 --- a/Examples/java/pointer/Makefile +++ b/Examples/java/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/reference/Makefile b/Examples/java/reference/Makefile index 13cfd1708..c76e09262 100644 --- a/Examples/java/reference/Makefile +++ b/Examples/java/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/simple/Makefile b/Examples/java/simple/Makefile index c0b1927ca..4babc683d 100644 --- a/Examples/java/simple/Makefile +++ b/Examples/java/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/template/Makefile b/Examples/java/template/Makefile index 637ce0ead..ddc2157a6 100644 --- a/Examples/java/template/Makefile +++ b/Examples/java/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/typemap/Makefile b/Examples/java/typemap/Makefile index fa67e48a4..b43a7d152 100644 --- a/Examples/java/typemap/Makefile +++ b/Examples/java/typemap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/java/variables/Makefile b/Examples/java/variables/Makefile index c0b1927ca..4babc683d 100644 --- a/Examples/java/variables/Makefile +++ b/Examples/java/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_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)' java $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile diff --git a/Examples/javascript/example.mk b/Examples/javascript/example.mk index cb8a33efd..3ef012aa8 100644 --- a/Examples/javascript/example.mk +++ b/Examples/javascript/example.mk @@ -13,20 +13,23 @@ else JSV8_VERSION=0x031110 endif -EXAMPLES_TOP=../.. -SWIG_TOP=../../.. -SWIG = $(SWIG_TOP)/preinst-swig -TARGET = example -INTERFACE = example.i -SWIGOPT=-$(JSENGINE) -DV8_VERSION=$(JSV8_VERSION) +EXAMPLES_TOP = ../.. +SWIG_TOP = ../../.. +SWIGEXE = $(SWIG_TOP)/swig +SWIG_LIB_DIR = $(SWIG_TOP)/$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +TARGET = example +INTERFACE = example.i +SWIGOPT = -$(JSENGINE) -DV8_VERSION=$(JSV8_VERSION) check: build $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' JSENGINE='$(JSENGINE)' TARGET='$(TARGET)' javascript_run build: - $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp - $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_cpp clean: diff --git a/Examples/lua/arrays/Makefile b/Examples/lua/arrays/Makefile index 4191f7ec3..70de9c453 100644 --- a/Examples/lua/arrays/Makefile +++ b/Examples/lua/arrays/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(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)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/lua/arrays/example.i b/Examples/lua/arrays/example.i index 3d5b60dc6..eafd8ff55 100644 --- a/Examples/lua/arrays/example.i +++ b/Examples/lua/arrays/example.i @@ -14,18 +14,19 @@ See the lua code for how they are called // this adds some lua code directly into the module // warning: you need the example. prefix if you want it added into the module -// addmittedly this code is a bit tedious, but its a one off effort +// admittedly this code is a bit tedious, but its a one off effort %luacode { function example.sort_int2(t) - local len=table.maxn(t) -- the len +-- local len=table.maxn(t) -- the len - maxn deprecated in 5.3 + local len=0; for _ in pairs(t) do len=len+1 end local arr=example.new_int(len) for i=1,len do - example.int_setitem(arr,i-1,t[i]) -- note: C index is one less then lua indea + example.int_setitem(arr,i-1,t[i]) -- note: C index is one less then lua index end example.sort_int(arr,len) -- call the fn -- copy back for i=1,len do - t[i]=example.int_getitem(arr,i-1) -- note: C index is one less then lua indea + t[i]=example.int_getitem(arr,i-1) -- note: C index is one less then lua index end example.delete_int(arr) -- must delete it end diff --git a/Examples/lua/class/Makefile b/Examples/lua/class/Makefile index 96308f0df..dd78fdbe9 100644 --- a/Examples/lua/class/Makefile +++ b/Examples/lua/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: diff --git a/Examples/lua/constants/Makefile b/Examples/lua/constants/Makefile index ae33cb182..979dc7d45 100644 --- a/Examples/lua/constants/Makefile +++ b/Examples/lua/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/lua/dual/Makefile b/Examples/lua/dual/Makefile index c86152a97..53b28b645 100644 --- a/Examples/lua/dual/Makefile +++ b/Examples/lua/dual/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = dual GENCXXSRCS = example2_wrap.cxx INTERFACE = dual.i @@ -11,9 +12,14 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: - $(SWIG) -lua -external-runtime - $(SWIG) -c++ -lua $(SWIGOPT) -o $(GENCXXSRCS) $(SRCDIR)example2.i - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) GENCXXSRCS='$(GENCXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + lua_externalhdr + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-c++' INTERFACE='example2.i' lua_swig_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) GENCXXSRCS='$(GENCXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static_cpp clean: diff --git a/Examples/lua/embed/Makefile b/Examples/lua/embed/Makefile index 5e3a91893..7f4054492 100644 --- a/Examples/lua/embed/Makefile +++ b/Examples/lua/embed/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = embed SRCS = example.c INTERFACE = example.i @@ -12,7 +13,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: diff --git a/Examples/lua/embed2/Makefile b/Examples/lua/embed2/Makefile index d30ba0942..28d9682b4 100644 --- a/Examples/lua/embed2/Makefile +++ b/Examples/lua/embed2/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = embed2 SRCS = example.c INTERFACE = example.i @@ -12,7 +13,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: diff --git a/Examples/lua/embed3/Makefile b/Examples/lua/embed3/Makefile index fc0026122..d8e7c7385 100644 --- a/Examples/lua/embed3/Makefile +++ b/Examples/lua/embed3/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = embed3 SRCS = example.cpp INTERFACE = example.i @@ -12,8 +13,11 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: - $(SWIG) -c++ -lua $(SWIGOPT) -external-runtime swigluarun.h - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + lua_externalhdr + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static_cpp clean: diff --git a/Examples/lua/exception/Makefile b/Examples/lua/exception/Makefile index ac9c28b69..a476f0b91 100644 --- a/Examples/lua/exception/Makefile +++ b/Examples/lua/exception/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: diff --git a/Examples/lua/funcptr3/Makefile b/Examples/lua/funcptr3/Makefile index aeeaad469..fb363cbe9 100644 --- a/Examples/lua/funcptr3/Makefile +++ b/Examples/lua/funcptr3/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(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)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/lua/functest/Makefile b/Examples/lua/functest/Makefile index aeeaad469..fb363cbe9 100644 --- a/Examples/lua/functest/Makefile +++ b/Examples/lua/functest/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(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)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/lua/functor/Makefile b/Examples/lua/functor/Makefile index e647fb2a8..1bc860a70 100644 --- a/Examples/lua/functor/Makefile +++ b/Examples/lua/functor/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: diff --git a/Examples/lua/import/Makefile b/Examples/lua/import/Makefile index 8d64a21c6..ff73702c4 100644 --- a/Examples/lua/import/Makefile +++ b/Examples/lua/import/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' lua_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' lua_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' lua_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' lua_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' lua_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' lua_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' lua_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' lua_cpp clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/import/README b/Examples/lua/import/README index 1a52e3c1e..af83d29b9 100644 --- a/Examples/lua/import/README +++ b/Examples/lua/import/README @@ -1,36 +1,36 @@ -This example tests the %import directive and working with multiple modules. - -Use 'lua runme.lua' to run a test. - -Overview: ---------- - -The example defines 4 different extension modules--each wrapping -a separate C++ class. - - base.i - Base class - foo.i - Foo class derived from Base - bar.i - Bar class derived from Base - spam.i - Spam class derived from Bar - -Each module uses %import to refer to another module. For -example, the 'foo.i' module uses '%import base.i' to get -definitions for its base class. - -If everything is okay, all of the modules will load properly and -type checking will work correctly. Caveat: Some compilers, for example -gcc-3.2.x, generate broken vtables with the inline methods in this test. -This is not a SWIG problem and can usually be solved with non-inlined -destructors compiled into separate shared objects/DLLs. - -Unix: ------ -- Run make -- Run the test as described above - -Windows: +This example tests the %import directive and working with multiple modules. + +Use 'lua runme.lua' to run a test. + +Overview: +--------- + +The example defines 4 different extension modules--each wrapping +a separate C++ class. + + base.i - Base class + foo.i - Foo class derived from Base + bar.i - Bar class derived from Base + spam.i - Spam class derived from Bar + +Each module uses %import to refer to another module. For +example, the 'foo.i' module uses '%import base.i' to get +definitions for its base class. + +If everything is okay, all of the modules will load properly and +type checking will work correctly. Caveat: Some compilers, for example +gcc-3.2.x, generate broken vtables with the inline methods in this test. +This is not a SWIG problem and can usually be solved with non-inlined +destructors compiled into separate shared objects/DLLs. + +Unix: +----- +- Run make +- Run the test as described above + +Windows: -------- Sorry, no files here. -If you know how, you could copy the python or ruby example dsw & dsp and try editing that +If you know how, you could copy the python or ruby example dsw & dsp and try editing that + - diff --git a/Examples/lua/nspace/Makefile b/Examples/lua/nspace/Makefile index 17757c2ec..fdedebca1 100644 --- a/Examples/lua/nspace/Makefile +++ b/Examples/lua/nspace/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: diff --git a/Examples/lua/owner/Makefile b/Examples/lua/owner/Makefile index 96308f0df..dd78fdbe9 100644 --- a/Examples/lua/owner/Makefile +++ b/Examples/lua/owner/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: diff --git a/Examples/lua/pointer/Makefile b/Examples/lua/pointer/Makefile index aeeaad469..fb363cbe9 100644 --- a/Examples/lua/pointer/Makefile +++ b/Examples/lua/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(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)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/lua/simple/Makefile b/Examples/lua/simple/Makefile index 4191f7ec3..70de9c453 100644 --- a/Examples/lua/simple/Makefile +++ b/Examples/lua/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(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)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/lua/variables/Makefile b/Examples/lua/variables/Makefile index 4191f7ec3..70de9c453 100644 --- a/Examples/lua/variables/Makefile +++ b/Examples/lua/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(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)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: diff --git a/Examples/modula3/class/Makefile b/Examples/modula3/class/Makefile index 2e2f37526..b25f636c3 100644 --- a/Examples/modula3/class/Makefile +++ b/Examples/modula3/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example PLATFORM = LINUXLIBC6 @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_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)' modula3 m3ppinplace $(MODULA3SRCS) # compilation of example_wrap.cxx is started by cm3 diff --git a/Examples/modula3/enum/Makefile b/Examples/modula3/enum/Makefile index 3915e5405..2c5c9b0a5 100644 --- a/Examples/modula3/enum/Makefile +++ b/Examples/modula3/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -11,11 +12,12 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(SWIG) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h + $(SWIGEXE) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h $(CXX) -Wall $(CONSTNUMERIC).c -o $(CONSTNUMERIC) $(CONSTNUMERIC) >$(CONSTNUMERIC).i - $(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)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ diff --git a/Examples/modula3/exception/Makefile b/Examples/modula3/exception/Makefile index 1dbf1a156..8d12ef19e 100644 --- a/Examples/modula3/exception/Makefile +++ b/Examples/modula3/exception/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -11,7 +12,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3_cpp # $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile m3ppinplace $(MODULA3SRCS) diff --git a/Examples/modula3/reference/Makefile b/Examples/modula3/reference/Makefile index 3b68fe822..eaceceb1f 100644 --- a/Examples/modula3/reference/Makefile +++ b/Examples/modula3/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_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)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ diff --git a/Examples/modula3/simple/Makefile b/Examples/modula3/simple/Makefile index 2796b25f8..3ba35d18b 100644 --- a/Examples/modula3/simple/Makefile +++ b/Examples/modula3/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_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)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ diff --git a/Examples/modula3/typemap/Makefile b/Examples/modula3/typemap/Makefile index 2796b25f8..3ba35d18b 100644 --- a/Examples/modula3/typemap/Makefile +++ b/Examples/modula3/typemap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,7 +11,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_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)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ diff --git a/Examples/mzscheme/multimap/Makefile b/Examples/mzscheme/multimap/Makefile index ecf83fbeb..713ee43a7 100644 --- a/Examples/mzscheme/multimap/Makefile +++ b/Examples/mzscheme/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_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)' mzscheme clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean diff --git a/Examples/mzscheme/simple/Makefile b/Examples/mzscheme/simple/Makefile index ecf83fbeb..713ee43a7 100644 --- a/Examples/mzscheme/simple/Makefile +++ b/Examples/mzscheme/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_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)' mzscheme clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean diff --git a/Examples/mzscheme/std_vector/Makefile b/Examples/mzscheme/std_vector/Makefile index 75918a61e..96f5e80cf 100644 --- a/Examples/mzscheme/std_vector/Makefile +++ b/Examples/mzscheme/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -12,7 +13,7 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run build: - $(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACE) + $(SWIGEXE) -mzscheme -c++ $(SWIGOPT) $(INTERFACE) $(MZC) --compiler $(GPP) ++ccf "-I." --cc example_wrap.cxx $(MZC) --linker $(GPP) --ld $(TARGET).so example_wrap.o diff --git a/Examples/ocaml/argout_ref/Makefile b/Examples/ocaml/argout_ref/Makefile index 09893af65..8b7fc959e 100644 --- a/Examples/ocaml/argout_ref/Makefile +++ b/Examples/ocaml/argout_ref/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -13,13 +14,15 @@ check: build build: static static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp dynamic: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp diff --git a/Examples/ocaml/contract/Makefile b/Examples/ocaml/contract/Makefile index df5d6a6f5..c77e6dcc4 100644 --- a/Examples/ocaml/contract/Makefile +++ b/Examples/ocaml/contract/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -13,19 +14,22 @@ check: build build: static dynamic: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static toplevel: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_toplevel diff --git a/Examples/ocaml/scoped_enum/Makefile b/Examples/ocaml/scoped_enum/Makefile index 794733971..9655c98e6 100644 --- a/Examples/ocaml/scoped_enum/Makefile +++ b/Examples/ocaml/scoped_enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -13,19 +14,22 @@ check: build build: static dynamic: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp toplevel: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp_toplevel diff --git a/Examples/ocaml/shapes/Makefile b/Examples/ocaml/shapes/Makefile index 69102f3b1..b291d07e8 100644 --- a/Examples/ocaml/shapes/Makefile +++ b/Examples/ocaml/shapes/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = SRCS = example.c TARGET = example @@ -14,19 +15,22 @@ check: build build: static static_top static: - $(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)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp static_top: - $(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)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp_toplevel dynamic: - $(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)' MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp diff --git a/Examples/ocaml/simple/Makefile b/Examples/ocaml/simple/Makefile index 49bf81c1e..88fef7435 100644 --- a/Examples/ocaml/simple/Makefile +++ b/Examples/ocaml/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -13,19 +14,22 @@ check: build build: static dynamic: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static toplevel: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_toplevel diff --git a/Examples/ocaml/std_string/Makefile b/Examples/ocaml/std_string/Makefile index 8f8b2f684..099b1fcee 100644 --- a/Examples/ocaml/std_string/Makefile +++ b/Examples/ocaml/std_string/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -11,12 +12,14 @@ check: build build: static static: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp dynamic: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_dynamic_cpp diff --git a/Examples/ocaml/std_vector/Makefile b/Examples/ocaml/std_vector/Makefile index 8f8b2f684..099b1fcee 100644 --- a/Examples/ocaml/std_vector/Makefile +++ b/Examples/ocaml/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -11,12 +12,14 @@ check: build build: static static: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp dynamic: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_dynamic_cpp diff --git a/Examples/ocaml/stl/Makefile b/Examples/ocaml/stl/Makefile index e4cce4883..912dd9f8d 100644 --- a/Examples/ocaml/stl/Makefile +++ b/Examples/ocaml/stl/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -11,22 +12,26 @@ check: build build: static static: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp director: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp_director dynamic: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp toplevel: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp_toplevel diff --git a/Examples/ocaml/string_from_ptr/Makefile b/Examples/ocaml/string_from_ptr/Makefile index 294bdec83..f9b027802 100644 --- a/Examples/ocaml/string_from_ptr/Makefile +++ b/Examples/ocaml/string_from_ptr/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = -c++ SRCS = TARGET = example @@ -14,19 +15,22 @@ check: build build: static static_top static: - $(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)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp static_top: - $(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)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp_toplevel dynamic: - $(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)' MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp diff --git a/Examples/ocaml/strings_test/Makefile b/Examples/ocaml/strings_test/Makefile index b6b866669..24e2e6cca 100644 --- a/Examples/ocaml/strings_test/Makefile +++ b/Examples/ocaml/strings_test/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -11,17 +12,20 @@ check: build build: static top static: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp dynamic: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp top: - $(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)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp_toplevel diff --git a/Examples/octave/example.mk b/Examples/octave/example.mk index e0b1e4efb..1ab96f038 100644 --- a/Examples/octave/example.mk +++ b/Examples/octave/example.mk @@ -2,7 +2,8 @@ # These paths are relative to such an example directory TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = swigexample INTERFACE = example.i @@ -11,18 +12,22 @@ check: build build: ifneq (,$(SRCS)) - $(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)' octave else - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp endif ifneq (,$(TARGET2)$(SWIGOPT2)) ifneq (,$(SRCS)) - $(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='$(SWIGOPT2)' TARGET='$(TARGET2)' INTERFACE='$(INTERFACE)' octave else - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT2)' TARGET='$(TARGET2)' INTERFACE='$(INTERFACE)' octave_cpp endif endif diff --git a/Examples/octave/module_load/runme.m b/Examples/octave/module_load/runme.m index bc311b5e6..30b7badb2 100644 --- a/Examples/octave/module_load/runme.m +++ b/Examples/octave/module_load/runme.m @@ -61,9 +61,8 @@ testme testme clear all -# octave 3.0.5 randomly crashes on the remaining tests, so skip them -api_version = sscanf(octave_config_info("api_version"), "api-v%i"); -if api_version < 37 +# octave 3.0.5 randomly crashes on the remaining tests +if !swig_octave_prereq(3,2,0) exit endif diff --git a/Examples/octave/operator/example.i b/Examples/octave/operator/example.i index 7fad8e609..937e8d39d 100644 --- a/Examples/octave/operator/example.i +++ b/Examples/octave/operator/example.i @@ -26,4 +26,25 @@ ComplexVal __paren__(int j) { return ComplexVal($self->re()*j,$self->im()*j); } + + double __float__() { + return (double) $self->re(); + } + + double __real__() { + return $self->re(); + } + double __imag__() { + return $self->im(); + } + double __abs__() { + return sqrt($self->re()*$self->re() + $self->im()*$self->im()); + } + ComplexVal __conj__() { + return ComplexVal($self->re(), -$self->im()); + } + ComplexVal __exp__() { + return exp($self->re()) * ComplexVal(cos($self->im()), sin($self->im())); + } + }; diff --git a/Examples/octave/operator/runme.m b/Examples/octave/operator/runme.m index 9ab614ffb..83197b410 100644 --- a/Examples/octave/operator/runme.m +++ b/Examples/octave/operator/runme.m @@ -24,3 +24,16 @@ printf("a(3)= %s\n",disp(a(3))); # friend operator printf("2*a = %s\n",disp(2*a)); + +# conversions +printf("single(a) = %g\n", single(a)); +printf("double(a) = %g\n", double(a)); + +# unary functions +if swig_octave_prereq(3,8,0) + printf("real(a) = %g\n", real(a)); + printf("imag(a) = %g\n", imag(a)); + printf("abs(a) = %g\n", abs(a)); + printf("conj(a) = %s\n", disp(conj(a))); + printf("exp(a) = %s\n", disp(exp(a))); +endif diff --git a/Examples/perl5/callback/Makefile b/Examples/perl5/callback/Makefile index 0d1cc574f..08271768c 100644 --- a/Examples/perl5/callback/Makefile +++ b/Examples/perl5/callback/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: diff --git a/Examples/perl5/class/Makefile b/Examples/perl5/class/Makefile index 0d1cc574f..08271768c 100644 --- a/Examples/perl5/class/Makefile +++ b/Examples/perl5/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: diff --git a/Examples/perl5/constants/Makefile b/Examples/perl5/constants/Makefile index b7b411534..b0dc67806 100644 --- a/Examples/perl5/constants/Makefile +++ b/Examples/perl5/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/constants2/Makefile b/Examples/perl5/constants2/Makefile index 85dd13741..db676cc4e 100644 --- a/Examples/perl5/constants2/Makefile +++ b/Examples/perl5/constants2/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/extend/Makefile b/Examples/perl5/extend/Makefile index 0d1cc574f..08271768c 100644 --- a/Examples/perl5/extend/Makefile +++ b/Examples/perl5/extend/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: diff --git a/Examples/perl5/funcptr/Makefile b/Examples/perl5/funcptr/Makefile index 3e1de1fc1..dfc01843e 100644 --- a/Examples/perl5/funcptr/Makefile +++ b/Examples/perl5/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 = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/import/Makefile b/Examples/perl5/import/Makefile index b31ab7952..e9225af25 100644 --- a/Examples/perl5/import/Makefile +++ b/Examples/perl5/import/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='baseclass' INTERFACE='base.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' perl5_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='baseclass' INTERFACE='base.i' perl5_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' perl5_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' perl5_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' perl5_cpp clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/java/Makefile b/Examples/perl5/java/Makefile index 5eaea3212..7c133235f 100644 --- a/Examples/perl5/java/Makefile +++ b/Examples/perl5/java/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ CXXSHARED="gcj -fpic -shared Example.class" PERL5_CCFLAGS='' PERL5_EXP='' LIBS="-lstdc++" perl5_cpp diff --git a/Examples/perl5/multimap/Makefile b/Examples/perl5/multimap/Makefile index 3e1de1fc1..dfc01843e 100644 --- a/Examples/perl5/multimap/Makefile +++ b/Examples/perl5/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/multiple_inheritance/Makefile b/Examples/perl5/multiple_inheritance/Makefile index 1fe5a51bb..b73356e3e 100644 --- a/Examples/perl5/multiple_inheritance/Makefile +++ b/Examples/perl5/multiple_inheritance/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: diff --git a/Examples/perl5/pointer/Makefile b/Examples/perl5/pointer/Makefile index 3e1de1fc1..dfc01843e 100644 --- a/Examples/perl5/pointer/Makefile +++ b/Examples/perl5/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/reference/Makefile b/Examples/perl5/reference/Makefile index a22f5a68d..c4212099e 100644 --- a/Examples/perl5/reference/Makefile +++ b/Examples/perl5/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' SWIGOPT='$(SWIGOPT)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' SWIGOPT='$(SWIGOPT)' perl5_cpp_static clean: diff --git a/Examples/perl5/simple/Makefile b/Examples/perl5/simple/Makefile index 3e1de1fc1..dfc01843e 100644 --- a/Examples/perl5/simple/Makefile +++ b/Examples/perl5/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/value/Makefile b/Examples/perl5/value/Makefile index 3e1de1fc1..dfc01843e 100644 --- a/Examples/perl5/value/Makefile +++ b/Examples/perl5/value/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/variables/Makefile b/Examples/perl5/variables/Makefile index 3e1de1fc1..dfc01843e 100644 --- a/Examples/perl5/variables/Makefile +++ b/Examples/perl5/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_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)' perl5 static: - $(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='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: diff --git a/Examples/perl5/xmlstring/Makefile b/Examples/perl5/xmlstring/Makefile index 4f02d3ee4..3b4ba0ea4 100644 --- a/Examples/perl5/xmlstring/Makefile +++ b/Examples/perl5/xmlstring/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS=$(LIBS) CXX="g++ -g3" perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: diff --git a/Examples/php/callback/Makefile b/Examples/php/callback/Makefile index 3ad3999a5..7f91fd56c 100644 --- a/Examples/php/callback/Makefile +++ b/Examples/php/callback/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,12 +11,9 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/class/Makefile b/Examples/php/class/Makefile index 8b2b340e9..063a0645f 100644 --- a/Examples/php/class/Makefile +++ b/Examples/php/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/constants/Makefile b/Examples/php/constants/Makefile index e5b49571e..a05be202b 100644 --- a/Examples/php/constants/Makefile +++ b/Examples/php/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/cpointer/Makefile b/Examples/php/cpointer/Makefile index f2c15c5c1..47e5ed9f9 100644 --- a/Examples/php/cpointer/Makefile +++ b/Examples/php/cpointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/disown/Makefile b/Examples/php/disown/Makefile index 8b2b340e9..063a0645f 100644 --- a/Examples/php/disown/Makefile +++ b/Examples/php/disown/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/enum/Makefile b/Examples/php/enum/Makefile index 2028d03c7..4483f781e 100644 --- a/Examples/php/enum/Makefile +++ b/Examples/php/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/extend/Makefile b/Examples/php/extend/Makefile index 3ad3999a5..7f91fd56c 100644 --- a/Examples/php/extend/Makefile +++ b/Examples/php/extend/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,12 +11,9 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/funcptr/Makefile b/Examples/php/funcptr/Makefile index f2c15c5c1..47e5ed9f9 100644 --- a/Examples/php/funcptr/Makefile +++ b/Examples/php/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 = example.c TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/overloading/Makefile b/Examples/php/overloading/Makefile index 8b2b340e9..063a0645f 100644 --- a/Examples/php/overloading/Makefile +++ b/Examples/php/overloading/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pointer/Makefile b/Examples/php/pointer/Makefile index f2c15c5c1..47e5ed9f9 100644 --- a/Examples/php/pointer/Makefile +++ b/Examples/php/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pragmas/Makefile b/Examples/php/pragmas/Makefile index e5b49571e..a05be202b 100644 --- a/Examples/php/pragmas/Makefile +++ b/Examples/php/pragmas/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/proxy/Makefile b/Examples/php/proxy/Makefile index 8b2b340e9..063a0645f 100644 --- a/Examples/php/proxy/Makefile +++ b/Examples/php/proxy/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/reference/Makefile b/Examples/php/reference/Makefile index 8b2b340e9..063a0645f 100644 --- a/Examples/php/reference/Makefile +++ b/Examples/php/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/simple/Makefile b/Examples/php/simple/Makefile index f2c15c5c1..47e5ed9f9 100644 --- a/Examples/php/simple/Makefile +++ b/Examples/php/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/sync/Makefile b/Examples/php/sync/Makefile index 8b2b340e9..063a0645f 100644 --- a/Examples/php/sync/Makefile +++ b/Examples/php/sync/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_cpp_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/value/Makefile b/Examples/php/value/Makefile index 3db7afec5..28fc3a127 100644 --- a/Examples/php/value/Makefile +++ b/Examples/php/value/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/variables/Makefile b/Examples/php/variables/Makefile index f2c15c5c1..47e5ed9f9 100644 --- a/Examples/php/variables/Makefile +++ b/Examples/php/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -10,14 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' \ php -static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ - php_static - clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php5/callback/Makefile b/Examples/php5/callback/Makefile new file mode 100644 index 000000000..3a34106c3 --- /dev/null +++ b/Examples/php5/callback/Makefile @@ -0,0 +1,19 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = -lm +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/callback/example.cxx b/Examples/php5/callback/example.cxx new file mode 100644 index 000000000..450d75608 --- /dev/null +++ b/Examples/php5/callback/example.cxx @@ -0,0 +1,4 @@ +/* File : example.cxx */ + +#include "example.h" + diff --git a/Examples/php5/callback/example.h b/Examples/php5/callback/example.h new file mode 100644 index 000000000..2a0194999 --- /dev/null +++ b/Examples/php5/callback/example.h @@ -0,0 +1,22 @@ +/* File : example.h */ + +#include + +class Callback { +public: + virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; } + virtual void run() { std::cout << "Callback::run()" << std::endl; } +}; + + +class Caller { +private: + Callback *_callback; +public: + Caller(): _callback(0) {} + ~Caller() { delCallback(); } + void delCallback() { delete _callback; _callback = 0; } + void setCallback(Callback *cb) { delCallback(); _callback = cb; } + void call() { if (_callback) _callback->run(); } +}; + diff --git a/Examples/php5/callback/example.i b/Examples/php5/callback/example.i new file mode 100644 index 000000000..cf61ef9d2 --- /dev/null +++ b/Examples/php5/callback/example.i @@ -0,0 +1,11 @@ +/* File : example.i */ +%module(directors="1") example +%{ +#include "example.h" +%} + +/* turn on director wrapping Callback */ +%feature("director") Callback; + +%include "example.h" + diff --git a/Examples/php5/callback/index.html b/Examples/php5/callback/index.html new file mode 100644 index 000000000..2a6cbdff9 --- /dev/null +++ b/Examples/php5/callback/index.html @@ -0,0 +1,19 @@ + + +SWIG:Examples:php5:callback + + + + + +SWIG/Examples/php5/callback/ +
    + +

    Implementing C++ callbacks in PHP5

    + +

    +This example illustrates how to use directors to implement C++ callbacks in PHP5. + +


    + + diff --git a/Examples/php5/callback/runme.php b/Examples/php5/callback/runme.php new file mode 100644 index 000000000..2be71994f --- /dev/null +++ b/Examples/php5/callback/runme.php @@ -0,0 +1,47 @@ +thisown = 0; +$caller->setCallback($callback); +$caller->call(); +$caller->delCallback(); + +print "\n"; +print "Adding and calling a PHP callback\n"; +print "------------------------------------\n"; + +# Add a PHP callback. + +$callback = new PhpCallback(); +$callback->thisown = 0; +$caller->setCallback($callback); +$caller->call(); +$caller->delCallback(); + +# All done. + +print "php exit\n"; + +?> diff --git a/Examples/php5/check.list b/Examples/php5/check.list new file mode 100644 index 000000000..fef3feba6 --- /dev/null +++ b/Examples/php5/check.list @@ -0,0 +1,19 @@ +# see top-level Makefile.in +# (see also top-level configure.ac kludge) +callback +class +constants +cpointer +disown +enum +extend +funcptr +overloading +pointer +pragmas +proxy +reference +simple +sync +value +variables diff --git a/Examples/php5/class/Makefile b/Examples/php5/class/Makefile new file mode 100644 index 000000000..8346a1dae --- /dev/null +++ b/Examples/php5/class/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/class/example.cxx b/Examples/php5/class/example.cxx new file mode 100644 index 000000000..046304519 --- /dev/null +++ b/Examples/php5/class/example.cxx @@ -0,0 +1,28 @@ +/* File : example.cxx */ + +#include "example.h" +#define M_PI 3.14159265358979323846 + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +double Circle::area() { + return M_PI*radius*radius; +} + +double Circle::perimeter() { + return 2*M_PI*radius; +} + +double Square::area() { + return width*width; +} + +double Square::perimeter() { + return 4*width; +} diff --git a/Examples/php5/class/example.h b/Examples/php5/class/example.h new file mode 100644 index 000000000..0dff185b2 --- /dev/null +++ b/Examples/php5/class/example.h @@ -0,0 +1,34 @@ +/* File : example.h */ + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; + void move(double dx, double dy); + virtual double area() = 0; + virtual double perimeter() = 0; + static int nshapes; +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); +}; diff --git a/Examples/php5/class/example.i b/Examples/php5/class/example.i new file mode 100644 index 000000000..fbdf7249f --- /dev/null +++ b/Examples/php5/class/example.i @@ -0,0 +1,9 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" diff --git a/Examples/php5/class/runme.php b/Examples/php5/class/runme.php new file mode 100644 index 000000000..99c253b46 --- /dev/null +++ b/Examples/php5/class/runme.php @@ -0,0 +1,60 @@ +x = 20; +$c->y = 30; +$s->x = -10; +$s->y = 5; + +print "\nHere is their current position:\n"; +print " Circle = ({$c->x},{$c->y})\n"; +print " Square = ({$s->x},{$s->y})\n"; + +# ----- Call some methods ----- + +# Notice how the Shape_area() and Shape_perimeter() functions really +# invoke the appropriate virtual method on each object. +print "\nHere are some properties of the shapes:\n"; +foreach (array($c,$s) as $o) { + print " ". get_class($o) . "\n"; + print " area = {$o->area()}\n"; + print " perimeter = {$o->perimeter()}\n"; +} + +# ----- Delete everything ----- + +print "\nGuess I'll clean up now\n"; + +# Note: this invokes the virtual destructor +$c = NULL; +$s = NULL; + +# and don't forget the $o from the for loop above. It still refers to +# the square. +$o = NULL; + +print Shape::nshapes() . " shapes remain\n"; +print "Goodbye\n"; + +?> diff --git a/Examples/php5/constants/Makefile b/Examples/php5/constants/Makefile new file mode 100644 index 000000000..f9557fa89 --- /dev/null +++ b/Examples/php5/constants/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/constants/example.i b/Examples/php5/constants/example.i new file mode 100644 index 000000000..0098a893a --- /dev/null +++ b/Examples/php5/constants/example.i @@ -0,0 +1,26 @@ +/* File : example.i */ +%module example + +/* A few preprocessor macros */ + +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" + +/* This should work just fine */ +#define EXPR ICONST + 3*(FCONST) + +/* This shouldn't do anything */ +#define EXTERN extern + +/* Neither should this (BAR isn't defined) */ +#define FOO (ICONST + BAR) + +/* The following statements also produce constants */ +%constant int iconst = 37; +%constant double fconst = 3.14; + + diff --git a/Examples/php5/constants/runme.php b/Examples/php5/constants/runme.php new file mode 100644 index 000000000..cea06485f --- /dev/null +++ b/Examples/php5/constants/runme.php @@ -0,0 +1,28 @@ + diff --git a/Examples/php5/cpointer/Makefile b/Examples/php5/cpointer/Makefile new file mode 100644 index 000000000..92085788a --- /dev/null +++ b/Examples/php5/cpointer/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/cpointer/example.c b/Examples/php5/cpointer/example.c new file mode 100644 index 000000000..04dd08df0 --- /dev/null +++ b/Examples/php5/cpointer/example.c @@ -0,0 +1,16 @@ +/* File : example.c */ + +void add(int *x, int *y, int *result) { + *result = *x + *y; +} + +void sub(int *x, int *y, int *result) { + *result = *x - *y; +} + +int divide(int n, int d, int *r) { + int q; + q = n/d; + *r = n - q*d; + return q; +} diff --git a/Examples/php5/cpointer/example.i b/Examples/php5/cpointer/example.i new file mode 100644 index 000000000..c61d92858 --- /dev/null +++ b/Examples/php5/cpointer/example.i @@ -0,0 +1,31 @@ +/* File : example.i */ +%module example + +%{ +extern void add(int *, int *, int *); +extern void sub(int *, int *, int *); +%} + +/* This example illustrates a couple of different techniques + for manipulating C pointers */ + +/* First we'll use the pointer library */ +extern void add(int *x, int *y, int *result); + +%include cpointer.i +%pointer_functions(int, intp); + +/* Next we'll use some typemaps */ + +%include typemaps.i +extern void sub(int *INPUT, int *INPUT, int *OUTPUT); + +/* Next we'll use typemaps and the %apply directive */ + +//%apply int *OUTPUT { int *r }; +//extern int divide(int n, int d, int *r); + + + + + diff --git a/Examples/php5/cpointer/runme.php b/Examples/php5/cpointer/runme.php new file mode 100644 index 000000000..22e8a681a --- /dev/null +++ b/Examples/php5/cpointer/runme.php @@ -0,0 +1,47 @@ + diff --git a/Examples/php5/disown/Makefile b/Examples/php5/disown/Makefile new file mode 100644 index 000000000..8346a1dae --- /dev/null +++ b/Examples/php5/disown/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/disown/example.cxx b/Examples/php5/disown/example.cxx new file mode 100644 index 000000000..6393735e9 --- /dev/null +++ b/Examples/php5/disown/example.cxx @@ -0,0 +1,51 @@ +/* File : example.c */ + +#include "example.h" +#include +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +int Shape::get_nshapes() { + return nshapes; +} + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +void Circle::set_radius( double r ) { + radius = r; +} + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} + +ShapeContainer::~ShapeContainer() { + iterator i=shapes.begin(); + for( iterator i = shapes.begin(); i != shapes.end(); ++i ) { + delete *i; + } +} + +void +ShapeContainer::addShape( Shape *s ) { + shapes.push_back( s ); +} diff --git a/Examples/php5/disown/example.h b/Examples/php5/disown/example.h new file mode 100644 index 000000000..e9f96743f --- /dev/null +++ b/Examples/php5/disown/example.h @@ -0,0 +1,50 @@ +/* File : example.h */ + +#include + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; + static int get_nshapes(); +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + ~Circle() { } + void set_radius( double r ); + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + ~Square() { } + virtual double area(void); + virtual double perimeter(void); +}; + +class ShapeContainer { +private: + typedef std::vector::iterator iterator; + std::vector shapes; +public: + ShapeContainer() : shapes() {} + ~ShapeContainer(); + void addShape( Shape *s ); +}; diff --git a/Examples/php5/disown/example.i b/Examples/php5/disown/example.i new file mode 100644 index 000000000..599f162c5 --- /dev/null +++ b/Examples/php5/disown/example.i @@ -0,0 +1,12 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%apply SWIGTYPE *DISOWN {(Shape *s)}; + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/php5/disown/runme.php b/Examples/php5/disown/runme.php new file mode 100644 index 000000000..d90b03a9d --- /dev/null +++ b/Examples/php5/disown/runme.php @@ -0,0 +1,49 @@ +addShape($c); +$container->addShape($s); + +# ----- Access a static member ----- + +print "\nA total of " . Shape::nshapes() . " shapes were created\n"; + +# ----- Delete by the old references ----- +# This should not truely delete the shapes because they are now owned +# by the ShapeContainer. + +print "Delete the old references."; + +# Note: this invokes the virtual destructor +$c = NULL; +$s = NULL; + +print "\nA total of " . Shape::nshapes() . " shapes remain\n"; + +# ----- Delete by the container ----- +# This should truely delete the shapes + +print "Delete the container."; +$container = NULL; +print "\nA total of " . Shape::nshapes() . " shapes remain\n"; + +print "Goodbye\n"; + +?> diff --git a/Examples/php5/enum/Makefile b/Examples/php5/enum/Makefile new file mode 100644 index 000000000..dc59a6c9b --- /dev/null +++ b/Examples/php5/enum/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = -noproxy + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/enum/example.cxx b/Examples/php5/enum/example.cxx new file mode 100644 index 000000000..df7bb6328 --- /dev/null +++ b/Examples/php5/enum/example.cxx @@ -0,0 +1,37 @@ +/* File : example.cxx */ + +#include "example.h" +#include + +void Foo::enum_test(speed s) { + if (s == IMPULSE) { + printf("IMPULSE speed\n"); + } else if (s == WARP) { + printf("WARP speed\n"); + } else if (s == LUDICROUS) { + printf("LUDICROUS speed\n"); + } else { + printf("Unknown speed\n"); + } +} + +void enum_test(color c, Foo::speed s) { + if (c == RED) { + printf("color = RED, "); + } else if (c == BLUE) { + printf("color = BLUE, "); + } else if (c == GREEN) { + printf("color = GREEN, "); + } else { + printf("color = Unknown color!, "); + } + if (s == Foo::IMPULSE) { + printf("speed = IMPULSE speed\n"); + } else if (s == Foo::WARP) { + printf("speed = WARP speed\n"); + } else if (s == Foo::LUDICROUS) { + printf("speed = LUDICROUS speed\n"); + } else { + printf("speed = Unknown speed!\n"); + } +} diff --git a/Examples/php5/enum/example.h b/Examples/php5/enum/example.h new file mode 100644 index 000000000..525d62afc --- /dev/null +++ b/Examples/php5/enum/example.h @@ -0,0 +1,13 @@ +/* File : example.h */ + +enum color { RED, BLUE, GREEN }; + +class Foo { + public: + Foo() { } + enum speed { IMPULSE, WARP, LUDICROUS }; + void enum_test(speed s); +}; + +void enum_test(color c, Foo::speed s); + diff --git a/Examples/php5/enum/example.i b/Examples/php5/enum/example.i new file mode 100644 index 000000000..abf254731 --- /dev/null +++ b/Examples/php5/enum/example.i @@ -0,0 +1,12 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + + +/* Let's just grab the original header file here */ + +%include "example.h" + diff --git a/Examples/php5/enum/runme.php b/Examples/php5/enum/runme.php new file mode 100644 index 000000000..55b0bc4c3 --- /dev/null +++ b/Examples/php5/enum/runme.php @@ -0,0 +1,32 @@ + diff --git a/Examples/php5/extend/Makefile b/Examples/php5/extend/Makefile new file mode 100644 index 000000000..3a34106c3 --- /dev/null +++ b/Examples/php5/extend/Makefile @@ -0,0 +1,19 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = -lm +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/extend/example.cxx b/Examples/php5/extend/example.cxx new file mode 100644 index 000000000..450d75608 --- /dev/null +++ b/Examples/php5/extend/example.cxx @@ -0,0 +1,4 @@ +/* File : example.cxx */ + +#include "example.h" + diff --git a/Examples/php5/extend/example.h b/Examples/php5/extend/example.h new file mode 100644 index 000000000..ca1aed28f --- /dev/null +++ b/Examples/php5/extend/example.h @@ -0,0 +1,56 @@ +/* File : example.h */ + +#include +#include +#include +#include +#include + +class Employee { +private: + std::string name; +public: + Employee(const char* n): name(n) {} + virtual std::string getTitle() { return getPosition() + " " + getName(); } + virtual std::string getName() { return name; } + virtual std::string getPosition() const { return "Employee"; } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } +}; + + +class Manager: public Employee { +public: + Manager(const char* n): Employee(n) {} + virtual std::string getPosition() const { return "Manager"; } +}; + + +class EmployeeList { + std::vector list; +public: + EmployeeList() { + list.push_back(new Employee("Bob")); + list.push_back(new Employee("Jane")); + list.push_back(new Manager("Ted")); + } + void addEmployee(Employee *p) { + list.push_back(p); + std::cout << "New employee added. Current employees are:" << std::endl; + std::vector::iterator i; + for (i=list.begin(); i!=list.end(); i++) { + std::cout << " " << (*i)->getTitle() << std::endl; + } + } + const Employee *get_item(int i) { + return list[i]; + } + ~EmployeeList() { + std::vector::iterator i; + std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl; + for (i=list.begin(); i!=list.end(); i++) { + delete *i; + } + std::cout << "~EmployeeList empty." << std::endl; + } +}; + diff --git a/Examples/php5/extend/example.i b/Examples/php5/extend/example.i new file mode 100644 index 000000000..c8ec32e09 --- /dev/null +++ b/Examples/php5/extend/example.i @@ -0,0 +1,15 @@ +/* File : example.i */ +%module(directors="1") example +%{ +#include "example.h" +%} + +%include "std_vector.i" +%include "std_string.i" + +/* turn on director wrapping for Manager */ +%feature("director") Employee; +%feature("director") Manager; + +%include "example.h" + diff --git a/Examples/php5/extend/index.html b/Examples/php5/extend/index.html new file mode 100644 index 000000000..32c6a4913 --- /dev/null +++ b/Examples/php5/extend/index.html @@ -0,0 +1,19 @@ + + +SWIG:Examples:php:extend + + + + + +SWIG/Examples/php/extend/ +
    + +

    Extending a simple C++ class in PHP

    + +

    +This example illustrates the extending of a C++ class with cross language polymorphism. + +


    + + diff --git a/Examples/php5/extend/runme.php b/Examples/php5/extend/runme.php new file mode 100644 index 000000000..158683142 --- /dev/null +++ b/Examples/php5/extend/runme.php @@ -0,0 +1,76 @@ +getName() . " is a " . $e->getPosition() . "\n"; +printf("Just call her \"%s\"\n", $e->getTitle()); +print "----------------------\n"; + +# 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 = new EmployeeList(); + +# EmployeeList owns its items, so we must surrender ownership of objects +# we add. This involves first clearing the ->disown member to tell the +# C++ director to start reference counting. + +$e->thisown = 0; +$list->addEmployee($e); +print "----------------------\n"; + +# Now we access the first four items in list (three are C++ objects that +# EmployeeList's constructor adds, the last is our CEO). The virtual +# methods of all these instances are treated the same. For items 0, 1, and +# 2, both all methods resolve in C++. For item 3, our CEO, getTitle calls +# getPosition which resolves in PHP. The call to getPosition is +# slightly different, however, from the e.getPosition() call above, since +# now the object reference has been "laundered" by passing through +# EmployeeList as an Employee*. Previously, PHP resolved the call +# immediately in CEO, but now PHP thinks the object is an instance of +# class Employee (actually EmployeePtr). So the call passes through the +# Employee proxy class and on to the C wrappers and C++ director, +# eventually ending up back at the 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 PHP implementation +# in CEO. All this routing takes place transparently. + +print "(position, title) for items 0-3:\n"; + +printf(" %s, \"%s\"\n", $list->get_item(0)->getPosition(), $list->get_item(0)->getTitle()); +printf(" %s, \"%s\"\n", $list->get_item(1)->getPosition(), $list->get_item(1)->getTitle()); +printf(" %s, \"%s\"\n", $list->get_item(2)->getPosition(), $list->get_item(2)->getTitle()); +printf(" %s, \"%s\"\n", $list->get_item(3)->getPosition(), $list->get_item(3)->getTitle()); +print "----------------------\n"; + +# Time to delete the EmployeeList, which will delete all the Employee* +# items it contains. The last item is our CEO, which gets destroyed as its +# reference count goes to zero. The PHP destructor runs, and is still +# able to call the getName() method since the underlying C++ object still +# exists. After this destructor runs the remaining C++ destructors run as +# usual to destroy the object. + +unset($list); +print "----------------------\n"; + +# All done. + +print "php exit\n"; + +?> diff --git a/Examples/php5/funcptr/Makefile b/Examples/php5/funcptr/Makefile new file mode 100644 index 000000000..92085788a --- /dev/null +++ b/Examples/php5/funcptr/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/funcptr/example.c b/Examples/php5/funcptr/example.c new file mode 100644 index 000000000..99583b72e --- /dev/null +++ b/Examples/php5/funcptr/example.c @@ -0,0 +1,17 @@ +/* File : example.c */ + +int do_op(int a, int b, int (*op)(int,int)) { + return (*op)(a,b); +} + +int add(int a, int b) { + return a+b; +} + +int sub(int a, int b) { + return a-b; +} + +int mul(int a, int b) { + return a*b; +} diff --git a/Examples/php5/funcptr/example.h b/Examples/php5/funcptr/example.h new file mode 100644 index 000000000..58989db79 --- /dev/null +++ b/Examples/php5/funcptr/example.h @@ -0,0 +1,7 @@ +/* file: example.h */ + +extern int do_op(int,int, int (*op)(int,int)); +extern int add(int,int); +extern int sub(int,int); +extern int mul(int,int); + diff --git a/Examples/php5/funcptr/example.i b/Examples/php5/funcptr/example.i new file mode 100644 index 000000000..39390da27 --- /dev/null +++ b/Examples/php5/funcptr/example.i @@ -0,0 +1,15 @@ +/* File : example.i */ +%module example +%{ +#include "example.h" +%} + +/* Wrap a function taking a pointer to a function */ +extern int do_op(int a, int b, int (*op)(int, int)); + +/* Now install a bunch of "ops" as constants */ +%constant int (*ADD)(int,int) = add; +%constant int (*SUB)(int,int) = sub; +%constant int (*MUL)(int,int) = mul; + + diff --git a/Examples/php5/funcptr/runme.php b/Examples/php5/funcptr/runme.php new file mode 100644 index 000000000..712d4147c --- /dev/null +++ b/Examples/php5/funcptr/runme.php @@ -0,0 +1,24 @@ + + diff --git a/Examples/php5/overloading/Makefile b/Examples/php5/overloading/Makefile new file mode 100644 index 000000000..8346a1dae --- /dev/null +++ b/Examples/php5/overloading/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/overloading/example.cxx b/Examples/php5/overloading/example.cxx new file mode 100644 index 000000000..2f684f05c --- /dev/null +++ b/Examples/php5/overloading/example.cxx @@ -0,0 +1,55 @@ +/* File : example.c */ + +#include "example.h" +#include +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +int Shape::get_nshapes() { + return nshapes; +} + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} + +const char *overloaded(int i) { + return "Overloaded with int"; +} + +const char *overloaded(double d) { + return "Overloaded with double"; +} + +const char *overloaded(const char * str) { + return "Overloaded with char *"; +} + +const char *overloaded( const Circle& ) { + return "Overloaded with Circle"; +} + +const char *overloaded( const Shape& ) { + return "Overloaded with Shape"; +} diff --git a/Examples/php5/overloading/example.h b/Examples/php5/overloading/example.h new file mode 100644 index 000000000..01d71dd70 --- /dev/null +++ b/Examples/php5/overloading/example.h @@ -0,0 +1,46 @@ +/* File : example.h */ + +#include + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; + static int get_nshapes(); +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + ~Circle() { } + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + ~Square() { } + virtual double area(void); + virtual double perimeter(void); +}; + +const char *overloaded( int i ); +const char *overloaded( double d ); +const char *overloaded( const char * str ); +const char *overloaded( const Circle& ); +const char *overloaded( const Shape& ); + diff --git a/Examples/php5/overloading/example.i b/Examples/php5/overloading/example.i new file mode 100644 index 000000000..950d2549d --- /dev/null +++ b/Examples/php5/overloading/example.i @@ -0,0 +1,8 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%include "example.h" diff --git a/Examples/php5/overloading/runme.php b/Examples/php5/overloading/runme.php new file mode 100644 index 000000000..56d515138 --- /dev/null +++ b/Examples/php5/overloading/runme.php @@ -0,0 +1,58 @@ +x = 20; +$c->y = 30; +$s->x = -10; +$s->y = 5; + +print "\nHere is their current position:\n"; +print " Circle = (" . $c->x . "," . $c->y . ")\n"; +print " Square = (" . $s->x . "," . $s->y . ")\n"; + +# ----- Call some methods ----- + +print "\nCall some overloaded methods:\n"; +foreach (array(1, 2.1, "quick brown fox", $c, $s) as $o) { + print " overloaded = " . overloaded($o) . "\n"; +} + +# Need to unset($o) or else we hang on to a reference to the Square object. +unset($o); + +# ----- Delete everything ----- + +print "\nGuess I'll clean up now\n"; + +# Note: this invokes the virtual destructor +unset($c); +$s = 42; + +print Shape::nshapes() . " shapes remain\n"; + +print "Goodbye\n"; + +?> diff --git a/Examples/php5/pointer/Makefile b/Examples/php5/pointer/Makefile new file mode 100644 index 000000000..92085788a --- /dev/null +++ b/Examples/php5/pointer/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/pointer/example.c b/Examples/php5/pointer/example.c new file mode 100644 index 000000000..3326dec3e --- /dev/null +++ b/Examples/php5/pointer/example.c @@ -0,0 +1,16 @@ +/* File : example.c */ + +void add(double *x, double *y, double *result) { + *result = *x + *y; +} + +void sub(int *x, int *y, int *result) { + *result = *x - *y; +} + +int divide(int n, int d, int *r) { + int q; + q = n/d; + *r = n - q*d; + return q; +} diff --git a/Examples/php5/pointer/example.i b/Examples/php5/pointer/example.i new file mode 100644 index 000000000..1f0059406 --- /dev/null +++ b/Examples/php5/pointer/example.i @@ -0,0 +1,30 @@ +/* File : example.i */ +%module example + +%{ +extern void add(double *, double *, double *); +extern void sub(int *, int *, int *); +extern int divide(int, int, int *); +%} + +/* This example illustrates a couple of different techniques + for manipulating C pointers */ + +%include phppointers.i +/* First we'll use the pointer library */ +extern void add(double *REF, double *REF, double *REF); + +/* Next we'll use some typemaps */ + +%include typemaps.i +extern void sub(int *INPUT, int *INPUT, int *OUTPUT); + +/* Next we'll use typemaps and the %apply directive */ + +//%apply int *OUTPUT { int *r }; +//extern int divide(int n, int d, int *r); + + + + + diff --git a/Examples/php5/pointer/runme.php b/Examples/php5/pointer/runme.php new file mode 100644 index 000000000..e79b23810 --- /dev/null +++ b/Examples/php5/pointer/runme.php @@ -0,0 +1,35 @@ + diff --git a/Examples/php5/pragmas/Makefile b/Examples/php5/pragmas/Makefile new file mode 100644 index 000000000..f9557fa89 --- /dev/null +++ b/Examples/php5/pragmas/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/pragmas/example.i b/Examples/php5/pragmas/example.i new file mode 100644 index 000000000..c7e8bf303 --- /dev/null +++ b/Examples/php5/pragmas/example.i @@ -0,0 +1,31 @@ +/* File : example.i */ +%module example + +%init{ + zend_printf("This was %%init\n"); +} + +%minit{ + zend_printf("This was %%minit\n"); +} + +%mshutdown{ + zend_printf("This was %%shutdown\n"); +} + +%rinit{ + zend_printf("This was %%rinit\n"); +} + +%rshutdown{ + zend_printf("This was %%rshutdown\n"); +} + +%pragma(php) include="include.php"; + +%pragma(php) code=" +# This code is inserted into example.php +echo \"this was php code\\n\"; +" + +%pragma(php) phpinfo="php_info_print_table_start();" diff --git a/Examples/php5/pragmas/include.php b/Examples/php5/pragmas/include.php new file mode 100644 index 000000000..e19880a06 --- /dev/null +++ b/Examples/php5/pragmas/include.php @@ -0,0 +1,7 @@ + diff --git a/Examples/php5/pragmas/runme.php b/Examples/php5/pragmas/runme.php new file mode 100644 index 000000000..538548b6f --- /dev/null +++ b/Examples/php5/pragmas/runme.php @@ -0,0 +1,5 @@ + diff --git a/Examples/php5/proxy/Makefile b/Examples/php5/proxy/Makefile new file mode 100644 index 000000000..8346a1dae --- /dev/null +++ b/Examples/php5/proxy/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/proxy/example.cxx b/Examples/php5/proxy/example.cxx new file mode 100644 index 000000000..94e4a7888 --- /dev/null +++ b/Examples/php5/proxy/example.cxx @@ -0,0 +1,43 @@ +/* File : example.c */ + +#include "example.h" +#include +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +int Shape::get_nshapes() { + return nshapes; +} + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +void Circle::set_radius( double r ) { + radius = r; +} + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} + +Circle *CircleFactory( double r ) { + return new Circle(r); +} diff --git a/Examples/php5/proxy/example.h b/Examples/php5/proxy/example.h new file mode 100644 index 000000000..0683f07f3 --- /dev/null +++ b/Examples/php5/proxy/example.h @@ -0,0 +1,43 @@ +/* File : example.h */ + +#include + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; + static int get_nshapes(); +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + ~Circle() { } + void set_radius( double r ); + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + ~Square() { } + virtual double area(void); + virtual double perimeter(void); +}; + +Circle *CircleFactory( double r ); + diff --git a/Examples/php5/proxy/example.i b/Examples/php5/proxy/example.i new file mode 100644 index 000000000..ce73746d0 --- /dev/null +++ b/Examples/php5/proxy/example.i @@ -0,0 +1,12 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ + +%newobject CircleFactory; +%include "example.h" + diff --git a/Examples/php5/proxy/runme.php b/Examples/php5/proxy/runme.php new file mode 100644 index 000000000..e70ab229f --- /dev/null +++ b/Examples/php5/proxy/runme.php @@ -0,0 +1,68 @@ +area() ."\n"; +$s = new Square(10); +print " Created square \$s\n"; + +# ----- Access a static member ----- + +print "\nA total of " . Shape::nshapes() . " shapes were created\n"; + +# ----- Member data access ----- + +# Set the location of the object. +# Note: methods in the base class Shape are used since +# x and y are defined there. + +$c->x = 20; +$c->y = 30; +$s->x = -10; +$s->y = 5; + +print "\nHere is their current position:\n"; +print " Circle = (" . $c->x . "," . $c->y . ")\n"; +print " Square = (" . $s->x . "," . $s->y . ")\n"; + +# ----- Call some methods ----- + +print "\nHere are some properties of the shapes:\n"; +foreach (array($c,$s) as $o) { + print " ".get_class($o)." \$o\n"; + print " x = " . $o->x . "\n"; + print " y = " . $o->y . "\n"; + print " area = " . $o->area() . "\n"; + print " perimeter = " . $o->perimeter() . "\n"; + } + +# Need to unset($o) or else we hang on to a reference to the Square object. +unset($o); + +# ----- Delete everything ----- + +print "\nGuess I'll clean up now\n"; + +# Note: this invokes the virtual destructor +unset($c); +$s = 42; + +print Shape::nshapes() . " shapes remain\n"; + +print "Manually setting nshapes\n"; + +Shape::nshapes(42); + +print Shape::get_nshapes() ." == 42\n"; + +print "Goodbye\n"; + +?> diff --git a/Examples/php5/reference/Makefile b/Examples/php5/reference/Makefile new file mode 100644 index 000000000..8346a1dae --- /dev/null +++ b/Examples/php5/reference/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/reference/example.cxx b/Examples/php5/reference/example.cxx new file mode 100644 index 000000000..7ead7fbf6 --- /dev/null +++ b/Examples/php5/reference/example.cxx @@ -0,0 +1,49 @@ +/* File : example.cxx */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include "example.h" +#include +#include + +Vector operator+(const Vector &a, const Vector &b) { + Vector r; + r.x = a.x + b.x; + r.y = a.y + b.y; + r.z = a.z + b.z; + return r; +} + +char *Vector::as_string() { + static char temp[512]; + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); + return temp; +} + +VectorArray::VectorArray(int size) { + items = new Vector[size]; + maxsize = size; + printf("VectorArray new: self=%p\n", (void *)this); +} + +VectorArray::~VectorArray() { + printf("VectorArray delete: self=%p\n", (void *)this); + delete [] items; +} + +Vector &VectorArray::operator[](int index) { + printf("VectorArray: read[%d] self=%p\n", index, (void *)this); + if ((index < 0) || (index >= maxsize)) { + printf("Panic! Array index out of bounds.\n"); + exit(1); + } + return items[index]; +} + +int VectorArray::size() { + printf("VectorArray: size %d self=%p\n", maxsize, (void *)this); + return maxsize; +} diff --git a/Examples/php5/reference/example.h b/Examples/php5/reference/example.h new file mode 100644 index 000000000..353b88835 --- /dev/null +++ b/Examples/php5/reference/example.h @@ -0,0 +1,22 @@ +/* File : example.h */ + +class Vector { +private: + double x,y,z; +public: + Vector() : x(0), y(0), z(0) { } + Vector(double x, double y, double z) : x(x), y(y), z(z) { } + friend Vector operator+(const Vector &a, const Vector &b); + char *as_string(); +}; + +class VectorArray { +private: + Vector *items; + int maxsize; +public: + VectorArray(int maxsize); + ~VectorArray(); + Vector &operator[](int); + int size(); +}; diff --git a/Examples/php5/reference/example.i b/Examples/php5/reference/example.i new file mode 100644 index 000000000..df1459921 --- /dev/null +++ b/Examples/php5/reference/example.i @@ -0,0 +1,43 @@ +/* File : example.i */ + +/* This file has a few "typical" uses of C++ references. */ + +%module example + +%{ +#include "example.h" +%} + +class Vector { +public: + Vector(double x, double y, double z); + ~Vector(); + char *as_string(); +}; + +/* This helper function calls an overloaded operator */ +%inline %{ +Vector addv(Vector &a, Vector &b) { + return a+b; +} +%} + +/* Wrapper around an array of vectors class */ + +class VectorArray { +public: + VectorArray(int maxsize); + ~VectorArray(); + int size(); + + /* This wrapper provides an alternative to the [] operator */ + %extend { + Vector &get(int index) { + printf("VectorArray extended get: %p %d\n", (void *)$self, index); + return (*$self)[index]; + } + void set(int index, Vector &a) { + (*$self)[index] = a; + } + } +}; diff --git a/Examples/php5/reference/runme.php b/Examples/php5/reference/runme.php new file mode 100644 index 000000000..5d264ee43 --- /dev/null +++ b/Examples/php5/reference/runme.php @@ -0,0 +1,49 @@ +as_string()}\n"; +print " Created b: {$b->as_string()}\n"; + +# ----- Call an overloaded operator ----- + +# This calls the wrapper we placed around +# +# operator+(const Vector &a, const Vector &) +# +# It returns a new allocated object. + +print "Adding a+b\n"; +$c = example::addv($a, $b); +print " a+b ={$c->as_string()}\n"; + +# ----- Create a vector array ----- + +print "Creating an array of vectors\n"; +$va = new VectorArray(10); + +print " va: size={$va->size()}\n"; + +# ----- Set some values in the array ----- + +# These operators copy the value of $a and $b to the vector array +$va->set(0, $a); +$va->set(1, $b); +$va->set(2, addv($a, $b)); + +# Get some values from the array + +print "Getting some array values\n"; +for ($i = 0; $i < 5; $i++) { + print " va[$i] = {$va->get($i)->as_string()}\n"; +} + +?> diff --git a/Examples/php5/simple/Makefile b/Examples/php5/simple/Makefile new file mode 100644 index 000000000..92085788a --- /dev/null +++ b/Examples/php5/simple/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/simple/example.c b/Examples/php5/simple/example.c new file mode 100644 index 000000000..2fe275632 --- /dev/null +++ b/Examples/php5/simple/example.c @@ -0,0 +1,23 @@ +/* File : example.c */ +#include + +/* A global variable */ +double Foo = 3.0; + +void print_Foo() { + printf("In C, Foo = %f\n",Foo); +} + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + + diff --git a/Examples/php5/simple/example.i b/Examples/php5/simple/example.i new file mode 100644 index 000000000..9d4e22aa9 --- /dev/null +++ b/Examples/php5/simple/example.i @@ -0,0 +1,8 @@ +/* File : example.i */ +%module example + +%inline %{ +extern int gcd(int x, int y); +extern double Foo; +void print_Foo(); +%} diff --git a/Examples/php5/simple/runme.php b/Examples/php5/simple/runme.php new file mode 100644 index 000000000..0e96fe800 --- /dev/null +++ b/Examples/php5/simple/runme.php @@ -0,0 +1,25 @@ + diff --git a/Examples/php5/sync/Makefile b/Examples/php5/sync/Makefile new file mode 100644 index 000000000..8346a1dae --- /dev/null +++ b/Examples/php5/sync/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/sync/example.cxx b/Examples/php5/sync/example.cxx new file mode 100644 index 000000000..0942279b2 --- /dev/null +++ b/Examples/php5/sync/example.cxx @@ -0,0 +1,13 @@ +#include "example.h" +#include + +int x = 42; +char *s = (char *)"Test"; + +void Sync::printer(void) { + + printf("The value of global s is %s\n", s); + printf("The value of global x is %d\n", x); + printf("The value of class s is %s\n", s); + printf("The value of class x is %d\n", x); +} diff --git a/Examples/php5/sync/example.h b/Examples/php5/sync/example.h new file mode 100644 index 000000000..d67ec21dc --- /dev/null +++ b/Examples/php5/sync/example.h @@ -0,0 +1,9 @@ +extern char *s; +extern int x; + +class Sync { + public: + int x; + char *s; + void printer(void); +}; diff --git a/Examples/php5/sync/example.i b/Examples/php5/sync/example.i new file mode 100644 index 000000000..17ff87cf3 --- /dev/null +++ b/Examples/php5/sync/example.i @@ -0,0 +1,7 @@ +%module example + +%{ +#include "example.h" +%} + +%include "example.h" diff --git a/Examples/php5/sync/runme.php b/Examples/php5/sync/runme.php new file mode 100644 index 000000000..a7c43474f --- /dev/null +++ b/Examples/php5/sync/runme.php @@ -0,0 +1,15 @@ +printer(); + +?> + diff --git a/Examples/php5/value/Makefile b/Examples/php5/value/Makefile new file mode 100644 index 000000000..b0b5e20ac --- /dev/null +++ b/Examples/php5/value/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = -noproxy + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/value/example.c b/Examples/php5/value/example.c new file mode 100644 index 000000000..3c402a214 --- /dev/null +++ b/Examples/php5/value/example.c @@ -0,0 +1,13 @@ +/* File : example.c */ + +#include "example.h" + +double dot_product(Vector a, Vector b) { + return (a.x*b.x + a.y*b.y + a.z*b.z); +} + +void vector_add(Vector a, Vector b, Vector* result) { + result->x = a.x + b.x; + result->y = a.y + b.y; + result->z = a.z + b.z; +} diff --git a/Examples/php5/value/example.h b/Examples/php5/value/example.h new file mode 100644 index 000000000..f55752a5f --- /dev/null +++ b/Examples/php5/value/example.h @@ -0,0 +1,8 @@ +/* File : example.h */ + +typedef struct { + double x, y, z; +} Vector; + +double dot_product(Vector a, Vector b); +void vector_add(Vector a, Vector b, Vector* result); diff --git a/Examples/php5/value/example.i b/Examples/php5/value/example.i new file mode 100644 index 000000000..20a453468 --- /dev/null +++ b/Examples/php5/value/example.i @@ -0,0 +1,17 @@ +// Tests SWIG's handling of pass-by-value for complex datatypes +%module example + +%{ +#include "example.h" +%} + +%include "example.h" + +/* Some helper functions for our interface */ +%inline %{ + +void vector_print(Vector *v) { + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); +} +%} + diff --git a/Examples/php5/value/runme.php b/Examples/php5/value/runme.php new file mode 100644 index 000000000..49115376c --- /dev/null +++ b/Examples/php5/value/runme.php @@ -0,0 +1,43 @@ + + + diff --git a/Examples/php5/variables/Makefile b/Examples/php5/variables/Makefile new file mode 100644 index 000000000..92085788a --- /dev/null +++ b/Examples/php5/variables/Makefile @@ -0,0 +1,20 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i +LIBS = +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ + php5 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php5_clean diff --git a/Examples/php5/variables/example.c b/Examples/php5/variables/example.c new file mode 100644 index 000000000..d4c6d026d --- /dev/null +++ b/Examples/php5/variables/example.c @@ -0,0 +1,95 @@ +/* File : example.c */ + +/* I'm a file containing some C global variables */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include +#include +#include "example.h" + +int ivar = 0; +short svar = 0; +long lvar = 0; +unsigned int uivar = 0; +unsigned short usvar = 0; +unsigned long ulvar = 0; +signed char scvar = 0; +unsigned char ucvar = 0; +char cvar = 0; +float fvar = 0; +double dvar = 0; +char *strvar = 0; +const char cstrvar[] = "Goodbye"; +int *iptrvar = 0; +char name[5] = "Dave"; +char path[256] = "/home/beazley"; + + +/* Global variables involving a structure */ +Point *ptptr = 0; +Point pt = { 10, 20 }; + +/* A variable that we will make read-only in the interface */ +int status = 1; + +/* A debugging function to print out their values */ + +void print_vars() { + printf("ivar = %d\n", ivar); + printf("svar = %d\n", svar); + printf("lvar = %ld\n", lvar); + printf("uivar = %u\n", uivar); + printf("usvar = %u\n", usvar); + printf("ulvar = %lu\n", ulvar); + printf("scvar = %d\n", scvar); + printf("ucvar = %u\n", ucvar); + printf("fvar = %g\n", fvar); + printf("dvar = %g\n", dvar); + printf("cvar = %c\n", cvar); + printf("strvar = %s\n", strvar ? strvar : "(null)"); + printf("cstrvar = %s\n", cstrvar); + printf("iptrvar = %p\n", (void *)iptrvar); + printf("name = %c%c%c%c%c\n", name[0],name[1],name[2],name[3],name[4]); + printf("ptptr = %p %s\n", (void *)ptptr, Point_print( ptptr ) ); + printf("pt = (%d, %d)\n", pt.x, pt.y); + printf("status = %d\n", status); +} + +/* A function to create an integer (to test iptrvar) */ + +int *new_int(int value) { + int *ip = (int *) malloc(sizeof(int)); + *ip = value; + return ip; +} + +int value_int(int *value) { + return *value; +} + +/* A function to create a point */ + +Point *new_Point(int x, int y) { + Point *p = (Point *) malloc(sizeof(Point)); + p->x = x; + p->y = y; + return p; +} + +char * Point_print(Point *p) { + static char buffer[256]; + if (p) { + sprintf(buffer,"(%d,%d)", p->x,p->y); + } else { + sprintf(buffer,"null"); + } + return buffer; +} + +void pt_print() { + printf("(%d, %d)\n", pt.x, pt.y); +} diff --git a/Examples/php5/variables/example.h b/Examples/php5/variables/example.h new file mode 100644 index 000000000..3b3659ce5 --- /dev/null +++ b/Examples/php5/variables/example.h @@ -0,0 +1,34 @@ +/* File: example.h */ + +typedef struct { + int x,y; +} Point; + +/* Some global variable declarations */ +extern int ivar; +extern short svar; +extern long lvar; +extern unsigned int uivar; +extern unsigned short usvar; +extern unsigned long ulvar; +extern signed char scvar; +extern unsigned char ucvar; +extern char cvar; +extern float fvar; +extern double dvar; +extern char *strvar; +extern const char cstrvar[]; +extern int *iptrvar; +extern char name[5]; + +extern Point *ptptr; +extern Point pt; + +extern int status; +extern char path[256]; + +extern void print_vars(); +extern int *new_int(int value); +extern Point *new_Point(int x, int y); +extern char *Point_print(Point *p); +extern void pt_print(); diff --git a/Examples/php5/variables/example.i b/Examples/php5/variables/example.i new file mode 100644 index 000000000..3edbb72d7 --- /dev/null +++ b/Examples/php5/variables/example.i @@ -0,0 +1,44 @@ +/* File : example.i */ +%module example +%{ +#include "example.h" +%} + +/* Some global variable declarations */ +extern int ivar; +extern short svar; +extern long lvar; +extern unsigned int uivar; +extern unsigned short usvar; +extern unsigned long ulvar; +extern signed char scvar; +extern unsigned char ucvar; +extern char cvar; +extern float fvar; +extern double dvar; +extern char *strvar; +extern const char cstrvar[]; +extern int *iptrvar; +extern char name[5]; + +extern Point *ptptr; +extern Point pt; + +/* Some read-only variables */ + +%immutable; +extern int status; +extern char path[256]; +%mutable; + +/* Some helper functions to make it easier to test */ +extern void print_vars(); +extern int *new_int(int value); + +extern Point *new_Point(int x, int y); +extern char *Point_print(Point *p); +extern void pt_print(); + + + + diff --git a/Examples/php5/variables/runme.php b/Examples/php5/variables/runme.php new file mode 100644 index 000000000..bbfeb610b --- /dev/null +++ b/Examples/php5/variables/runme.php @@ -0,0 +1,96 @@ + + diff --git a/Examples/pike/class/Makefile b/Examples/pike/class/Makefile index d8cf4ea7e..e5319dbe2 100644 --- a/Examples/pike/class/Makefile +++ b/Examples/pike/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: diff --git a/Examples/pike/constants/Makefile b/Examples/pike/constants/Makefile index 736d30f03..45da7d269 100644 --- a/Examples/pike/constants/Makefile +++ b/Examples/pike/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike static: - $(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)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static clean: diff --git a/Examples/pike/enum/Makefile b/Examples/pike/enum/Makefile index d8cf4ea7e..e5319dbe2 100644 --- a/Examples/pike/enum/Makefile +++ b/Examples/pike/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: diff --git a/Examples/pike/overload/Makefile b/Examples/pike/overload/Makefile index f111b1137..5e5fe669b 100644 --- a/Examples/pike/overload/Makefile +++ b/Examples/pike/overload/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: diff --git a/Examples/pike/simple/Makefile b/Examples/pike/simple/Makefile index d7f6b209e..8b49b4ea5 100644 --- a/Examples/pike/simple/Makefile +++ b/Examples/pike/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike static: - $(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)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static clean: diff --git a/Examples/pike/template/Makefile b/Examples/pike/template/Makefile index da115c1d5..513dc3b4b 100644 --- a/Examples/pike/template/Makefile +++ b/Examples/pike/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: diff --git a/Examples/python/callback/Makefile b/Examples/python/callback/Makefile index a4c4d2a69..71926f397 100644 --- a/Examples/python/callback/Makefile +++ b/Examples/python/callback/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/class/Makefile b/Examples/python/class/Makefile index 41cded284..471e39073 100644 --- a/Examples/python/class/Makefile +++ b/Examples/python/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/constants/Makefile b/Examples/python/constants/Makefile index 8ec6e9cc9..a412cf299 100644 --- a/Examples/python/constants/Makefile +++ b/Examples/python/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/contract/Makefile b/Examples/python/contract/Makefile index fe1d9325e..54817c79d 100644 --- a/Examples/python/contract/Makefile +++ b/Examples/python/contract/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -9,12 +10,14 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mypython' INTERFACE='$(INTERFACE)' python_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/docstrings/Makefile b/Examples/python/docstrings/Makefile index f471930dd..f1365a599 100644 --- a/Examples/python/docstrings/Makefile +++ b/Examples/python/docstrings/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,12 +11,14 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static diff --git a/Examples/python/enum/Makefile b/Examples/python/enum/Makefile index 41cded284..471e39073 100644 --- a/Examples/python/enum/Makefile +++ b/Examples/python/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/exception/Makefile b/Examples/python/exception/Makefile index ad3d49fe1..8420c8297 100644 --- a/Examples/python/exception/Makefile +++ b/Examples/python/exception/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/exceptproxy/Makefile b/Examples/python/exceptproxy/Makefile index f406dfaf4..65af5ec82 100644 --- a/Examples/python/exceptproxy/Makefile +++ b/Examples/python/exceptproxy/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/extend/Makefile b/Examples/python/extend/Makefile index a4c4d2a69..71926f397 100644 --- a/Examples/python/extend/Makefile +++ b/Examples/python/extend/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/funcptr/Makefile b/Examples/python/funcptr/Makefile index 222916fa1..26bfd946e 100644 --- a/Examples/python/funcptr/Makefile +++ b/Examples/python/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 = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/funcptr2/Makefile b/Examples/python/funcptr2/Makefile index 222916fa1..26bfd946e 100644 --- a/Examples/python/funcptr2/Makefile +++ b/Examples/python/funcptr2/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/functor/Makefile b/Examples/python/functor/Makefile index 1234c310e..e5de5c5b7 100644 --- a/Examples/python/functor/Makefile +++ b/Examples/python/functor/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/import/Makefile b/Examples/python/import/Makefile index d83dfeaa8..ad208b3e7 100644 --- a/Examples/python/import/Makefile +++ b/Examples/python/import/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp clean: diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile index 34362f65a..f428d6f5c 100644 --- a/Examples/python/import_packages/Makefile +++ b/Examples/python/import_packages/Makefile @@ -1,5 +1,4 @@ TOP = ../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = @@ -11,11 +10,15 @@ import_packages_subdirs = \ from_init3 \ relativeimport1 \ relativeimport2 \ - relativeimport3 + relativeimport3 \ + split_modules \ + namespace_pkg + check: build if test "x$(SRCDIR)" != x; then \ - for file in `cd $(SRCDIR) && find . -type f -name __init__.py`; do \ + for file in `cd $(SRCDIR) && find . -type f -name "*.py"`; do \ + mkdir -p `dirname $$file`; \ cp "${SRCDIR}$$file" "$$file" || exit 1; \ done; \ fi; \ @@ -25,18 +28,18 @@ check: build build: for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ done static: for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \ done clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean if test "x$(SRCDIR)" != x; then \ - for file in `cd $(SRCDIR) && find . -type f -name __init__.py`; do \ + for file in `cd $(SRCDIR) && find . -type f -name "*.py"`; do \ rm -f "$$file" || exit 1; \ done; \ fi; \ diff --git a/Examples/python/import_packages/README b/Examples/python/import_packages/README index 69fe3516e..187a5d64e 100644 --- a/Examples/python/import_packages/README +++ b/Examples/python/import_packages/README @@ -1,2 +1,4 @@ These are actually regression tests for SF bug #1297 (GH issue #7). -See individual READMEs in subdirectories. +The namespace_pkg is an example of python3's namespace packages. + +See individual READMEs in subdirectories. \ No newline at end of file diff --git a/Examples/python/import_packages/from_init1/Makefile b/Examples/python/import_packages/from_init1/Makefile index dd38f90bd..90c92ab1c 100644 --- a/Examples/python/import_packages/from_init1/Makefile +++ b/Examples/python/import_packages/from_init1/Makefile @@ -1,6 +1,4 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = ifeq (,$(PY3)) @@ -13,10 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build static: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init1/py2/Makefile b/Examples/python/import_packages/from_init1/py2/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/from_init1/py2/Makefile +++ b/Examples/python/import_packages/from_init1/py2/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/Makefile b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile index 1eb810e05..102a8938b 100644 --- a/Examples/python/import_packages/from_init1/py2/pkg2/Makefile +++ b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile @@ -1,19 +1,24 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp_static clean:: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init1/py3/Makefile b/Examples/python/import_packages/from_init1/py3/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/from_init1/py3/Makefile +++ b/Examples/python/import_packages/from_init1/py3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/Makefile b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile index 1eb810e05..102a8938b 100644 --- a/Examples/python/import_packages/from_init1/py3/pkg2/Makefile +++ b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile @@ -1,19 +1,24 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp_static clean:: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init2/Makefile b/Examples/python/import_packages/from_init2/Makefile index dd38f90bd..90c92ab1c 100644 --- a/Examples/python/import_packages/from_init2/Makefile +++ b/Examples/python/import_packages/from_init2/Makefile @@ -1,6 +1,4 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = ifeq (,$(PY3)) @@ -13,10 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build static: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init2/py2/Makefile b/Examples/python/import_packages/from_init2/py2/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/from_init2/py2/Makefile +++ b/Examples/python/import_packages/from_init2/py2/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/from_init2/py2/pkg2/Makefile +++ b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile index cb20bd25f..7a0cb18ad 100644 --- a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init2/py3/Makefile b/Examples/python/import_packages/from_init2/py3/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/from_init2/py3/Makefile +++ b/Examples/python/import_packages/from_init2/py3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/from_init2/py3/pkg2/Makefile +++ b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile index cb20bd25f..7a0cb18ad 100644 --- a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init3/Makefile b/Examples/python/import_packages/from_init3/Makefile index dd38f90bd..90c92ab1c 100644 --- a/Examples/python/import_packages/from_init3/Makefile +++ b/Examples/python/import_packages/from_init3/Makefile @@ -1,6 +1,4 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = ifeq (,$(PY3)) @@ -13,10 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build static: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init3/py2/Makefile b/Examples/python/import_packages/from_init3/py2/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/from_init3/py2/Makefile +++ b/Examples/python/import_packages/from_init3/py2/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/from_init3/py2/pkg2/Makefile +++ b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile index d6ae1b2bc..6f193fa33 100644 --- a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile index 286d90070..a870607e2 100644 --- a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init3/py3/Makefile b/Examples/python/import_packages/from_init3/py3/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/from_init3/py3/Makefile +++ b/Examples/python/import_packages/from_init3/py3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/from_init3/py3/pkg2/Makefile +++ b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile index d6ae1b2bc..6f193fa33 100644 --- a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile index 286d90070..a870607e2 100644 --- a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/namespace_pkg/Makefile b/Examples/python/import_packages/namespace_pkg/Makefile new file mode 100644 index 000000000..d86871344 --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/Makefile @@ -0,0 +1,17 @@ +TOP = ../../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +TARGET = robin +INTERFACE = robin.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -rf path1 path2 path3 path4.zip diff --git a/Examples/python/import_packages/namespace_pkg/README b/Examples/python/import_packages/namespace_pkg/README new file mode 100644 index 000000000..8f7297a51 --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/README @@ -0,0 +1,25 @@ + This is an example (and test) of using swig generated modules in the context +of python3's namespace packages: + +https://www.python.org/dev/peps/pep-0420/ + + Consequently, this example requires python (3.3 or newer) to build and run. + + This example creates a simple swig module named robin. The robin.py module +has a companion C module named _robin.so. The robin module is tested in four +ways: + + 1) As a non-package module (tested by nonpkg.py) + + 2) With robin.py and _robin.so in the brave package under the path1 + subdirectory. (tested by normal.py) + + 3) With robin.py in path2/brave and _robin.so in path3/brave + (tested by split.py) + + 4) With robin.py contained in a zip file (path4.zip) as brave/robin.py and + _robin.so found on the filesystem under path3/brave (tested by zipsplit.py) + +Note: Using namespace packages with subpackages (such as brave.sir.robin) where + robin.py is located in a zipfile requires python-3.5.1 or newer as + python's zipimporter only worked with packages of depth 1 until then. \ No newline at end of file diff --git a/Examples/python/import_packages/namespace_pkg/nonpkg.py b/Examples/python/import_packages/namespace_pkg/nonpkg.py new file mode 100644 index 000000000..acf0aedbd --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/nonpkg.py @@ -0,0 +1,5 @@ +# import robin as a module in the global namespace + +import robin + +assert(robin.run() == "AWAY!") diff --git a/Examples/python/import_packages/namespace_pkg/normal.py b/Examples/python/import_packages/namespace_pkg/normal.py new file mode 100644 index 000000000..fc26c0216 --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/normal.py @@ -0,0 +1,7 @@ +import sys +# Package brave found under one path +sys.path.insert(0, 'path1') + +from brave import robin + +assert(robin.run() == "AWAY!") diff --git a/Examples/python/import_packages/namespace_pkg/nstest.py b/Examples/python/import_packages/namespace_pkg/nstest.py new file mode 100644 index 000000000..9b075ad8c --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/nstest.py @@ -0,0 +1,45 @@ +import sys +import os +import shutil +import zipfile + + +def copyMods(): + dirs = ['path1', 'path2', 'path3'] + + # Clean out any old package paths + for d in dirs: + if os.path.isdir(d): + shutil.rmtree(d) + + for d in dirs: + os.mkdir(d) + os.mkdir(os.path.join(d, 'brave')) + + shutil.copy('robin.py', os.path.join('path1', 'brave')) + os.system('cp _robin.* ' + os.path.join('path1', 'brave')) + + shutil.copy('robin.py', os.path.join('path2', 'brave')) + os.system('cp _robin.* ' + os.path.join('path3', 'brave')) + + mkzip() + +def mkzip(): + zf = zipfile.ZipFile("path4.zip", "w") + zf.writestr("brave/", b'') + zf.write('robin.py', 'brave/robin.py') + zf.close() + + +def main(): + copyMods() + + # Run each test with a separate interpreter + os.system(sys.executable + " nonpkg.py") + os.system(sys.executable + " normal.py") + os.system(sys.executable + " split.py") + os.system(sys.executable + " zipsplit.py") + + +if __name__ == "__main__": + main() diff --git a/Examples/python/import_packages/namespace_pkg/robin.i b/Examples/python/import_packages/namespace_pkg/robin.i new file mode 100644 index 000000000..394922130 --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/robin.i @@ -0,0 +1,7 @@ +%module robin + +%inline %{ +const char *run(void) { + return "AWAY!"; +} +%} diff --git a/Examples/python/import_packages/namespace_pkg/runme.py b/Examples/python/import_packages/namespace_pkg/runme.py new file mode 100644 index 000000000..9c22d36fb --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/runme.py @@ -0,0 +1,17 @@ +# These examples rely on namespace packages. Don't +# run them for old python interpreters. +import sys +import os.path + +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - namespace packages" + +if sys.version_info < (3, 3, 0): + print " Not importing nstest as Python version is < 3.3" + sys.exit(0) + +import nstest + +print " Finished importing nstest" + +nstest.main() diff --git a/Examples/python/import_packages/namespace_pkg/split.py b/Examples/python/import_packages/namespace_pkg/split.py new file mode 100644 index 000000000..1b66c2d49 --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/split.py @@ -0,0 +1,9 @@ +import sys +# Package brave split into two paths. +# path2/brave/robin.py and path3/brave/_robin.so +sys.path.insert(0, 'path2') +sys.path.insert(0, 'path3') + +from brave import robin + +assert(robin.run() == "AWAY!") diff --git a/Examples/python/import_packages/namespace_pkg/zipsplit.py b/Examples/python/import_packages/namespace_pkg/zipsplit.py new file mode 100644 index 000000000..9e35559e3 --- /dev/null +++ b/Examples/python/import_packages/namespace_pkg/zipsplit.py @@ -0,0 +1,9 @@ +import sys +# Package brave split into two paths. +# brave/robin.py (in path4.zip) and path3/brave/_robin.so +sys.path.insert(0, 'path4.zip') +sys.path.insert(0, 'path3') + +from brave import robin + +assert(robin.run() == "AWAY!") diff --git a/Examples/python/import_packages/relativeimport1/Makefile b/Examples/python/import_packages/relativeimport1/Makefile index dd38f90bd..90c92ab1c 100644 --- a/Examples/python/import_packages/relativeimport1/Makefile +++ b/Examples/python/import_packages/relativeimport1/Makefile @@ -1,6 +1,4 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = ifeq (,$(PY3)) @@ -13,10 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build static: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py2/Makefile b/Examples/python/import_packages/relativeimport1/py2/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/relativeimport1/py2/Makefile +++ b/Examples/python/import_packages/relativeimport1/py2/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile index cb20bd25f..7a0cb18ad 100644 --- a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py3/Makefile b/Examples/python/import_packages/relativeimport1/py3/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/relativeimport1/py3/Makefile +++ b/Examples/python/import_packages/relativeimport1/py3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile index cb20bd25f..7a0cb18ad 100644 --- a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport2/Makefile b/Examples/python/import_packages/relativeimport2/Makefile index dd38f90bd..90c92ab1c 100644 --- a/Examples/python/import_packages/relativeimport2/Makefile +++ b/Examples/python/import_packages/relativeimport2/Makefile @@ -1,6 +1,4 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = ifeq (,$(PY3)) @@ -13,10 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build static: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py2/Makefile b/Examples/python/import_packages/relativeimport2/py2/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/relativeimport2/py2/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile index d6ae1b2bc..6f193fa33 100644 --- a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile index 286d90070..a870607e2 100644 --- a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py3/Makefile b/Examples/python/import_packages/relativeimport2/py3/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/relativeimport2/py3/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile index d6ae1b2bc..6f193fa33 100644 --- a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile index 286d90070..a870607e2 100644 --- a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport3/Makefile b/Examples/python/import_packages/relativeimport3/Makefile index dd38f90bd..90c92ab1c 100644 --- a/Examples/python/import_packages/relativeimport3/Makefile +++ b/Examples/python/import_packages/relativeimport3/Makefile @@ -1,6 +1,4 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = ifeq (,$(PY3)) @@ -13,10 +11,10 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build static: - cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport3/py2/Makefile b/Examples/python/import_packages/relativeimport3/py2/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/relativeimport3/py2/Makefile +++ b/Examples/python/import_packages/relativeimport3/py2/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/Makefile index cb20bd25f..7a0cb18ad 100644 --- a/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport3/py3/Makefile b/Examples/python/import_packages/relativeimport3/py3/Makefile index 9595397d8..629625144 100644 --- a/Examples/python/import_packages/relativeimport3/py3/Makefile +++ b/Examples/python/import_packages/relativeimport3/py3/Makefile @@ -1,13 +1,12 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = build: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile index 36e099b78..c1f234e34 100644 --- a/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile @@ -1,17 +1,20 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - cd pkg3 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/Makefile index cb20bd25f..7a0cb18ad 100644 --- a/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/Makefile b/Examples/python/import_packages/same_modnames1/Makefile index e05c13017..57148c614 100644 --- a/Examples/python/import_packages/same_modnames1/Makefile +++ b/Examples/python/import_packages/same_modnames1/Makefile @@ -1,18 +1,16 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static - cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/same_modnames1/pkg1/Makefile b/Examples/python/import_packages/same_modnames1/pkg1/Makefile index df1b30321..3ca7fab03 100644 --- a/Examples/python/import_packages/same_modnames1/pkg1/Makefile +++ b/Examples/python/import_packages/same_modnames1/pkg1/Makefile @@ -1,15 +1,18 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/pkg2/Makefile b/Examples/python/import_packages/same_modnames1/pkg2/Makefile index df1b30321..3ca7fab03 100644 --- a/Examples/python/import_packages/same_modnames1/pkg2/Makefile +++ b/Examples/python/import_packages/same_modnames1/pkg2/Makefile @@ -1,15 +1,18 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py index 2107597b3..3c3c00c1a 100644 --- a/Examples/python/import_packages/same_modnames1/runme.py +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -8,6 +8,12 @@ import pkg2.foo print " Finished importing pkg2.foo" var2 = pkg2.foo.Pkg2_Foo() -if str(type(var2)).find("'pkg2.foo.Pkg2_Foo'") == -1: - raise RuntimeError("failed type checking: " + str(type(var2))) + +classname = str(type(var2)) +# Check for an old-style class if swig was run in -classic mode +if classname == "": + classname = str(var2.__class__) + +if classname.find("pkg2.foo.Pkg2_Foo") == -1: + raise RuntimeError("failed type checking: " + classname) print " Successfully created object pkg2.foo.Pkg2_Foo" diff --git a/Examples/python/import_packages/same_modnames2/Makefile b/Examples/python/import_packages/same_modnames2/Makefile index 770343a80..cf6db0c41 100644 --- a/Examples/python/import_packages/same_modnames2/Makefile +++ b/Examples/python/import_packages/same_modnames2/Makefile @@ -1,18 +1,16 @@ TOP = ../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) -SWIGOPT = LIBS = check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build - cd pkg1/pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg1/pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build static: - cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static - cd pkg1/pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + cd pkg1/pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean diff --git a/Examples/python/import_packages/same_modnames2/pkg1/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/Makefile index df1b30321..3ca7fab03 100644 --- a/Examples/python/import_packages/same_modnames2/pkg1/Makefile +++ b/Examples/python/import_packages/same_modnames2/pkg1/Makefile @@ -1,15 +1,18 @@ TOP = ../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile index 11e8573ad..921bb9951 100644 --- a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile @@ -1,15 +1,18 @@ TOP = ../../../../.. -SWIG = $(realpath $(TOP)/../preinst-swig) +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py index 41ff1afec..38daad0a3 100644 --- a/Examples/python/import_packages/same_modnames2/runme.py +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -7,6 +7,12 @@ import pkg1.pkg2.foo print " Finished importing pkg1.pkg2.foo" var2 = pkg1.pkg2.foo.Pkg2_Foo() -if str(type(var2)).find("'pkg1.pkg2.foo.Pkg2_Foo'") == -1: - raise RuntimeError("failed type checking: " + str(type(var2))) + +classname = str(type(var2)) +# Check for an old-style class if swig was run in -classic mode +if classname == "": + classname = str(var2.__class__) + +if classname.find("pkg1.pkg2.foo.Pkg2_Foo") == -1: + raise RuntimeError("failed type checking: " + classname) print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo" diff --git a/Examples/python/import_packages/split_modules/Makefile b/Examples/python/import_packages/split_modules/Makefile new file mode 100644 index 000000000..65d635bb7 --- /dev/null +++ b/Examples/python/import_packages/split_modules/Makefile @@ -0,0 +1,26 @@ +TOP = ../../.. +LIBS = + +subdirs = vanilla vanilla_split + + +check: build + for s in $(subdirs); do \ + (cd $$s && $(MAKE) check); \ + done + +build: + for s in $(subdirs); do \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ + done + +static: + for s in $(subdirs); do \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \ + done + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + for s in $(subdirs); do \ + (cd $$s && $(MAKE) clean); \ + done diff --git a/Examples/python/import_packages/split_modules/README b/Examples/python/import_packages/split_modules/README new file mode 100644 index 000000000..0cb543e8a --- /dev/null +++ b/Examples/python/import_packages/split_modules/README @@ -0,0 +1,7 @@ + These examples/tests are for when the SWIG generated wrapper module is split +between two packages. Specifically the pure python part is part of a package +and the C/C++ part is not in any package at all. Historically SWIG has +supported this sort of thing. + +vanilla # "plane Jane" module both halves in pkg1 +vanilla_split # python 1/2 in pkg1 C 1/2 in global namespace diff --git a/Examples/python/import_packages/split_modules/vanilla/Makefile b/Examples/python/import_packages/split_modules/vanilla/Makefile new file mode 100644 index 000000000..b679d60a0 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SWIGOPT = +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd pkg1 && $(MAKE) build + +static: + cd pkg1 && $(MAKE) static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean + cd pkg1 && $(MAKE) -f $(TOP)/../Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/split_modules/vanilla/pkg1/Makefile b/Examples/python/import_packages/split_modules/vanilla/pkg1/Makefile new file mode 100644 index 000000000..921bb9951 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla/pkg1/Makefile @@ -0,0 +1,18 @@ +TOP = ../../../../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/split_modules/vanilla/pkg1/__init__.py b/Examples/python/import_packages/split_modules/vanilla/pkg1/__init__.py new file mode 100644 index 000000000..7b1594cc8 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla/pkg1/__init__.py @@ -0,0 +1 @@ +# killroy was here diff --git a/Examples/python/import_packages/split_modules/vanilla/pkg1/foo.i b/Examples/python/import_packages/split_modules/vanilla/pkg1/foo.i new file mode 100644 index 000000000..60ce16ec3 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla/pkg1/foo.i @@ -0,0 +1,10 @@ +%module(package="pkg1") foo +%{ +static unsigned count(void) +{ + return 3; +} +%} + +unsigned count(void); + diff --git a/Examples/python/import_packages/split_modules/vanilla/runme.py b/Examples/python/import_packages/split_modules/vanilla/runme.py new file mode 100644 index 000000000..a188364f1 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla/runme.py @@ -0,0 +1,10 @@ +import os.path + +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - split modules" + +import pkg1.foo + +print " Finished importing pkg1.foo" + +assert(pkg1.foo.count() == 3) diff --git a/Examples/python/import_packages/split_modules/vanilla_split/Makefile b/Examples/python/import_packages/split_modules/vanilla_split/Makefile new file mode 100644 index 000000000..c322b5aec --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla_split/Makefile @@ -0,0 +1,22 @@ +TOP = ../../../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SWIGOPT = -outdir pkg1 +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean + cd pkg1 && $(MAKE) -f $(TOP)/../Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/split_modules/vanilla_split/foo.i b/Examples/python/import_packages/split_modules/vanilla_split/foo.i new file mode 100644 index 000000000..60ce16ec3 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla_split/foo.i @@ -0,0 +1,10 @@ +%module(package="pkg1") foo +%{ +static unsigned count(void) +{ + return 3; +} +%} + +unsigned count(void); + diff --git a/Examples/python/import_packages/split_modules/vanilla_split/pkg1/__init__.py b/Examples/python/import_packages/split_modules/vanilla_split/pkg1/__init__.py new file mode 100644 index 000000000..7b1594cc8 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla_split/pkg1/__init__.py @@ -0,0 +1 @@ +# killroy was here diff --git a/Examples/python/import_packages/split_modules/vanilla_split/runme.py b/Examples/python/import_packages/split_modules/vanilla_split/runme.py new file mode 100644 index 000000000..a188364f1 --- /dev/null +++ b/Examples/python/import_packages/split_modules/vanilla_split/runme.py @@ -0,0 +1,10 @@ +import os.path + +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - split modules" + +import pkg1.foo + +print " Finished importing pkg1.foo" + +assert(pkg1.foo.count() == 3) diff --git a/Examples/python/import_template/Makefile b/Examples/python/import_template/Makefile index d83dfeaa8..ad208b3e7 100644 --- a/Examples/python/import_template/Makefile +++ b/Examples/python/import_template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp clean: diff --git a/Examples/python/java/Makefile b/Examples/python/java/Makefile index 4befa38ba..7c75e6b91 100644 --- a/Examples/python/java/Makefile +++ b/Examples/python/java/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ CXXSHARED="gcj -fpic -shared Example.class" DEFS='' LIBS="-lstdc++" python_cpp diff --git a/Examples/python/libffi/Makefile b/Examples/python/libffi/Makefile index db5dfe138..0875fdd96 100644 --- a/Examples/python/libffi/Makefile +++ b/Examples/python/libffi/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS='-L/usr/local/lib -lffi' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/libffi/example.i b/Examples/python/libffi/example.i index 9a29ec04e..3f5d766c5 100644 --- a/Examples/python/libffi/example.i +++ b/Examples/python/libffi/example.i @@ -20,7 +20,7 @@ PyObject *o = PyTuple_GetItem(varargs,i); if (!PyString_Check(o)) { PyErr_SetString(PyExc_ValueError,"Expected a string"); - return NULL; + SWIG_fail; } argv[i] = PyString_AsString(o); } @@ -58,11 +58,11 @@ &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); @@ -107,9 +107,9 @@ int execlp(const char *path, const char *arg1, ...); argv[i].type = VT_POINTER; argv[i].val.pvalue = (void *) PyString_AsString(o); } else { - PyErr_SetString(PyExc_ValueError,"Unsupported argument type"); free(argv); - return NULL; + PyErr_SetString(PyExc_ValueError,"Unsupported argument type"); + SWIG_fail; } } @@ -157,11 +157,11 @@ int execlp(const char *path, const char *arg1, ...); &ffi_type_uint, types) == FFI_OK) { ffi_call(&cif, (void (*)()) printf, &result, values); } else { - PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); free(types); free(values); free(args); - return NULL; + PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); + SWIG_fail; } free(types); free(values); diff --git a/Examples/python/multimap/Makefile b/Examples/python/multimap/Makefile index 222916fa1..26bfd946e 100644 --- a/Examples/python/multimap/Makefile +++ b/Examples/python/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/multimap/example.i b/Examples/python/multimap/example.i index 635f61c13..66c0f74c6 100644 --- a/Examples/python/multimap/example.i +++ b/Examples/python/multimap/example.i @@ -69,7 +69,7 @@ extern int gcdmain(int argc, char *argv[]); PyObject *utf8str; if (!PyUnicode_Check($input)) { PyErr_SetString(PyExc_ValueError,"Expected a string"); - return NULL; + SWIG_fail; } utf8str = PyUnicode_AsUTF8String($input); PyBytes_AsStringAndSize(utf8str, &cstr, &len); @@ -79,7 +79,7 @@ extern int gcdmain(int argc, char *argv[]); %#else if (!PyString_Check($input)) { PyErr_SetString(PyExc_ValueError,"Expected a string"); - return NULL; + SWIG_fail; } $1 = PyString_AsString($input); $2 = (int)PyString_Size($input); diff --git a/Examples/python/operator/Makefile b/Examples/python/operator/Makefile index 1234c310e..e5de5c5b7 100644 --- a/Examples/python/operator/Makefile +++ b/Examples/python/operator/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/performance/constructor/Makefile b/Examples/python/performance/constructor/Makefile index 8e65123cf..cbc11543f 100644 --- a/Examples/python/performance/constructor/Makefile +++ b/Examples/python/performance/constructor/Makefile @@ -1,19 +1,24 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-module Simple_baseline' TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-O -module Simple_optimized' TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-builtin -O -module Simple_builtin' TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/performance/func/Makefile b/Examples/python/performance/func/Makefile index 8e65123cf..cbc11543f 100644 --- a/Examples/python/performance/func/Makefile +++ b/Examples/python/performance/func/Makefile @@ -1,19 +1,24 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-module Simple_baseline' TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-O -module Simple_optimized' TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-builtin -O -module Simple_builtin' TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/performance/hierarchy/Makefile b/Examples/python/performance/hierarchy/Makefile index 8e65123cf..cbc11543f 100644 --- a/Examples/python/performance/hierarchy/Makefile +++ b/Examples/python/performance/hierarchy/Makefile @@ -1,19 +1,24 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-module Simple_baseline' TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-O -module Simple_optimized' TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-builtin -O -module Simple_builtin' TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/performance/hierarchy_operator/Makefile b/Examples/python/performance/hierarchy_operator/Makefile index 8e65123cf..cbc11543f 100644 --- a/Examples/python/performance/hierarchy_operator/Makefile +++ b/Examples/python/performance/hierarchy_operator/Makefile @@ -1,19 +1,24 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-module Simple_baseline' TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-O -module Simple_optimized' TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-builtin -O -module Simple_builtin' TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/performance/operator/Makefile b/Examples/python/performance/operator/Makefile index 8e65123cf..cbc11543f 100644 --- a/Examples/python/performance/operator/Makefile +++ b/Examples/python/performance/operator/Makefile @@ -1,19 +1,24 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-module Simple_baseline' TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-O -module Simple_optimized' TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-builtin -O -module Simple_builtin' TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/pointer/Makefile b/Examples/python/pointer/Makefile index 222916fa1..26bfd946e 100644 --- a/Examples/python/pointer/Makefile +++ b/Examples/python/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/reference/Makefile b/Examples/python/reference/Makefile index 41cded284..471e39073 100644 --- a/Examples/python/reference/Makefile +++ b/Examples/python/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/simple/Makefile b/Examples/python/simple/Makefile index 222916fa1..26bfd946e 100644 --- a/Examples/python/simple/Makefile +++ b/Examples/python/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/smartptr/Makefile b/Examples/python/smartptr/Makefile index 19609353d..34edcfc40 100644 --- a/Examples/python/smartptr/Makefile +++ b/Examples/python/smartptr/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/std_map/Makefile b/Examples/python/std_map/Makefile index f406dfaf4..65af5ec82 100644 --- a/Examples/python/std_map/Makefile +++ b/Examples/python/std_map/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/std_vector/Makefile b/Examples/python/std_vector/Makefile index f406dfaf4..65af5ec82 100644 --- a/Examples/python/std_vector/Makefile +++ b/Examples/python/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/template/Makefile b/Examples/python/template/Makefile index f406dfaf4..65af5ec82 100644 --- a/Examples/python/template/Makefile +++ b/Examples/python/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: diff --git a/Examples/python/varargs/Makefile b/Examples/python/varargs/Makefile index 8ec6e9cc9..a412cf299 100644 --- a/Examples/python/varargs/Makefile +++ b/Examples/python/varargs/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/python/variables/Makefile b/Examples/python/variables/Makefile index 222916fa1..26bfd946e 100644 --- a/Examples/python/variables/Makefile +++ b/Examples/python/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(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)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: diff --git a/Examples/r/class/Makefile b/Examples/r/class/Makefile index 3e5d6a6ca..6b4b306f3 100644 --- a/Examples/r/class/Makefile +++ b/Examples/r/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' r_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r_cpp clean: diff --git a/Examples/r/simple/Makefile b/Examples/r/simple/Makefile index 5cc41530c..add881898 100644 --- a/Examples/r/simple/Makefile +++ b/Examples/r/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' r_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r clean: diff --git a/Examples/ruby/class/Makefile b/Examples/ruby/class/Makefile index 516f842d7..0d469c655 100644 --- a/Examples/ruby/class/Makefile +++ b/Examples/ruby/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/constants/Makefile b/Examples/ruby/constants/Makefile index 561d5fd84..24698f2b4 100644 --- a/Examples/ruby/constants/Makefile +++ b/Examples/ruby/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/enum/Makefile b/Examples/ruby/enum/Makefile index 516f842d7..0d469c655 100644 --- a/Examples/ruby/enum/Makefile +++ b/Examples/ruby/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/exception_class/Makefile b/Examples/ruby/exception_class/Makefile index 6723a2a7c..2d4518e11 100644 --- a/Examples/ruby/exception_class/Makefile +++ b/Examples/ruby/exception_class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/free_function/Makefile b/Examples/ruby/free_function/Makefile index 516f842d7..0d469c655 100644 --- a/Examples/ruby/free_function/Makefile +++ b/Examples/ruby/free_function/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/funcptr/Makefile b/Examples/ruby/funcptr/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/funcptr/Makefile +++ b/Examples/ruby/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 = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/funcptr2/Makefile b/Examples/ruby/funcptr2/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/funcptr2/Makefile +++ b/Examples/ruby/funcptr2/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/functor/Makefile b/Examples/ruby/functor/Makefile index 348bd66e3..c7f998c14 100644 --- a/Examples/ruby/functor/Makefile +++ b/Examples/ruby/functor/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = example INTERFACE = example.i LIBS = -lm @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/hashargs/Makefile b/Examples/ruby/hashargs/Makefile index 59a36c0dd..2d0d943e1 100644 --- a/Examples/ruby/hashargs/Makefile +++ b/Examples/ruby/hashargs/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/import/Makefile b/Examples/ruby/import/Makefile index b5d06bdd7..586e48870 100644 --- a/Examples/ruby/import/Makefile +++ b/Examples/ruby/import/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/import_template/Makefile b/Examples/ruby/import_template/Makefile index b5d06bdd7..586e48870 100644 --- a/Examples/ruby/import_template/Makefile +++ b/Examples/ruby/import_template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/java/Makefile b/Examples/ruby/java/Makefile index 7d611abd2..bec5e1844 100644 --- a/Examples/ruby/java/Makefile +++ b/Examples/ruby/java/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ CXXSHARED="gcj -fpic -shared Example.class" LIBS="-lstdc++" DEFS='' ruby_cpp diff --git a/Examples/ruby/mark_function/Makefile b/Examples/ruby/mark_function/Makefile index 516f842d7..0d469c655 100644 --- a/Examples/ruby/mark_function/Makefile +++ b/Examples/ruby/mark_function/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/mark_function/runme.rb b/Examples/ruby/mark_function/runme.rb index 6d84ee88f..a7c5b042e 100644 --- a/Examples/ruby/mark_function/runme.rb +++ b/Examples/ruby/mark_function/runme.rb @@ -9,7 +9,7 @@ begin zoo.add_animal(tiger1) # unset variables to force gc - tiger = nil + tiger1 = nil end GC.start @@ -20,4 +20,4 @@ tiger2 = zoo.get_animal(0) # Call a method to verify the animal is still valid and not gc'ed if tiger2.get_name != "tiger1" raise RuntimeError, "Wrong animal name" -end +end diff --git a/Examples/ruby/multimap/Makefile b/Examples/ruby/multimap/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/multimap/Makefile +++ b/Examples/ruby/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/operator/Makefile b/Examples/ruby/operator/Makefile index bdcf52646..53241eead 100644 --- a/Examples/ruby/operator/Makefile +++ b/Examples/ruby/operator/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/overloading/Makefile b/Examples/ruby/overloading/Makefile index 516f842d7..0d469c655 100644 --- a/Examples/ruby/overloading/Makefile +++ b/Examples/ruby/overloading/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/pointer/Makefile b/Examples/ruby/pointer/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/pointer/Makefile +++ b/Examples/ruby/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/reference/Makefile b/Examples/ruby/reference/Makefile index 516f842d7..0d469c655 100644 --- a/Examples/ruby/reference/Makefile +++ b/Examples/ruby/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/simple/Makefile b/Examples/ruby/simple/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/simple/Makefile +++ b/Examples/ruby/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/std_vector/Makefile b/Examples/ruby/std_vector/Makefile index 370bd8fb6..636a0f19f 100644 --- a/Examples/ruby/std_vector/Makefile +++ b/Examples/ruby/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/template/Makefile b/Examples/ruby/template/Makefile index 370bd8fb6..636a0f19f 100644 --- a/Examples/ruby/template/Makefile +++ b/Examples/ruby/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: diff --git a/Examples/ruby/value/Makefile b/Examples/ruby/value/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/value/Makefile +++ b/Examples/ruby/value/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/ruby/variables/Makefile b/Examples/ruby/variables/Makefile index 15b39cf0d..d320c9a83 100644 --- a/Examples/ruby/variables/Makefile +++ b/Examples/ruby/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,11 +9,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(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)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: diff --git a/Examples/s-exp/uffi.lisp b/Examples/s-exp/uffi.lisp index 253f85aba..aea9a1405 100644 --- a/Examples/s-exp/uffi.lisp +++ b/Examples/s-exp/uffi.lisp @@ -15,7 +15,7 @@ (defvar *swig-source-directory* #p"/home/mkoeppe/s/swig1.3/") -(defvar *swig-program* (merge-pathnames "preinst-swig" *swig-source-directory*)) +(defvar *swig-program* (merge-pathnames "swig" *swig-source-directory*)) (defun run-swig (swig-interface-file-name &key directory-search-list module ignore-errors c++) diff --git a/Examples/scilab/class/Makefile b/Examples/scilab/class/Makefile index b0545d804..40c97a5f7 100644 --- a/Examples/scilab/class/Makefile +++ b/Examples/scilab/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp clean: diff --git a/Examples/scilab/constants/Makefile b/Examples/scilab/constants/Makefile index 56e51e6f5..d47674b37 100644 --- a/Examples/scilab/constants/Makefile +++ b/Examples/scilab/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/contract/Makefile b/Examples/scilab/contract/Makefile index 208a88bfe..6604d191b 100644 --- a/Examples/scilab/contract/Makefile +++ b/Examples/scilab/contract/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/enum/Makefile b/Examples/scilab/enum/Makefile index b0545d804..40c97a5f7 100644 --- a/Examples/scilab/enum/Makefile +++ b/Examples/scilab/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp clean: diff --git a/Examples/scilab/funcptr/Makefile b/Examples/scilab/funcptr/Makefile index 208a88bfe..6604d191b 100644 --- a/Examples/scilab/funcptr/Makefile +++ b/Examples/scilab/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 = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/matrix/Makefile b/Examples/scilab/matrix/Makefile index 208a88bfe..6604d191b 100644 --- a/Examples/scilab/matrix/Makefile +++ b/Examples/scilab/matrix/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/matrix2/Makefile b/Examples/scilab/matrix2/Makefile index 208a88bfe..6604d191b 100644 --- a/Examples/scilab/matrix2/Makefile +++ b/Examples/scilab/matrix2/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/pointer/Makefile b/Examples/scilab/pointer/Makefile index 92308c312..9ce2685bf 100644 --- a/Examples/scilab/pointer/Makefile +++ b/Examples/scilab/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/simple/Makefile b/Examples/scilab/simple/Makefile index 208a88bfe..6604d191b 100644 --- a/Examples/scilab/simple/Makefile +++ b/Examples/scilab/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/std_list/Makefile b/Examples/scilab/std_list/Makefile index b0545d804..40c97a5f7 100644 --- a/Examples/scilab/std_list/Makefile +++ b/Examples/scilab/std_list/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp clean: diff --git a/Examples/scilab/std_vector/Makefile b/Examples/scilab/std_vector/Makefile index f73144d78..490ac73b5 100644 --- a/Examples/scilab/std_vector/Makefile +++ b/Examples/scilab/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp clean: diff --git a/Examples/scilab/struct/Makefile b/Examples/scilab/struct/Makefile index 7a030a33c..9f8b7e891 100644 --- a/Examples/scilab/struct/Makefile +++ b/Examples/scilab/struct/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/scilab/template/Makefile b/Examples/scilab/template/Makefile index f73144d78..490ac73b5 100644 --- a/Examples/scilab/template/Makefile +++ b/Examples/scilab/template/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp clean: diff --git a/Examples/scilab/variables/Makefile b/Examples/scilab/variables/Makefile index 208a88bfe..6604d191b 100644 --- a/Examples/scilab/variables/Makefile +++ b/Examples/scilab/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = example INTERFACE = example.i @@ -8,7 +9,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab clean: diff --git a/Examples/tcl/class/Makefile b/Examples/tcl/class/Makefile index aacf30e04..3fd77cff5 100644 --- a/Examples/tcl/class/Makefile +++ b/Examples/tcl/class/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: diff --git a/Examples/tcl/constants/Makefile b/Examples/tcl/constants/Makefile index 17c8afa3f..67f6567a8 100644 --- a/Examples/tcl/constants/Makefile +++ b/Examples/tcl/constants/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/tcl/contract/Makefile b/Examples/tcl/contract/Makefile index 01fdc37b3..bab90552b 100644 --- a/Examples/tcl/contract/Makefile +++ b/Examples/tcl/contract/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my_tclsh DLTARGET = example @@ -10,12 +11,14 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/enum/Makefile b/Examples/tcl/enum/Makefile index aacf30e04..3fd77cff5 100644 --- a/Examples/tcl/enum/Makefile +++ b/Examples/tcl/enum/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: diff --git a/Examples/tcl/funcptr/Makefile b/Examples/tcl/funcptr/Makefile index 7155bf3c3..8765f7ef9 100644 --- a/Examples/tcl/funcptr/Makefile +++ b/Examples/tcl/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 = example.c TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/tcl/import/Makefile b/Examples/tcl/import/Makefile index 6aa48e7a8..64ef0cdd1 100644 --- a/Examples/tcl/import/Makefile +++ b/Examples/tcl/import/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = @@ -7,14 +8,18 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' tcl_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' tcl_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' tcl_cpp - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' tcl_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' tcl_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' tcl_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' tcl_cpp + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' tcl_cpp clean: diff --git a/Examples/tcl/java/Makefile b/Examples/tcl/java/Makefile index 4be3764e2..e4dfc536b 100644 --- a/Examples/tcl/java/Makefile +++ b/Examples/tcl/java/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,7 +10,8 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ TCLCXXSHARED="gcj -fpic -shared Example.class " LIBS="-lstdc++" DEFS='' tcl_cpp diff --git a/Examples/tcl/multimap/Makefile b/Examples/tcl/multimap/Makefile index 7155bf3c3..8765f7ef9 100644 --- a/Examples/tcl/multimap/Makefile +++ b/Examples/tcl/multimap/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/tcl/operator/Makefile b/Examples/tcl/operator/Makefile index 1c6e1be98..73dca485a 100644 --- a/Examples/tcl/operator/Makefile +++ b/Examples/tcl/operator/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: diff --git a/Examples/tcl/pointer/Makefile b/Examples/tcl/pointer/Makefile index 7155bf3c3..8765f7ef9 100644 --- a/Examples/tcl/pointer/Makefile +++ b/Examples/tcl/pointer/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/tcl/reference/Makefile b/Examples/tcl/reference/Makefile index aacf30e04..3fd77cff5 100644 --- a/Examples/tcl/reference/Makefile +++ b/Examples/tcl/reference/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = example.cxx TARGET = example INTERFACE = example.i @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: diff --git a/Examples/tcl/simple/Makefile b/Examples/tcl/simple/Makefile index 7155bf3c3..8765f7ef9 100644 --- a/Examples/tcl/simple/Makefile +++ b/Examples/tcl/simple/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/tcl/std_vector/Makefile b/Examples/tcl/std_vector/Makefile index f29f933ba..3ed97f27c 100644 --- a/Examples/tcl/std_vector/Makefile +++ b/Examples/tcl/std_vector/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = my_tclsh DLTARGET = example @@ -10,11 +11,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: diff --git a/Examples/tcl/value/Makefile b/Examples/tcl/value/Makefile index 7155bf3c3..8765f7ef9 100644 --- a/Examples/tcl/value/Makefile +++ b/Examples/tcl/value/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/tcl/variables/Makefile b/Examples/tcl/variables/Makefile index 7155bf3c3..8765f7ef9 100644 --- a/Examples/tcl/variables/Makefile +++ b/Examples/tcl/variables/Makefile @@ -1,5 +1,6 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = example.c TARGET = my_tclsh DLTARGET = example @@ -9,11 +10,13 @@ check: build $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_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)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(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)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: diff --git a/Examples/test-suite/allegrocl/Makefile.in b/Examples/test-suite/allegrocl/Makefile.in index 02ef8e302..b13d546da 100644 --- a/Examples/test-suite/allegrocl/Makefile.in +++ b/Examples/test-suite/allegrocl/Makefile.in @@ -35,7 +35,7 @@ CPP_TEST_BROKEN_ACL = \ dynamic_cast \ extend_variable \ # cdata.i support needed \ - li_cdata \ + li_cdata_cpp \ # warning generated. otherwise all good. \ operator_overload \ # std_common.i support \ diff --git a/Examples/test-suite/apply_strings.i b/Examples/test-suite/apply_strings.i index 62b578bf2..695dd068f 100644 --- a/Examples/test-suite/apply_strings.i +++ b/Examples/test-suite/apply_strings.i @@ -68,6 +68,10 @@ TAscii *DigitsGlobalC; // Director test %feature("director"); +#if defined(SWIGGO) +%typemap(godirectorout) CharPtr, CCharPtr "" +#endif + %inline %{ struct DirectorTest { virtual UCharPtr UCharFunction(UCharPtr str) { return str; } diff --git a/Examples/test-suite/array_typedef_memberin.i b/Examples/test-suite/array_typedef_memberin.i index 3618c9305..ad2855eed 100644 --- a/Examples/test-suite/array_typedef_memberin.i +++ b/Examples/test-suite/array_typedef_memberin.i @@ -5,6 +5,10 @@ #endif %inline %{ +#if defined(_MSC_VER) + #pragma warning(disable: 4351) // new behavior: elements of array 'xyz' will be default initialized +#endif + typedef short Eight[8]; typedef const short ConstEight[8]; namespace ArrayExample diff --git a/Examples/test-suite/autodoc.i b/Examples/test-suite/autodoc.i index d85899756..a2d9f5b4e 100644 --- a/Examples/test-suite/autodoc.i +++ b/Examples/test-suite/autodoc.i @@ -1,4 +1,4 @@ -%module(docstring="hello") autodoc +%module(docstring="hello.") autodoc %feature("autodoc"); @@ -27,7 +27,7 @@ %feature("autodoc","2") A::variable_c; // extended %feature("autodoc","3") A::variable_d; // extended + types -%feature("autodoc","just a string") A::funk; // names +%feature("autodoc","just a string.") A::funk; // names %inline { diff --git a/Examples/test-suite/callback.i b/Examples/test-suite/callback.i index 8e28dad06..4db63353b 100644 --- a/Examples/test-suite/callback.i +++ b/Examples/test-suite/callback.i @@ -1,10 +1,18 @@ %module callback +// Not specifying the callback name is only possible in Python. +#ifdef SWIGPYTHON %callback(1) foo; %callback(1) foof; %callback(1) A::bar; %callback(1) A::foom; -%callback("%s_Cb_Ptr") foo_T; // old style, still works. +#else +%callback("%s") foo; +%callback("%s") foof; +%callback("%s") A::bar; +%callback("%s") A::foom; +#endif +%callback("%(uppercase)s_Cb_Ptr") foo_T; // this works in Python too %inline %{ diff --git a/Examples/test-suite/cffi/Makefile.in b/Examples/test-suite/cffi/Makefile.in index ee7e3f61e..6eebaa07c 100644 --- a/Examples/test-suite/cffi/Makefile.in +++ b/Examples/test-suite/cffi/Makefile.in @@ -48,4 +48,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" cffi_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' cffi_clean diff --git a/Examples/test-suite/char_binary.i b/Examples/test-suite/char_binary.i index 778792946..394565438 100644 --- a/Examples/test-suite/char_binary.i +++ b/Examples/test-suite/char_binary.i @@ -5,12 +5,16 @@ A test case for testing non null terminated char pointers. %module char_binary %apply (char *STRING, size_t LENGTH) { (const char *str, size_t len) } +%apply (char *STRING, size_t LENGTH) { (const unsigned char *str, size_t len) } %inline %{ struct Test { size_t strlen(const char *str, size_t len) { return len; } + size_t ustrlen(const unsigned char *str, size_t len) { + return len; + } }; typedef char namet[5]; diff --git a/Examples/test-suite/char_constant.i b/Examples/test-suite/char_constant.i index 5235b0581..918456192 100644 --- a/Examples/test-suite/char_constant.i +++ b/Examples/test-suite/char_constant.i @@ -12,6 +12,36 @@ #define ESC_CONST '\1' #define NULL_CONST '\0' #define SPECIALCHAR 'á' +#define SPECIALCHAR2 '\n' +#define SPECIALCHARA 'A' +#define SPECIALCHARB '\102' // B +#define SPECIALCHARC '\x43' // C +#define SPECIALCHARD 0x44 // D +#define SPECIALCHARE 69 // E +#define SPECIALCHARAE1 'Æ' // AE (latin1 encoded) +#define SPECIALCHARAE2 '\306' // AE (latin1 encoded) +#define SPECIALCHARAE3 '\xC6' // AE (latin1 encoded) + +#if defined(SWIGJAVA) +%javaconst(1); +#elif SWIGCSHARP +%csconst(1); +#elif SWIGD +%dmanifestconst; +#endif + +#define X_ESC_CONST '\1' +#define X_NULL_CONST '\0' +#define X_SPECIALCHAR 'á' +#define X_SPECIALCHAR2 '\n' +#define X_SPECIALCHARA 'A' +#define X_SPECIALCHARB '\102' // B +#define X_SPECIALCHARC '\x43' // C +#define X_SPECIALCHARD 0x44 // D +#define X_SPECIALCHARE 69 // E +#define X_SPECIALCHARAE1 'Æ' // AE (latin1 encoded) +#define X_SPECIALCHARAE2 '\306' // AE (latin1 encoded) +#define X_SPECIALCHARAE3 '\xC6' // AE (latin1 encoded) %inline { diff --git a/Examples/test-suite/chartest.i b/Examples/test-suite/chartest.i index e81cf54a4..1046fa4d1 100644 --- a/Examples/test-suite/chartest.i +++ b/Examples/test-suite/chartest.i @@ -1,6 +1,11 @@ %module chartest %inline %{ +#if defined(__clang__) +#pragma clang diagnostic push +// Suppress: illegal character encoding in character literal +#pragma clang diagnostic ignored "-Winvalid-source-encoding" +#endif char printable_global_char = 'a'; char unprintable_global_char = 0x7F; @@ -12,4 +17,68 @@ char GetUnprintableChar() { return 0x7F; } +static const char globchar0 = '\0'; +static const char globchar1 = '\1'; +static const char globchar2 = '\n'; +static const char globcharA = 'A'; +static const char globcharB = '\102'; // B +static const char globcharC = '\x43'; // C +static const char globcharD = 0x44; // D +static const char globcharE = 69; // E +static const char globcharAE1 = 'Æ'; // AE (latin1 encoded) +static const char globcharAE2 = '\306'; // AE (latin1 encoded) +static const char globcharAE3 = '\xC6'; // AE (latin1 encoded) + +struct CharTestClass { + static const char memberchar0 = '\0'; + static const char memberchar1 = '\1'; + static const char memberchar2 = '\n'; + static const char membercharA = 'A'; + static const char membercharB = '\102'; // B + static const char membercharC = '\x43'; // C + static const char membercharD = 0x44; // D + static const char membercharE = 69; // E + static const char membercharAE1 = 'Æ'; // AE (latin1 encoded) + static const char membercharAE2 = '\306'; // AE (latin1 encoded) + static const char membercharAE3 = '\xC6'; // AE (latin1 encoded) +}; +%} + +#if defined(SWIGJAVA) +%javaconst(1); +#elif SWIGCSHARP +%csconst(1); +#elif SWIGD +%dmanifestconst; +#endif + +%inline %{ +static const char x_globchar0 = '\0'; +static const char x_globchar1 = '\1'; +static const char x_globchar2 = '\n'; +static const char x_globcharA = 'A'; +static const char x_globcharB = '\102'; // B +static const char x_globcharC = '\x43'; // C +static const char x_globcharD = 0x44; // D +static const char x_globcharE = 69; // E +static const char x_globcharAE1 = 'Æ'; // AE (latin1 encoded) +static const char x_globcharAE2 = '\306'; // AE (latin1 encoded) +static const char x_globcharAE3 = '\xC6'; // AE (latin1 encoded) + +struct X_CharTestClass { + static const char memberchar0 = '\0'; + static const char memberchar1 = '\1'; + static const char memberchar2 = '\n'; + static const char membercharA = 'A'; + static const char membercharB = '\102'; // B + static const char membercharC = '\x43'; // C + static const char membercharD = 0x44; // D + static const char membercharE = 69; // E + static const char membercharAE1 = 'Æ'; // AE (latin1 encoded) + static const char membercharAE2 = '\306'; // AE (latin1 encoded) + static const char membercharAE3 = '\xC6'; // AE (latin1 encoded) +}; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif %} diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in index 31ab311bb..b3dccc9c3 100644 --- a/Examples/test-suite/chicken/Makefile.in +++ b/Examples/test-suite/chicken/Makefile.in @@ -97,5 +97,5 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" chicken_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' chicken_clean rm -f *.scm diff --git a/Examples/test-suite/chicken/overload_extend_c_runme.ss b/Examples/test-suite/chicken/overload_extend_c_runme.ss new file mode 100644 index 000000000..75c0ea8a8 --- /dev/null +++ b/Examples/test-suite/chicken/overload_extend_c_runme.ss @@ -0,0 +1,2 @@ +(load "overload_extend_c.so") +(include "../schemerunme/overload_extend_c.scm") diff --git a/Examples/test-suite/clisp/Makefile.in b/Examples/test-suite/clisp/Makefile.in index 6837ed60b..3d207178f 100644 --- a/Examples/test-suite/clisp/Makefile.in +++ b/Examples/test-suite/clisp/Makefile.in @@ -48,4 +48,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" clisp_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' clisp_clean diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index ac726ef05..c8670801c 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -33,9 +33,7 @@ # can be used for memory checking of the runtime tests using: # make RUNTOOL="valgrind --leak-check=full" # and valgrind can be used when invoking SWIG using: -# make SWIGTOOL="valgrind --tool=memcheck --trace-children=yes" -# Note: trace-children needed because of preinst-swig shell wrapper -# to the swig executable. +# make SWIGTOOL="valgrind --tool=memcheck" # # An individual test run can be debugged easily: # make director_string.cpptest RUNTOOL="gdb --args" @@ -56,8 +54,8 @@ endif COMPILETOOL= SWIGTOOL = -SWIG = $(SWIGTOOL) $(top_builddir)/preinst-swig -SWIG_LIB = $(top_srcdir)/Lib +SWIGEXE = $(top_builddir)/swig +SWIG_LIB_DIR = $(top_srcdir)/Lib TEST_SUITE = test-suite EXAMPLES = Examples CXXSRCS = @@ -89,7 +87,6 @@ CPP_TEST_BROKEN += \ director_nested_class \ exception_partial_info \ extend_variable \ - li_std_vector_ptr \ li_boost_shared_ptr_template \ nested_private \ overload_complicated \ @@ -176,7 +173,6 @@ CPP_TEST_CASES += \ director_abstract \ director_alternating \ director_basic \ - director_property \ director_binary_string \ director_classes \ director_classic \ @@ -191,12 +187,14 @@ CPP_TEST_CASES += \ director_ignore \ director_keywords \ director_namespace_clash \ + director_nested \ director_nspace \ director_nspace_director_name_collision \ - director_nested \ director_overload \ director_overload2 \ + director_pass_by_value \ director_primitives \ + director_property \ director_protected \ director_protected_overloaded \ director_redefined \ @@ -205,6 +203,7 @@ CPP_TEST_CASES += \ director_thread \ director_unroll \ director_using \ + director_void \ director_wombat \ disown \ dynamic_cast \ @@ -220,6 +219,7 @@ CPP_TEST_CASES += \ evil_diamond \ evil_diamond_ns \ evil_diamond_prop \ + exception_classname \ exception_order \ extend \ extend_constructor_destructor \ @@ -264,9 +264,9 @@ CPP_TEST_CASES += \ li_boost_shared_ptr_bits \ li_boost_shared_ptr_template \ li_boost_shared_ptr_attribute \ - li_carrays \ - li_cdata \ - li_cpointer \ + li_carrays_cpp \ + li_cdata_cpp \ + li_cpointer_cpp \ li_std_auto_ptr \ li_stdint \ li_swigtype_inout \ @@ -282,6 +282,10 @@ CPP_TEST_CASES += \ minherit2 \ mixed_types \ multiple_inheritance \ + multiple_inheritance_abstract \ + multiple_inheritance_interfaces \ + multiple_inheritance_nspace \ + multiple_inheritance_shared_ptr \ name_cxx \ name_warnings \ namespace_class \ @@ -303,6 +307,7 @@ CPP_TEST_CASES += \ nested_class \ nested_directors \ nested_comment \ + nested_ignore \ nested_scope \ nested_template_base \ nested_workaround \ @@ -341,12 +346,14 @@ CPP_TEST_CASES += \ rename2 \ rename3 \ rename4 \ + rename_rstrip_encoder \ rename_scope \ rename_simple \ rename_strip_encoder \ rename_pcre_encoder \ rename_pcre_enum \ rename_predicates \ + rename_wildcard \ restrict_cplusplus \ return_const_value \ return_value_scope \ @@ -357,6 +364,7 @@ CPP_TEST_CASES += \ smart_pointer_const2 \ smart_pointer_const_overload \ smart_pointer_extend \ + smart_pointer_ignore \ smart_pointer_member \ smart_pointer_multi \ smart_pointer_multi_typedef \ @@ -374,12 +382,15 @@ CPP_TEST_CASES += \ smart_pointer_templatevariables \ smart_pointer_typedef \ special_variables \ + special_variable_attributes \ special_variable_macros \ static_array_member \ static_const_member \ static_const_member_2 \ + string_constants \ struct_initialization_cpp \ struct_value \ + swig_exception \ symbol_clash \ template_arg_replace \ template_arg_scope \ @@ -394,6 +405,8 @@ CPP_TEST_CASES += \ template_default \ template_default2 \ template_default_arg \ + template_default_arg_overloaded \ + template_default_arg_overloaded_extend \ template_default_arg_virtual_destructor \ template_default_class_parms \ template_default_class_parms_typedef \ @@ -469,12 +482,13 @@ CPP_TEST_CASES += \ typedef_reference \ typedef_scope \ typedef_sizet \ - typedef_struct \ + typedef_struct_cpp \ typedef_typedef \ typemap_arrays \ typemap_array_qualifiers \ typemap_delete \ typemap_directorout \ + typemap_documentation \ typemap_global_scope \ typemap_manyargs \ typemap_namespace \ @@ -508,6 +522,7 @@ CPP_TEST_CASES += \ valuewrapper_opaque \ varargs \ varargs_overload \ + variable_replacement \ virtual_destructor \ virtual_poly \ virtual_vs_nonvirtual_base \ @@ -531,6 +546,7 @@ CPP11_TEST_CASES = \ cpp11_initializer_list \ cpp11_initializer_list_extend \ cpp11_lambda_functions \ + cpp11_li_std_array \ cpp11_noexcept \ cpp11_null_pointer_constant \ cpp11_raw_string_literals \ @@ -597,7 +613,7 @@ CPP_STD_TEST_CASES += \ li_std_vector \ li_std_vector_enum \ li_std_vector_member_var\ - naturalvar \ + li_std_vector_ptr \ smart_pointer_inherit \ template_typedef_fnc \ template_type_namespace \ @@ -622,7 +638,7 @@ C_TEST_CASES += \ char_constant \ const_const \ constant_expr \ - empty \ + empty_c \ enums \ enum_forward \ enum_macro \ @@ -635,7 +651,7 @@ C_TEST_CASES += \ inctest \ infinity \ integers \ - keyword_rename \ + keyword_rename_c \ lextype \ li_carrays \ li_cdata \ @@ -650,8 +666,8 @@ C_TEST_CASES += \ nested_extend_c \ nested_structs \ newobject2 \ - overload_extend \ - overload_extendc \ + overload_extend_c \ + overload_extend2 \ preproc \ preproc_constants_c \ preproc_defined \ @@ -684,6 +700,11 @@ MULTI_CPP_TEST_CASES += \ wallkw.cpptest: SWIGOPT += -Wallkw preproc_include.ctest: SWIGOPT += -includeall +# Allow modules to define temporarily failing tests. +C_TEST_CASES := $(filter-out $(FAILING_C_TESTS),$(C_TEST_CASES)) +CPP_TEST_CASES := $(filter-out $(FAILING_CPP_TESTS),$(CPP_TEST_CASES)) +MULTI_CPP_TEST_CASES := $(filter-out $(FAILING_MULTI_CPP_TESTS),$(MULTI_CPP_TEST_CASES)) + NOT_BROKEN_TEST_CASES = $(CPP_TEST_CASES:=.cpptest) \ $(C_TEST_CASES:=.ctest) \ @@ -714,6 +735,7 @@ all: $(NOT_BROKEN_TEST_CASES) $(BROKEN_TEST_CASES) broken: $(BROKEN_TEST_CASES) check: $(NOT_BROKEN_TEST_CASES) + @echo $(words $^) $(LANGUAGE) tests passed check-c: $(C_TEST_CASES:=.ctest) @@ -725,6 +747,13 @@ ifdef HAS_DOXYGEN check-doxygen: $(DOXYGEN_TEST_CASES:=.cpptest) endif +check-failing-test = \ + $(MAKE) -s $1.$2 >/dev/null 2>/dev/null && echo "Failing test $1 passed." + +check-failing: + +-$(foreach t,$(FAILING_C_TESTS),$(call check-failing-test,$t,ctest);) + +-$(foreach t,$(FAILING_CPP_TESTS),$(call check-failing-test,$t,cpptest);) + +-$(foreach t,$(FAILING_MULTI_CPP_TESTS),$(call check-failing-test,$t,multicpptest);) endif # partialcheck target runs SWIG only, ie no compilation or running of tests (for a subset of languages) @@ -732,37 +761,37 @@ partialcheck: $(MAKE) check CC=true CXX=true LDSHARED=true CXXSHARED=true RUNTOOL=true COMPILETOOL=true swig_and_compile_cpp = \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET='$(TARGETPREFIX)$*$(TARGETSUFFIX)' INTERFACEDIR='$(INTERFACEDIR)' INTERFACE='$*.i' \ $(LANGUAGE)$(VARIANT)_cpp swig_and_compile_c = \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CSRCS="$(CSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CSRCS='$(CSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET='$(TARGETPREFIX)$*$(TARGETSUFFIX)' INTERFACEDIR='$(INTERFACEDIR)' INTERFACE='$*.i' \ $(LANGUAGE)$(VARIANT) swig_and_compile_multi_cpp = \ for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$$f.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + LIBS='$(LIBS)' INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR='$(INTERFACEDIR)' INTERFACE="$$f.i" \ $(LANGUAGE)$(VARIANT)_cpp; \ done swig_and_compile_external = \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ - TARGET="$*_wrap_hdr.h" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$*_wrap_hdr.h' \ $(LANGUAGE)$(VARIANT)_externalhdr; \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS) $*_external.cxx" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS) $*_external.cxx' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET='$(TARGETPREFIX)$*$(TARGETSUFFIX)' INTERFACEDIR='$(INTERFACEDIR)' INTERFACE='$*.i' \ $(LANGUAGE)$(VARIANT)_cpp swig_and_compile_runtime = \ diff --git a/Examples/test-suite/compactdefaultargs.i b/Examples/test-suite/compactdefaultargs.i index b2b07c5f8..af96fbe23 100644 --- a/Examples/test-suite/compactdefaultargs.i +++ b/Examples/test-suite/compactdefaultargs.i @@ -30,6 +30,7 @@ public: static const double PUBLIC_DEFAULT; Defaults2(int a = PRIVATE_DEFAULT) {} double ret(double d = PUBLIC_DEFAULT) { return d; } + double nodefault(int x) { return x; } }; %} diff --git a/Examples/test-suite/constant_directive.i b/Examples/test-suite/constant_directive.i index 8204720d6..89f13cecc 100644 --- a/Examples/test-suite/constant_directive.i +++ b/Examples/test-suite/constant_directive.i @@ -1,28 +1,44 @@ %module constant_directive // %constant and struct + +%inline %{ +#if defined(_MSC_VER) + #pragma warning(disable : 4190) // warning C4190: 'result' has C-linkage specified, but returns UDT 'Type1' which is incompatible with C +#endif +struct Type1 { + Type1(int val = 0) : val(val) {} + int val; +}; +/* Typedefs for const Type and its pointer */ +typedef const Type1 Type1Const; +typedef const Type1* Type1Cptr; + +/* Typedefs for function pointers returning Type1 */ +typedef Type1 (*Type1Fptr)(); +typedef Type1 (* const Type1Cfptr)(); + +/* Function returning an instance of Type1 */ +Type1 getType1Instance() { return Type1(111); } +%} + %{ - struct Type1 { - Type1(int val = 0) : val(val) {} - int val; - }; static Type1 TYPE1_CONSTANT1(1); static Type1 TYPE1_CONST2(2); static Type1 TYPE1_CONST3(3); %} -struct Type1 { - Type1(int val = 0) : val(val) {} - int val; -}; - -%inline %{ -Type1 getType1Instance() { return Type1(111); } -%} - %constant Type1 TYPE1_CONSTANT1; %constant Type1 TYPE1_CONSTANT2 = TYPE1_CONST2; %constant Type1 *TYPE1_CONSTANT3 = &TYPE1_CONST3; - +/* Typedef'ed types */ +%constant Type1Const* TYPE1CONST_CONSTANT1 = &TYPE1_CONSTANT1; +%constant Type1Cptr TYPE1CPTR_CONSTANT1 = &TYPE1_CONSTANT1; +/* Function pointers */ +%constant Type1 (*TYPE1FPTR1_CONSTANT1)() = getType1Instance; +%constant Type1 (* const TYPE1CFPTR1_CONSTANT1)() = getType1Instance; +/* Typedef'ed function pointers */ +%constant Type1Fptr TYPE1FPTR1DEF_CONSTANT1 = getType1Instance; +%constant Type1Cfptr TYPE1CFPTR1DEF_CONSTANT1 = getType1Instance; +/* Regular constant */ %constant int TYPE_INT = 0; - diff --git a/Examples/test-suite/cpp11_li_std_array.i b/Examples/test-suite/cpp11_li_std_array.i new file mode 100644 index 000000000..dedd6483a --- /dev/null +++ b/Examples/test-suite/cpp11_li_std_array.i @@ -0,0 +1,62 @@ +%module cpp11_li_std_array + +#if defined(SWIGPYTHON) || defined(SWIGRUBY) || defined(SWIGJAVA) || defined(SWIGCSHARP) + +%{ +#include +%} + +%include + +%template(ArrayInt6) std::array; + +%inline %{ +std::array arrayOutVal() { + return { -2, -1, 0, 0, 1, 2 }; +} + +std::array & arrayOutRef() { + static std::array a = { -2, -1, 0, 0, 1, 2 }; + return a; +} + +const std::array & arrayOutConstRef() { + static std::array a = { -2, -1, 0, 0, 1, 2 }; + return a; +} + +std::array * arrayOutPtr() { + static std::array a = { -2, -1, 0, 0, 1, 2 }; + return &a; +} + +std::array arrayInVal(std::array myarray) { + std::array a = myarray; + for (auto& val : a) { + val *= 10; + } + return a; +} + +const std::array & arrayInConstRef(const std::array & myarray) { + static std::array a = myarray; + for (auto& val : a) { + val *= 10; + } + return a; +} + +void arrayInRef(std::array & myarray) { + for (auto& val : myarray) { + val *= 10; + } +} + +void arrayInPtr(std::array * myarray) { + for (auto& val : *myarray) { + val *= 10; + } +} +%} + +#endif diff --git a/Examples/test-suite/cpp11_strongly_typed_enumerations.i b/Examples/test-suite/cpp11_strongly_typed_enumerations.i index 3a4ee107a..64fdd2b6f 100644 --- a/Examples/test-suite/cpp11_strongly_typed_enumerations.i +++ b/Examples/test-suite/cpp11_strongly_typed_enumerations.i @@ -214,5 +214,12 @@ Enum1 globalTest1(Enum1 e) { return e; } Class1::Enum12 globalTest2(Class1::Enum12 e) { return e; } Class1::Struct1::Enum12 globalTest3(Class1::Struct1::Enum12 e) { return e; } +class PrivateEnumClass { +private: + enum class Enum { + PrivateEnum1, + PrivateEnum2 + }; +}; %} diff --git a/Examples/test-suite/cpp11_template_typedefs.i b/Examples/test-suite/cpp11_template_typedefs.i index 97a1da7ed..02cb8ac30 100644 --- a/Examples/test-suite/cpp11_template_typedefs.i +++ b/Examples/test-suite/cpp11_template_typedefs.i @@ -1,56 +1,86 @@ -/* This testcase checks whether SWIG correctly parses alias templates. */ +/* This testcase checks whether SWIG correctly handles alias templates. */ %module cpp11_template_typedefs -%warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefName; -%warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefNamePtr; -%warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) MyIntKeyClass; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) PF; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) BucketAllocator1; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) BucketAllocator2; - -// This warning should go away when type aliasing is supported -#pragma SWIG nowarn=SWIGWARN_PARSE_USING_UNDEF // Nothing known about 'p.SomeType< char *,T2,4 >'. - %inline %{ -template< typename T1, typename T2, int > + +template +using ptr_t = T*; + +namespace ns { + +template class SomeType { +public: + using type1_t = T1; + using type2_t = T2; T1 a; T2 b; - int c; + constexpr int get_n() { return N; } }; -// template aliasing -template< typename T2 > -using TypedefName = SomeType; -template< typename T2 > -using TypedefNamePtr = SomeType*; - -// type aliasing -typedef void (*PFD)(double); // Old style -using PF = void (*)(double); // New introduced syntax - - -// use of template aliasing -template -class MyCPP11Class { +// Specialization for T1=const char*, T2=bool +template +class SomeType { +public: + using type1_t = const char*; + using type2_t = bool; + type1_t a; + type2_t b; + constexpr int get_n() { return 3 * N; } }; -template using MyIntKeyClass = MyCPP11Class; -MyIntKeyClass intchar; -TypedefName alias1(TypedefName a) { return a; } -TypedefNamePtr alias1(TypedefNamePtr a = nullptr) { return a; } -%} +// alias templates +template +using TypedefName = SomeType; +template +using TypedefNamePtr = ptr_t>; + +// alias template that returns T2 for a SomeType class +template +using T2_of = typename T::type2_t; + +T2_of> get_SomeType_b(const SomeType& x) { return x.b; } + +template +T2_of> get_SomeType_b2(const TypedefName& x) { return x.b; } + +} // namespace ns + +ns::TypedefName create_TypedefName() { return { "hello", 10}; } +ns::TypedefName create_TypedefNameBool() { return { "hello", true}; } +ns::TypedefNamePtr identity(ns::TypedefNamePtr a = nullptr) { return a; } -%inline %{ typedef double Val; template struct ListBucket { }; namespace Alloc { template struct rebind { - typedef int other; + using other = int; }; } using BucketAllocator1 = typename Alloc::template rebind>::other; using BucketAllocator2 = typename Alloc::template rebind<::template ListBucket>::other; + +BucketAllocator1 get_bucket_allocator1() { return 1; } +BucketAllocator2 get_bucket_allocator2() { return 2; } %} + +%immutable ns::SomeType::a; + +// %template() directives + +%template(SomeTypeInt5) ns::SomeType; +%template(SomeTypeInt4) ns::SomeType; +%template(SomeTypeBool5) ns::SomeType; + +%template(ListBucketDouble) ListBucket; +%template(RebindListBucketDouble) Alloc::rebind>; + +%template() ptr_t>; +%template() ns::TypedefName; +%template() ns::TypedefName; +%template() ns::TypedefNamePtr; +%template() ns::T2_of>; + +%template(get_SomeType_b2) ns::get_SomeType_b2; diff --git a/Examples/test-suite/cpp11_type_aliasing.i b/Examples/test-suite/cpp11_type_aliasing.i index 87443633a..2f6ea3aa7 100644 --- a/Examples/test-suite/cpp11_type_aliasing.i +++ b/Examples/test-suite/cpp11_type_aliasing.i @@ -2,15 +2,6 @@ // Type aliasing seg fault : Github issue #424 -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) Target; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) Int; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntRef; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntPtrRef; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntRValueRef; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntArray; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) HalideTargetPtr1; -%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) HalideTargetPtr2; - %inline %{ namespace Halide { @@ -53,14 +44,69 @@ public: %inline %{ -using Int = int; -using IntRef = int&; -using IntPtrRef = int*&; -using IntRValueRef = int&&; -using IntArray = int[]; - using HalideTargetPtr1 = Halide::Target*; namespace Halide { using HalideTargetPtr2 = Target*; } %} + +// Define some types + +%inline %{ +using Int = int; +using IntPtr = Int*; +using IntRef = Int&; +using IntPtrRef = Int*&; +using IntRValueRef = Int&&; +using IntArray = Int[]; +%} + +// Test that SWIG understands these new types + +%callback("%s_cb"); +Int mult2(Int x); +%nocallback; + +%inline %{ +Int mult2(Int x) { return x * 2; } +IntPtr allocate_int() { return new Int(12); } +void free_int(int* ptr) { delete ptr; } +void inplace_mult2(IntRef x) { x *= 2; } +Int read_int(IntPtr ptr) { return *ptr; } + +template class Pair { +public: + using data_t = T; + + data_t a, b; + + Pair() : a(), b() { } + Pair(data_t a, data_t b) : a(a), b(b) { } + data_t first() { return a; } + data_t second() { return b; } +}; +%} + +%template(int_pair) Pair; + +%inline %{ +using PairInt = Pair; + +class PairSubclass : public PairInt { +public: + PairSubclass(data_t a, data_t b) : PairInt(a, b) { } + + using const_ref_data_t = const data_t&; +}; + +PairSubclass::data_t plus1(PairSubclass::const_ref_data_t x) { return x + 1; } +%} + +// Test function pointers + +%inline %{ +using callback_t = int(*)(int); + +callback_t get_callback() { return mult2; } +int call(callback_t func, int param) { return func(param); } +%} diff --git a/Examples/test-suite/cpp_enum.i b/Examples/test-suite/cpp_enum.i index cb212615a..548c65de4 100644 --- a/Examples/test-suite/cpp_enum.i +++ b/Examples/test-suite/cpp_enum.i @@ -6,6 +6,12 @@ The primary purpose of this testcase is to ensure that enums used along with the %inline %{ +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for anonymous enums */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif + enum SOME_ENUM {ENUM_ONE, ENUM_TWO}; struct StructWithEnums { diff --git a/Examples/test-suite/cpp_static.i b/Examples/test-suite/cpp_static.i index c68e986eb..1f8ca1282 100644 --- a/Examples/test-suite/cpp_static.i +++ b/Examples/test-suite/cpp_static.i @@ -22,5 +22,28 @@ public: %} %{ -int StaticMemberTest::static_int; +int StaticMemberTest::static_int = 99; +%} + +%inline %{ +struct StaticBase { + static int statty; + virtual ~StaticBase() {} +}; +struct StaticDerived : StaticBase { + static int statty; +}; +%} + +%{ +int StaticBase::statty = 11; +int StaticDerived::statty = 111; +%} + +%inline %{ +#ifdef SWIGPYTHON_BUILTIN +bool is_python_builtin() { return true; } +#else +bool is_python_builtin() { return false; } +#endif %} diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index d5eac5c03..0c799c7d9 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -73,7 +73,7 @@ setup = \ # Compiles C# files then runs the testcase. A testcase is only run if # a file is found which has _runme.cs appended after the testcase name. # Note C# uses LD_LIBRARY_PATH under Unix, PATH under Cygwin/Windows and SHLIB_PATH on HPUX. -# DYLD_FALLBACK_LIBRARY_PATH is cleared for MacOSX. +# DYLD_FALLBACK_LIBRARY_PATH is cleared for Mac OS X. run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ $(MAKE) -f $*/$(top_builddir)/$(EXAMPLES)/Makefile \ diff --git a/Examples/test-suite/csharp/cpp11_li_std_array_runme.cs b/Examples/test-suite/csharp/cpp11_li_std_array_runme.cs new file mode 100644 index 000000000..d0c956ad3 --- /dev/null +++ b/Examples/test-suite/csharp/cpp11_li_std_array_runme.cs @@ -0,0 +1,82 @@ +// This test tests all the methods in the C# collection wrapper +using System; +using cpp11_li_std_arrayNamespace; + +public class cpp11_li_std_array_runme +{ + private static ArrayInt6 ToArray6(int[] a) + { + if (a.Length != 6) + throw new Exception("a is incorrect size"); + return new ArrayInt6(a); + } + + private static void compareContainers(ArrayInt6 actual, int[] expected) + { + if (actual.Count != expected.Length) + throw new Exception("Sizes are different: " + actual.Count + " " + expected.Length); + for (int i=0; i(types); + return string.Join(" ", types); + } + + static string SortArrayToString(Type[] types) { + List stypes = new List(); + foreach (Type t in types) + stypes.Add(t.Name); + return SortArrayToString(stypes.ToArray()); + } + + + private static void checkBaseAndInterfaces(Type cls, bool interfaceExpected, string baseClass, string[] interfaces) { + string[] expectedInterfaces = new string[interfaces.Length + (interfaceExpected ? 0 : 1)]; + for (int i=0; iFooBarDo(); } + virtual std::string upcall(FooBar* fooBarPtr) { return fooBarPtr->FooBarDo(); } virtual Foo makeFoo() { return Foo(); } virtual FooBar makeFooBar() { return FooBar(); } + static std::string callPong(Foo &foo) { return foo.pong(); } + static std::string callUpcall(Foo &foo, FooBar* fooBarPtr) { return foo.upcall(fooBarPtr); } static Foo* get_self(Foo *self_) {return self_;} }; %} -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) || defined(SWIGOCTAVE) || defined(SWIGRUBY) #define SHARED_PTR_WRAPPERS_IMPLEMENTED #endif @@ -61,10 +63,12 @@ public: virtual ~Foo(); virtual std::string ping(); virtual std::string pong(); - virtual std::string fooBar(FooBar* fooBarPtr); + virtual std::string upcall(FooBar* fooBarPtr); virtual Foo makeFoo(); virtual FooBar makeFooBar(); + static std::string callPong(Foo &foo); + static std::string callUpcall(Foo &foo, FooBar* fooBarPtr); static Foo* get_self(Foo *self_); }; diff --git a/Examples/test-suite/director_void.i b/Examples/test-suite/director_void.i new file mode 100644 index 000000000..40f53b6e2 --- /dev/null +++ b/Examples/test-suite/director_void.i @@ -0,0 +1,47 @@ +%module(directors="1") director_void + +%warnfilter(SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) voidPtrOut; + +%feature("director") DirectorVoidPointer; + +#if defined(SWIGCSHARP) +%apply void *VOID_INT_PTR { void * } +#endif + +%inline %{ +class DirectorVoidPointer { + int *ptr; +public: + DirectorVoidPointer(int val) : ptr(new int(val)) {} + virtual ~DirectorVoidPointer() { delete ptr; } + + virtual void * voidPtrOut() { return ptr; } + virtual int voidPtrIn(void *p) { + return nonVirtualVoidPtrIn(p); + } + + void setNewValue(int val) { + delete ptr; + ptr = new int(val); + } + void *nonVirtualVoidPtrOut() { return ptr; } + int nonVirtualVoidPtrIn(void *p) { + int val = *(int *)p; + setNewValue(val + 100); + return *ptr; + } +}; + +struct Caller { + int callVirtualIn(DirectorVoidPointer *d, int num) { + return d->voidPtrIn(&num); + } + int callVirtualOut(DirectorVoidPointer *d) { + return *(int *)d->voidPtrOut(); + } + static int VoidToInt(void *p) { + return *(int *)p; + } +}; +%} + diff --git a/Examples/test-suite/empty_c.i b/Examples/test-suite/empty_c.i new file mode 100644 index 000000000..f5d27ec19 --- /dev/null +++ b/Examples/test-suite/empty_c.i @@ -0,0 +1 @@ +%module empty_c diff --git a/Examples/test-suite/enum_thorough.i b/Examples/test-suite/enum_thorough.i index 3ece5471b..3beefccc0 100644 --- a/Examples/test-suite/enum_thorough.i +++ b/Examples/test-suite/enum_thorough.i @@ -47,6 +47,12 @@ %inline %{ +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for anonymous enums */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif + enum { AnonEnum1, AnonEnum2 = 100 }; enum { ReallyAnInteger = 200 }; //enum { AnonEnum3, AnonEnum4 } instance; @@ -563,6 +569,17 @@ repeat repeatTest(repeat e) { return e; } } %} +%inline %{ +namespace EnumWithMacro { +#define PACK(C1,C2,C3,C4) ((C1<<24)|(C2<<16)|(C3<<8)|C4) +typedef enum { + ABCD = PACK('A','B','C','D'), + ABCD2 = ABCD +} enumWithMacro; +enumWithMacro enumWithMacroTest(enumWithMacro e) { return e; } +} +%} + %inline %{ namespace DifferentSpace { enum DifferentTypes { @@ -571,7 +588,9 @@ enum DifferentTypes { typebooltrue = true, typebooltwo, typechar = 'C', - typedefaultint + typedefaultint, + typecharcompound='A'+1, + typecharcompound2='B' << 2 }; DifferentTypes differentTypesTest(DifferentTypes n) { return n; } @@ -581,11 +600,68 @@ enum { global_typebooltrue = true, global_typebooltwo, global_typechar = 'C', - global_typedefaultint + global_typedefaultint, + global_typecharcompound='A'+1, + global_typecharcompound2='B' << 2 }; int globalDifferentTypesTest(int n) { return n; } } +%} +#if defined(SWIGCSHARP) +%csconstvalue("1") globalenumchar1; +%csconstvalue("'B'") globalenumcharB; +%csconstvalue("1") enumchar1; +%csconstvalue("'B'") enumcharB; +#endif +%inline %{ +#if defined(__clang__) +#pragma clang diagnostic push +// Suppress: illegal character encoding in character literal +#pragma clang diagnostic ignored "-Winvalid-source-encoding" +#endif + +enum { + globalenumchar0 = '\0', + globalenumchar1 = '\1', + globalenumchar2 = '\n', + globalenumcharA = 'A', + globalenumcharB = '\102', // B + globalenumcharC = '\x43', // C + globalenumcharD = 0x44, // D + globalenumcharE = 69, // E + globalenumcharAE1 = 'Æ', // AE (latin1 encoded) + globalenumcharAE2 = '\306', // AE (latin1 encoded) + globalenumcharAE3 = '\xC6' // AE (latin1 encoded) +}; +enum EnumChar { + enumchar0 = '\0', + enumchar1 = '\1', + enumchar2 = '\n', + enumcharA = 'A', + enumcharB = '\102', // B + enumcharC = '\x43', // C + enumcharD = 0x44, // D + enumcharE = 69, // E + enumcharAE1 = 'Æ', // AE (latin1 encoded) + enumcharAE2 = '\306', // AE (latin1 encoded) + enumcharAE3 = '\xC6' // AE (latin1 encoded) +}; +struct EnumCharStruct { + enum EnumChar { + enumchar0 = '\0', + enumchar1 = '\1', + enumchar2 = '\n', + enumcharA = 'A', + enumcharB = '\102', // B + enumcharC = '\x43', // C + enumcharD = 0x44, // D + enumcharE = 69, // E + enumcharAE1 = 'Æ', // AE (latin1 encoded) + enumcharAE2 = '\306', // AE (latin1 encoded) + enumcharAE3 = '\xC6' // AE (latin1 encoded) + }; +}; %} #if defined(SWIGJAVA) @@ -594,6 +670,53 @@ int globalDifferentTypesTest(int n) { return n; } %csconst(0); #endif +%inline %{ +enum { + x_globalenumchar0 = '\0', + x_globalenumchar1 = '\1', + x_globalenumchar2 = '\n', + x_globalenumcharA = 'A', + x_globalenumcharB = '\102', // B + x_globalenumcharC = '\x43', // C + x_globalenumcharD = 0x44, // D + x_globalenumcharE = 69, // E + x_globalenumcharAE1 = 'Æ', // AE (latin1 encoded) + x_globalenumcharAE2 = '\306', // AE (latin1 encoded) + x_globalenumcharAE3 = '\xC6' // AE (latin1 encoded) +}; +enum X_EnumChar { + x_enumchar0 = '\0', + x_enumchar1 = '\1', + x_enumchar2 = '\n', + x_enumcharA = 'A', + x_enumcharB = '\102', // B + x_enumcharC = '\x43', // C + x_enumcharD = 0x44, // D + x_enumcharE = 69, // E + x_enumcharAE1 = 'Æ', // AE (latin1 encoded) + x_enumcharAE2 = '\306', // AE (latin1 encoded) + x_enumcharAE3 = '\xC6' // AE (latin1 encoded) +}; +struct X_EnumCharStruct { + enum X_EnumChar { + enumchar0 = '\0', + enumchar1 = '\1', + enumchar2 = '\n', + enumcharA = 'A', + enumcharB = '\102', // B + enumcharC = '\x43', // C + enumcharD = 0x44, // D + enumcharE = 69, // E + enumcharAE1 = 'Æ', // AE (latin1 encoded) + enumcharAE2 = '\306', // AE (latin1 encoded) + enumcharAE3 = '\xC6' // AE (latin1 encoded) + }; +}; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif +%} + %inline %{ namespace DifferentSpace { enum DifferentTypesNoConst { @@ -614,5 +737,4 @@ enum { global_typedefaultint_noconst }; } - %} diff --git a/Examples/test-suite/enums.i b/Examples/test-suite/enums.i index 14c6efbba..b8ffd7588 100644 --- a/Examples/test-suite/enums.i +++ b/Examples/test-suite/enums.i @@ -12,6 +12,12 @@ %inline %{ +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for anonymous enums */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif + typedef enum { CSP_ITERATION_FWD, CSP_ITERATION_BWD = 11 diff --git a/Examples/test-suite/errors/.gitignore b/Examples/test-suite/errors/.gitignore deleted file mode 100644 index 22ca11947..000000000 --- a/Examples/test-suite/errors/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.newerr -cpp_recursive_typedef.py -cpp_shared_ptr.py -xxx.py diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index 09f5bc8c7..c66840997 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -20,6 +20,9 @@ srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +SWIG_LIB_SET = @SWIG_LIB_SET@ +SWIGINVOKE = $(SWIG_LIB_SET) $(SWIGTOOL) $(SWIGEXE) + # All .i files with prefix 'cpp_' will be treated as C++ input and remaining .i files as C input ALL_ERROR_TEST_CASES := $(patsubst %.i,%, $(notdir $(wildcard $(srcdir)/*.i))) CPP_ERROR_TEST_CASES := $(filter cpp_%, $(ALL_ERROR_TEST_CASES)) @@ -44,7 +47,7 @@ $(DOXYGEN_ERROR_TEST_CASES): SWIGOPT += -doxygen # Portable dos2unix / todos for stripping CR TODOS = tr -d '\r' -#TODOS = sed -e 's/\r$$//' # On OSX behaves as if written 's/r$$//' +#TODOS = sed -e 's/\r$$//' # On Mac OS X behaves as if written 's/r$$//' # strip source directory from output, so that diffs compare STRIP_SRCDIR = sed -e 's|\\|/|g' -e 's|^$(SRCDIR)||' @@ -52,17 +55,17 @@ STRIP_SRCDIR = sed -e 's|\\|/|g' -e 's|^$(SRCDIR)||' # Rules for the different types of tests %.cpptest: echo "$(ACTION)ing errors testcase $*" - -$(SWIG) -c++ -python -Wall -Fstandard $(SWIGOPT) $(SRCDIR)$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) + -$(SWIGINVOKE) -c++ -python -Wall -Fstandard $(SWIGOPT) $(SRCDIR)$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) $(COMPILETOOL) diff -c $(SRCDIR)$*.stderr $*.$(ERROR_EXT) %.ctest: echo "$(ACTION)ing errors testcase $*" - -$(SWIG) -python -Wall -Fstandard $(SWIGOPT) $(SRCDIR)$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) + -$(SWIGINVOKE) -python -Wall -Fstandard $(SWIGOPT) $(SRCDIR)$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) $(COMPILETOOL) diff -c $(SRCDIR)$*.stderr $*.$(ERROR_EXT) %.clean: @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" python_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' python_clean @rm -f *.$(ERROR_EXT) *.py diff --git a/Examples/test-suite/errors/c_default_error.i b/Examples/test-suite/errors/c_default_error.i deleted file mode 100644 index f6220e11d..000000000 --- a/Examples/test-suite/errors/c_default_error.i +++ /dev/null @@ -1,4 +0,0 @@ -%module xxx - -int foo(int x = 42 || 3); - diff --git a/Examples/test-suite/errors/c_default_error.stderr b/Examples/test-suite/errors/c_default_error.stderr deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/errors/c_varargs.i b/Examples/test-suite/errors/c_varargs.i deleted file mode 100644 index 88f9c2e7d..000000000 --- a/Examples/test-suite/errors/c_varargs.i +++ /dev/null @@ -1,3 +0,0 @@ -%module xxx - -int foo(int x, ...); diff --git a/Examples/test-suite/errors/c_varargs.stderr b/Examples/test-suite/errors/c_varargs.stderr deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/errors/cpp_inherit_ignored.i b/Examples/test-suite/errors/cpp_inherit_ignored.i new file mode 100644 index 000000000..fdc1c83e3 --- /dev/null +++ b/Examples/test-suite/errors/cpp_inherit_ignored.i @@ -0,0 +1,19 @@ +%module xxx + +// Only non-ignored classes should warn about Ignored base classes +%ignore ActualClass; +%ignore ActualClassNoTemplates; + +%{ +struct BaseClassNoTemplates {}; +%} +%inline %{ +template +class TemplateClass {}; + +class ActualClass : public TemplateClass {}; +class AktuelKlass : public TemplateClass {}; + +class ActualClassNoTemplates : public BaseClassNoTemplates {}; +class AktuelKlassNoTemplates : public BaseClassNoTemplates {}; +%} diff --git a/Examples/test-suite/errors/cpp_inherit_ignored.stderr b/Examples/test-suite/errors/cpp_inherit_ignored.stderr new file mode 100644 index 000000000..360c1f9fc --- /dev/null +++ b/Examples/test-suite/errors/cpp_inherit_ignored.stderr @@ -0,0 +1,3 @@ +cpp_inherit_ignored.i:15: Warning 401: Nothing known about base class 'TemplateClass< int >'. Ignored. +cpp_inherit_ignored.i:15: Warning 401: Maybe you forgot to instantiate 'TemplateClass< int >' using %template. +cpp_inherit_ignored.i:18: Warning 401: Nothing known about base class 'BaseClassNoTemplates'. Ignored. diff --git a/Examples/test-suite/errors/cpp_overload.i b/Examples/test-suite/errors/cpp_overload.i deleted file mode 100644 index 34fa3cc25..000000000 --- a/Examples/test-suite/errors/cpp_overload.i +++ /dev/null @@ -1,15 +0,0 @@ -%module xxx -int foo(int x); -int foo(double x); - -class Foo { -public: - int bar(int); - int bar(double); -}; - -class Spam { -public: - Spam(); - Spam(int); -}; diff --git a/Examples/test-suite/errors/cpp_overload.stderr b/Examples/test-suite/errors/cpp_overload.stderr deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/errors/cpp_private_defvalue.i b/Examples/test-suite/errors/cpp_private_defvalue.i deleted file mode 100644 index 15542c7bc..000000000 --- a/Examples/test-suite/errors/cpp_private_defvalue.i +++ /dev/null @@ -1,7 +0,0 @@ -%module xxx - -class foo { -static const int BAR = 42; -public: - int blah(int x = BAR); -}; diff --git a/Examples/test-suite/errors/cpp_private_defvalue.stderr b/Examples/test-suite/errors/cpp_private_defvalue.stderr deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/errors/cpp_template_argname.i b/Examples/test-suite/errors/cpp_template_argname.i deleted file mode 100644 index b87c115c1..000000000 --- a/Examples/test-suite/errors/cpp_template_argname.i +++ /dev/null @@ -1,8 +0,0 @@ -%module xxx - -template T blah(T x); - - - - - diff --git a/Examples/test-suite/errors/cpp_template_argname.stderr b/Examples/test-suite/errors/cpp_template_argname.stderr deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/errors/cpp_template_repeat.i b/Examples/test-suite/errors/cpp_template_repeat.i index e63ffe8d9..f170080b7 100644 --- a/Examples/test-suite/errors/cpp_template_repeat.i +++ b/Examples/test-suite/errors/cpp_template_repeat.i @@ -4,4 +4,4 @@ template T blah(T x) { }; %template(iblah) blah; %template(iiblah) blah; - +// The second %template instantiation above should surely be ignored with a warning, but doesn't atm diff --git a/Examples/test-suite/errors/cpp_using_type_aliasing.stderr b/Examples/test-suite/errors/cpp_using_type_aliasing.stderr index 3f256652f..e69de29bb 100644 --- a/Examples/test-suite/errors/cpp_using_type_aliasing.stderr +++ b/Examples/test-suite/errors/cpp_using_type_aliasing.stderr @@ -1,3 +0,0 @@ -cpp_using_type_aliasing.i:8: Warning 341: The 'using' keyword in type aliasing is not fully supported yet. -cpp_using_type_aliasing.i:8: Warning 315: Nothing known about 'Okay< int >'. -cpp_using_type_aliasing.i:8: Warning 315: Nothing known about 'Okay< int >'. diff --git a/Examples/test-suite/errors/pp_macro_args.i b/Examples/test-suite/errors/pp_macro_args.i deleted file mode 100644 index 8bbbfb104..000000000 --- a/Examples/test-suite/errors/pp_macro_args.i +++ /dev/null @@ -1,7 +0,0 @@ -%module xxx - -#define foo(a,x) a x - -#if foo -#endif - diff --git a/Examples/test-suite/errors/pp_macro_args.stderr b/Examples/test-suite/errors/pp_macro_args.stderr deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/errors/swig_pythoncode_bad.stderr b/Examples/test-suite/errors/swig_pythoncode_bad.stderr index 71e5db8da..4bded5677 100644 --- a/Examples/test-suite/errors/swig_pythoncode_bad.stderr +++ b/Examples/test-suite/errors/swig_pythoncode_bad.stderr @@ -1 +1 @@ -swig_pythoncode_bad.i:7: Error: Line indented less than expected (line 2 of pythoncode) +swig_pythoncode_bad.i:7: Error: Line indented less than expected (line 2 of %pythoncode or %insert("python") block) as no line should be indented less than the indentation in line 1 diff --git a/Examples/test-suite/errors/swig_pythoncode_bad2.stderr b/Examples/test-suite/errors/swig_pythoncode_bad2.stderr index 48ad77e51..4fce40444 100644 --- a/Examples/test-suite/errors/swig_pythoncode_bad2.stderr +++ b/Examples/test-suite/errors/swig_pythoncode_bad2.stderr @@ -1 +1 @@ -swig_pythoncode_bad2.i:13: Error: Line indented less than expected (line 3 of pythoncode) +swig_pythoncode_bad2.i:13: 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 diff --git a/Examples/test-suite/errors/swig_pythoncode_bad3.i b/Examples/test-suite/errors/swig_pythoncode_bad3.i new file mode 100644 index 000000000..5759158d9 --- /dev/null +++ b/Examples/test-suite/errors/swig_pythoncode_bad3.i @@ -0,0 +1,7 @@ +%module xxx + +%pythoncode %{ + def extra(): + print "extra a" # indentation is 2 spaces then tab + print "extra b" # indentation is tab then 2 spaces +%} diff --git a/Examples/test-suite/errors/swig_pythoncode_bad3.stderr b/Examples/test-suite/errors/swig_pythoncode_bad3.stderr new file mode 100644 index 000000000..2de4e7d05 --- /dev/null +++ b/Examples/test-suite/errors/swig_pythoncode_bad3.stderr @@ -0,0 +1 @@ +swig_pythoncode_bad3.i:7: Warning 740: Whitespace indentation is inconsistent compared to earlier lines (line 3 of %pythoncode or %insert("python") block) diff --git a/Examples/test-suite/exception_classname.i b/Examples/test-suite/exception_classname.i new file mode 100644 index 000000000..ed8c433eb --- /dev/null +++ b/Examples/test-suite/exception_classname.i @@ -0,0 +1,13 @@ +%module exception_classname + +%warnfilter(SWIGWARN_RUBY_WRONG_NAME); +#if defined(SWIGPHP) || defined(SWIGD) +%rename(ExceptionClass) Exception; +#endif + +%inline %{ +class Exception { +public: + int testfunc() { return 42; } +}; +%} diff --git a/Examples/test-suite/extend.i b/Examples/test-suite/extend.i index 2a2a472ea..29e258f5b 100644 --- a/Examples/test-suite/extend.i +++ b/Examples/test-suite/extend.i @@ -23,6 +23,9 @@ struct Base { virtual int method(int v) { return v; } +#if !defined(SWIG) + virtual ~Base() {} +#endif }; struct Derived : Base { double actualval; diff --git a/Examples/test-suite/funcptr_cpp.i b/Examples/test-suite/funcptr_cpp.i index 015164ed9..b63749dc1 100644 --- a/Examples/test-suite/funcptr_cpp.i +++ b/Examples/test-suite/funcptr_cpp.i @@ -20,7 +20,7 @@ int call3(int & (*d)(const int &, int), int a, int b) { return d(a, b); } %constant int (*ADD_BY_VALUE)(const int &, int) = addByValue; %constant int * (*ADD_BY_POINTER)(const int &, int) = addByPointer; %constant int & (*ADD_BY_REFERENCE)(const int &, int) = addByReference; - +%constant int (* const ADD_BY_VALUE_C)(const int &, int) = addByValue; %inline %{ typedef int AddByValueTypedef(const int &a, int b); diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 63c18f2f4..01989b0d3 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -11,6 +11,8 @@ GO12 = @GO12@ GO13 = @GO13@ GO15 = @GO15@ GOC = @GOC@ +GOVERSIONOPTION = @GOVERSIONOPTION@ +host = @host@ SCRIPTSUFFIX = _runme.go GOCOMPILEARG = `if $(GO15); then echo tool compile; elif $(GO1); then echo tool $(GOC:c=g); fi` @@ -20,6 +22,8 @@ GOPACK = `if $(GO1) ; then echo go tool pack; else echo gopack; fi` GOOBJEXT = `if $(GO15); then echo o; else echo $(GOC:c=); fi` +OSXOLDGOLINKFLAGS = `if [ -n "\`$(GO) $(GOVERSIONOPTION) | grep -E 'go1($|.0|.1|.2|.3)'\`" ] && [ -n "\`echo $(host) | grep darwin\`" ]; then echo "-Wl,-U,__cgo_topofstack"; fi` + SO = @SO@ srcdir = @srcdir@ @@ -46,11 +50,11 @@ INCLUDES = -I$(abs_top_srcdir)/$(EXAMPLES)/$(TEST_SUITE) +$(swig_and_compile_cpp) $(run_testcase_cpp) if ! $(GO15); then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ - $(LANGUAGE)$(VARIANT)_cpp_nocgo; \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET='$(TARGETPREFIX)$*$(TARGETSUFFIX)' INTERFACEDIR='$(INTERFACEDIR)' INTERFACE='$*.i' \ + $(LANGUAGE)$(VARIANT)_cpp_nocgo && \ $(run_testcase_cpp); \ fi @@ -59,11 +63,11 @@ INCLUDES = -I$(abs_top_srcdir)/$(EXAMPLES)/$(TEST_SUITE) +$(swig_and_compile_c) $(run_testcase) if ! $(GO15); then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CSRCS="$(CSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ - $(LANGUAGE)$(VARIANT)_nocgo; \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CSRCS='$(CSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET='$(TARGETPREFIX)$*$(TARGETSUFFIX)' INTERFACEDIR='$(INTERFACEDIR)' INTERFACE='$*.i' \ + $(LANGUAGE)$(VARIANT)_nocgo && \ $(run_testcase); \ fi @@ -79,10 +83,10 @@ li_windows.cpptest: multi_import.multicpptest: $(setup) for f in multi_import_b multi_import_a; do \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$$f.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + LIBS='$(LIBS)' INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR='$(INTERFACEDIR)' INTERFACE="$$f.i" \ $(LANGUAGE)$(VARIANT)_cpp; \ done $(run_multi_testcase) @@ -91,18 +95,18 @@ go_subdir_import.multicpptest: $(setup) mkdir -p testdir/go_subdir_import/ mkdir -p gopath/src/testdir/go_subdir_import/ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ - INTERFACEPATH="$(SRCDIR)$(INTERFACEDIR)go_subdir_import_b.i" \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT) -outdir ." NOLINK=true \ - TARGET="$(TARGETPREFIX)go_subdir_import_b$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" \ - INTERFACE="testdir/go_subdir_import/go_subdir_import_b.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + LIBS='$(LIBS)' INTERFACEPATH='$(SRCDIR)$(INTERFACEDIR)go_subdir_import_b.i' \ + INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT) -outdir .' NOLINK=true \ + TARGET='$(TARGETPREFIX)go_subdir_import_b$(TARGETSUFFIX)' INTERFACEDIR='$(INTERFACEDIR)' \ + INTERFACE='testdir/go_subdir_import/go_subdir_import_b.i' \ $(LANGUAGE)$(VARIANT)_cpp; for f in testdir/go_subdir_import/go_subdir_import_c go_subdir_import_a ; do \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ - SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ - INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ - TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$$f.i" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + LIBS='$(LIBS)' INCLUDES='$(INCLUDES)' SWIGOPT='$(SWIGOPT)' NOLINK=true \ + TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR='$(INTERFACEDIR)' INTERFACE="$$f.i" \ $(LANGUAGE)$(VARIANT)_cpp; \ done if $(GOGCC); then \ @@ -121,7 +125,7 @@ run_testcase = \ $(COMPILETOOL) $(GCCGO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.a; \ elif $(GO12) || $(GO13) || $(GO15); then \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS) $(OSXOLDGOLINKFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ @@ -136,7 +140,7 @@ run_testcase_cpp = \ $(COMPILETOOL) $(GCCGO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.a -lstdc++; \ elif $(GO12) || $(GO13) || $(GO15); then \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS) $(OSXOLDGOLINKFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ @@ -152,7 +156,7 @@ run_multi_testcase = \ $(COMPILETOOL) $(GCCGO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ `for f in $$files; do echo $$f.a; done` -lstdc++; \ elif $(GO12) || $(GO13) || $(GO15); then \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS) $(OSXOLDGOLINKFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ @@ -164,7 +168,7 @@ run_multi_testcase = \ @rm -rf $*.go $*_gc.c $*_wrap.* $*_runme $*.gox $*.a clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" go_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' go_clean rm -f mod_a.go mod_a.gox mod_b.go mod_b.gox rm -f imports_a.go imports_a.gox imports_b.go imports_b.gox rm -f clientdata_prop_a.go clientdata_prop_a.gox diff --git a/Examples/test-suite/go/empty_c_runme.go b/Examples/test-suite/go/empty_c_runme.go new file mode 100644 index 000000000..831a56118 --- /dev/null +++ b/Examples/test-suite/go/empty_c_runme.go @@ -0,0 +1,6 @@ +package main + +import _ "./empty_c" + +func main() { +} diff --git a/Examples/test-suite/go/go_inout_runme.go b/Examples/test-suite/go/go_inout_runme.go index 13c429b87..9aa0cd0c5 100644 --- a/Examples/test-suite/go/go_inout_runme.go +++ b/Examples/test-suite/go/go_inout_runme.go @@ -40,4 +40,14 @@ func main() { fmt.Println("got", a, "want", dwant) panic(a) } + + c2 := go_inout.NewC2() + pm := c2.M() + want = map[string]interface{}{ + "ID": float64(1), + } + if !reflect.DeepEqual(*pm, want) { + fmt.Println("for c2.M got", pm, "want", want) + panic(pm) + } } diff --git a/Examples/test-suite/go/keyword_rename_c_runme.go b/Examples/test-suite/go/keyword_rename_c_runme.go new file mode 100644 index 000000000..425e38a26 --- /dev/null +++ b/Examples/test-suite/go/keyword_rename_c_runme.go @@ -0,0 +1,8 @@ +package main + +import "./keyword_rename_c" + +func main() { + keyword_rename_c.Xgo(1) + keyword_rename_c.Xchan(1) +} diff --git a/Examples/test-suite/go/li_carrays_cpp_runme.go b/Examples/test-suite/go/li_carrays_cpp_runme.go new file mode 100644 index 000000000..7ee0a4103 --- /dev/null +++ b/Examples/test-suite/go/li_carrays_cpp_runme.go @@ -0,0 +1,14 @@ +package main + +import . "./li_carrays_cpp" + +func main() { + d := NewDoubleArray(10) + + d.Setitem(0, 7) + d.Setitem(5, d.Getitem(0)+3) + + if d.Getitem(5)+d.Getitem(0) != 17 { + panic(0) + } +} diff --git a/Examples/test-suite/go/li_cdata_cpp_runme.go b/Examples/test-suite/go/li_cdata_cpp_runme.go new file mode 100644 index 000000000..42a0ebd08 --- /dev/null +++ b/Examples/test-suite/go/li_cdata_cpp_runme.go @@ -0,0 +1,13 @@ +package main + +import . "./li_cdata_cpp" + +func main() { + s := "ABC abc" + m := Malloc(256) + Memmove(m, s, len(s)) + ss := Cdata(m, 7) + if string(ss) != "ABC abc" { + panic("failed") + } +} diff --git a/Examples/test-suite/go/li_cpointer_cpp_runme.go b/Examples/test-suite/go/li_cpointer_cpp_runme.go new file mode 100644 index 000000000..e2f5a59d1 --- /dev/null +++ b/Examples/test-suite/go/li_cpointer_cpp_runme.go @@ -0,0 +1,14 @@ +package main + +import . "./li_cpointer_cpp" + +func main() { + p := New_intp() + Intp_assign(p, 3) + + if Intp_value(p) != 3 { + panic(0) + } + + Delete_intp(p) +} diff --git a/Examples/test-suite/go/li_std_vector_ptr_runme.go b/Examples/test-suite/go/li_std_vector_ptr_runme.go index cee997ad0..a9f7fe91c 100644 --- a/Examples/test-suite/go/li_std_vector_ptr_runme.go +++ b/Examples/test-suite/go/li_std_vector_ptr_runme.go @@ -1,12 +1,19 @@ package main import . "./li_std_vector_ptr" +import "fmt" +func check(val1 int, val2 int) { + if val1 != val2 { + panic(fmt.Sprintf("Values are not the same %d %d", val1, val2)) + } +} func main() { ip1 := MakeIntPtr(11) ip2 := MakeIntPtr(22) vi := NewIntPtrVector() vi.Add(ip1) vi.Add(ip2) - DisplayVector(vi) + check(GetValueFromVector(vi, 0), 11) + check(GetValueFromVector(vi, 1), 22) } diff --git a/Examples/test-suite/go/overload_extendc_runme.go b/Examples/test-suite/go/overload_extend2_runme.go similarity index 86% rename from Examples/test-suite/go/overload_extendc_runme.go rename to Examples/test-suite/go/overload_extend2_runme.go index 1bdba7509..121506734 100644 --- a/Examples/test-suite/go/overload_extendc_runme.go +++ b/Examples/test-suite/go/overload_extend2_runme.go @@ -1,9 +1,9 @@ package main -import "./overload_extendc" +import "./overload_extend2" func main() { - f := overload_extendc.NewFoo() + f := overload_extend2.NewFoo() if f.Test(3) != 1 { panic(0) } diff --git a/Examples/test-suite/go/overload_extend_c_runme.go b/Examples/test-suite/go/overload_extend_c_runme.go new file mode 100644 index 000000000..e00f0b945 --- /dev/null +++ b/Examples/test-suite/go/overload_extend_c_runme.go @@ -0,0 +1,22 @@ +package main + +import "./overload_extend_c" + +func main() { + f := overload_extend_c.NewFoo() + if f.Test().(int) != 0 { + panic(0) + } + if f.Test(3).(int) != 1 { + panic(0) + } + if f.Test("hello").(int) != 2 { + panic(0) + } + if f.Test(float64(3), float64(2)).(float64) != 5 { + panic(0) + } + if f.Test(3.0).(float64) != 1003 { + panic(0) + } +} diff --git a/Examples/test-suite/go_inout.i b/Examples/test-suite/go_inout.i index 57e7bf2fb..0bcb979ef 100644 --- a/Examples/test-suite/go_inout.i +++ b/Examples/test-suite/go_inout.i @@ -23,7 +23,7 @@ struct RetStruct { // Write a typemap that calls C++ by converting in and out of JSON. -%go_import("encoding/json", "bytes", "encoding/binary") +%go_import("encoding/json", "bytes", "encoding/binary", "reflect", "unsafe") %insert(go_header) %{ @@ -68,6 +68,26 @@ type In json.Marshaler } %} +%typemap(gotype) RetStruct* "*map[string]interface{}" + +%typemap(imtype) RetStruct* "*string" + +%typemap(out,fragment="AllocateString") RetStruct* +%{ + $result = (_gostring_*)malloc(sizeof(_gostring_)); + *$result = Swig_AllocateString($1->str.data(), $1->str.length()); +%} + +%typemap(goout,fragment="CopyString") RetStruct* +%{ + defer Swig_free(uintptr(unsafe.Pointer($1))) + var rm map[string]interface{} + if err := json.Unmarshal([]byte(swigCopyString(*$1)), &rm); err != nil { + panic(err) + } + $result = &rm +%} + %inline %{ @@ -87,6 +107,10 @@ struct MyArray { std::vector strings; }; +void* Allocate(int n) { + return new char[n]; +} + static uint64_t getuint64(const char* s) { uint64_t ret = 0; for (int i = 0; i < 8; i++, s++) { @@ -121,7 +145,12 @@ static void putuint64(std::string *s, size_t off, uint64_t v) { buf.Write(b[:]) buf.WriteString(s) } - str := buf.String() + bb := buf.Bytes() + p := Allocate(len(bb)) + copy((*[1<<15]byte)(unsafe.Pointer(p))[:len(bb)], bb) + var str string + (*reflect.StringHeader)(unsafe.Pointer(&str)).Data = uintptr(unsafe.Pointer(p)) + (*reflect.StringHeader)(unsafe.Pointer(&str)).Len = len(bb) $result = &str } %} @@ -197,3 +226,18 @@ void DoubleArray(MyArray* v) { } } %} + +%inline +%{ +class C1 { + public: + RetStruct* M() { + RetStruct* r = new RetStruct; + r->str = "{\"ID\":1}"; + return r; + } +}; + +class C2 : public C1 { +}; +%} diff --git a/Examples/test-suite/guile/Makefile.in b/Examples/test-suite/guile/Makefile.in index 9050d76f5..55885fc29 100644 --- a/Examples/test-suite/guile/Makefile.in +++ b/Examples/test-suite/guile/Makefile.in @@ -62,4 +62,4 @@ run_testcase = \ @rm -f $*-guile clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" guile_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' guile_clean diff --git a/Examples/test-suite/guile/li_std_string_runme.scm b/Examples/test-suite/guile/li_std_string_runme.scm index 83fc2b5e7..fcf2f58d2 100644 --- a/Examples/test-suite/guile/li_std_string_runme.scm +++ b/Examples/test-suite/guile/li_std_string_runme.scm @@ -25,7 +25,7 @@ (if (not (try-set-locale "C.UTF-8")) ; Linux (if (not (try-set-locale "en_US.utf8")) ; Linux -(if (not (try-set-locale "en_US.UTF-8")) ; Mac OSX +(if (not (try-set-locale "en_US.UTF-8")) ; Mac OS X (error "Failed to set any UTF-8 locale") ))) diff --git a/Examples/test-suite/guile/overload_extend_c_runme.scm b/Examples/test-suite/guile/overload_extend_c_runme.scm new file mode 100644 index 000000000..a26b8a95c --- /dev/null +++ b/Examples/test-suite/guile/overload_extend_c_runme.scm @@ -0,0 +1,2 @@ +(dynamic-call "scm_init_overload_extend_c_module" (dynamic-link "./liboverload_extend_c")) +(load "../schemerunme/overload_extend_c.scm") diff --git a/Examples/test-suite/insert_directive.i b/Examples/test-suite/insert_directive.i index 8ad966a99..36c3af6c6 100644 --- a/Examples/test-suite/insert_directive.i +++ b/Examples/test-suite/insert_directive.i @@ -34,5 +34,5 @@ int inserted_wrapper(int i) { return inserted_header3(i); } %init %{ // %inserted code %init -int inserted_init_value = inserted_wrapper(0); +int SWIGUNUSED inserted_init_value = inserted_wrapper(0); %} diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index 6dcc62f26..986c230cc 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -5,7 +5,7 @@ LANGUAGE = java JAVA = @JAVA@ JAVAC = @JAVAC@ -JAVAFLAGS = -Xcheck:jni +JAVAFLAGS = @JAVAFLAGS@ JAVA_CLASSPATH_SEP := @JAVA_CLASSPATH_SEP@ SCRIPTSUFFIX = _runme.java @@ -28,6 +28,7 @@ CPP_TEST_CASES = \ java_director_assumeoverride \ java_director_exception_feature \ java_director_exception_feature_nspace \ + java_director_ptrclass \ java_enums \ java_jnitypes \ java_lib_arrays_dimensionless \ @@ -38,7 +39,7 @@ CPP_TEST_CASES = \ java_prepost \ java_throws \ java_typemaps_proxy \ - java_typemaps_typewrapper + java_typemaps_typewrapper \ # li_boost_intrusive_ptr CPP11_TEST_CASES = \ @@ -59,12 +60,13 @@ JAVA_PACKAGEOPT = -package $(JAVA_PACKAGE) SWIGOPT += $(JAVA_PACKAGEOPT) # Custom tests - tests with additional commandline options -java_nspacewithoutpackage.%: JAVA_PACKAGEOPT = -java_director_exception_feature_nspace.%: JAVA_PACKAGE = $*Package -nspace.%: JAVA_PACKAGE = $*Package -nspace_extend.%: JAVA_PACKAGE = $*Package director_nspace.%: JAVA_PACKAGE = $*Package director_nspace_director_name_collision.%: JAVA_PACKAGE = $*Package +java_director_exception_feature_nspace.%: JAVA_PACKAGE = $*Package +java_nspacewithoutpackage.%: JAVA_PACKAGEOPT = +multiple_inheritance_nspace.%: JAVA_PACKAGE = $*Package +nspace.%: JAVA_PACKAGE = $*Package +nspace_extend.%: JAVA_PACKAGE = $*Package doxygen_misc_constructs.%: INCLUDES = -I../$(srcdir)/.. # Rules for the different types of tests diff --git a/Examples/test-suite/java/char_binary_runme.java b/Examples/test-suite/java/char_binary_runme.java index 9227f8617..bc811ef5d 100644 --- a/Examples/test-suite/java/char_binary_runme.java +++ b/Examples/test-suite/java/char_binary_runme.java @@ -20,5 +20,11 @@ public class char_binary_runme { if (t.strlen(hil0) != 4) throw new RuntimeException("bad multi-arg typemap"); + + if (t.ustrlen(hile) != 4) + throw new RuntimeException("bad multi-arg typemap"); + + if (t.ustrlen(hil0) != 4) + throw new RuntimeException("bad multi-arg typemap"); } } diff --git a/Examples/test-suite/java/constant_directive_runme.java b/Examples/test-suite/java/constant_directive_runme.java index b5135a499..4b5c3c3d0 100644 --- a/Examples/test-suite/java/constant_directive_runme.java +++ b/Examples/test-suite/java/constant_directive_runme.java @@ -18,5 +18,9 @@ public class constant_directive_runme { throw new RuntimeException("fail"); if (constant_directive.TYPE1_CONSTANT3.getVal() != 3) throw new RuntimeException("fail"); + if (constant_directive.TYPE1CONST_CONSTANT1.getVal() != 1) + throw new RuntimeException("fail"); + if (constant_directive.TYPE1CPTR_CONSTANT1.getVal() != 1) + throw new RuntimeException("fail"); } } diff --git a/Examples/test-suite/java/cpp11_li_std_array_runme.java b/Examples/test-suite/java/cpp11_li_std_array_runme.java new file mode 100644 index 000000000..2e2a20138 --- /dev/null +++ b/Examples/test-suite/java/cpp11_li_std_array_runme.java @@ -0,0 +1,82 @@ +import cpp11_li_std_array.*; + +public class cpp11_li_std_array_runme { + + static { + try { + System.loadLibrary("cpp11_li_std_array"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); + System.exit(1); + } + } + + private static ArrayInt6 ToArray6(int [] a) { + ArrayInt6 ai = new ArrayInt6(); + if (a.length != 6) + throw new RuntimeException("a is incorrect size"); + for (int i=0; i<6; ++i) + ai.set(i, a[i]); + return ai; + } + + private static void compareContainers(ArrayInt6 actual, int[] expected) { + if (actual.size() != expected.length) + throw new RuntimeException("Sizes are different: " + actual.size() + " " + expected.length); + for (int i=0; i bigIntegers = new ArrayList(); + for (int i=0; i +class Ptr { +public: + Ptr(T* b) : b_(b) {} + T* Get() const { return b_; } +private: + T* b_; +}; + +class Foo { +public: + // Calling FinalMaybeTouch from Java unambiguously goes through C++ to + // reach MaybeTouch. + Ptr< bar::Baz > FinalMaybeTouch(Baz* b) { + return MaybeTouch(Ptr< bar::Baz >(b)); + } + virtual Ptr< bar::Baz > MaybeTouch(Ptr< bar::Baz > f) { + return f; /* Don't touch */ + } + virtual ~Foo() {} +}; +} +%} + +%feature("director") Foo; + +%typemap(jni) bar::Ptr< bar::Baz > "jlong" +%typemap(jtype) bar::Ptr< bar::Baz > "long" +%typemap(jstype) bar::Ptr< bar::Baz > "Baz" +%typemap(in) bar::Ptr< bar::Baz > { + $1 = bar::Ptr< bar::Baz >(*( bar::Baz**)&$input); +} +%typemap(out) bar::Ptr< bar::Baz > { + const bar::Ptr< bar::Baz >& ptr = $1; + if (ptr.Get()) { + $result = ($typemap(jni, bar::Baz))ptr.Get(); + } else { + $result = 0; + } +} +%typemap(javain) bar::Ptr< bar::Baz > "$typemap(jstype, bar::Baz).getCPtr($javainput)" +%typemap(javaout) bar::Ptr< bar::Baz > { + long cPtr = $jnicall; + return (cPtr == 0) ? null : new $typemap(jstype, bar::Baz)(cPtr, false); +} +%typemap(directorin, descriptor="L$packagepath/$typemap(jstype, bar::Baz);") bar::Ptr< bar::Baz > +%{ *((bar::Baz**)&$input) = ((bar::Ptr< bar::Baz >&)$1).Get(); %} +%typemap(directorout) bar::Ptr< bar::Baz > { + $result = bar::Ptr< bar::Baz >(*( bar::Baz**)&$input); +} +%typemap(javadirectorin) bar::Ptr< bar::Baz > %{ + ((long)$jniinput == 0) ? null : new $typemap(jstype, bar::Baz)($jniinput, false) +%} +%typemap(javadirectorout) bar::Ptr< bar::Baz > "$typemap(jstype, bar::Baz).getCPtr($javacall)" + +namespace bar { +class Baz { +public: + Baz() : touched(false) {} + void SetTouched() { touched = true; } + bool GetTouched() { return touched; } +private: + bool touched; +}; + +template +class Ptr { +public: + Ptr(T* b) : b_(b) {} + T* Get() { return b_; } +private: + T* b_; +}; + +class Foo { +public: + // Calling FinalMaybeTouch from Java unambiguously goes through C++ to + // reach MaybeTouch. + Ptr< bar::Baz > FinalMaybeTouch(Baz* b) { + return MaybeTouch(Ptr< bar::Baz >(b)); + } + virtual Ptr< bar::Baz > MaybeTouch(Ptr< bar::Baz > f) { + return f; /* Don't touch */ + } + virtual ~Foo() {} +}; +} + diff --git a/Examples/test-suite/java_typemaps_proxy.i b/Examples/test-suite/java_typemaps_proxy.i index e315a36b5..3e9b18335 100644 --- a/Examples/test-suite/java_typemaps_proxy.i +++ b/Examples/test-suite/java_typemaps_proxy.i @@ -31,8 +31,8 @@ import java.lang.*; // for Exception // Create a new getCPtr() function which takes Java null and is public %typemap(javabody) NS::Greeting %{ - private long swigCPtr; - protected boolean swigCMemOwn; + private transient long swigCPtr; + protected transient boolean swigCMemOwn; protected $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; @@ -46,8 +46,8 @@ import java.lang.*; // for Exception // Make the pointer constructor public %typemap(javabody) NS::Farewell %{ - private long swigCPtr; - protected boolean swigCMemOwn; + private transient long swigCPtr; + protected transient boolean swigCMemOwn; public $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; diff --git a/Examples/test-suite/java_typemaps_typewrapper.i b/Examples/test-suite/java_typemaps_typewrapper.i index a99ca7b65..b7bf847ef 100644 --- a/Examples/test-suite/java_typemaps_typewrapper.i +++ b/Examples/test-suite/java_typemaps_typewrapper.i @@ -39,7 +39,7 @@ import java.lang.*; // for Exception // Create a new getCPtr() function which takes Java null and is public // Make the pointer constructor public %typemap(javabody) Farewell * %{ - private long swigCPtr; + private transient long swigCPtr; public $javaclassname(long cPtr, boolean bFutureUse) { swigCPtr = cPtr; diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 83b15f822..b430f236f 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -13,7 +13,8 @@ srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -SWIG = $(top_builddir)/preinst_swig +SWIGEXE = $(top_builddir)/swig +SWIG_LIB_DIR = $(top_srcdir)/Lib ifneq (, $(ENGINE)) JSENGINE=$(ENGINE) @@ -53,26 +54,30 @@ ifeq (node,$(JSENGINE)) enum_thorough.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" setup_node = \ - test -d $* || mkdir $*; \ + test -d $* || mkdir $* && \ sed -e 's|$$testcase|$*|g; s|$$cflags|$(GYP_CFLAGS)|g; s|$$srcdir|$(srcdir)|g' \ - $(srcdir)/node_template/binding.gyp.in > $*/binding.gyp; \ + $(srcdir)/node_template/binding.gyp.in > $*/binding.gyp && \ sed -e 's|$$testcase|$*|g;' \ $(srcdir)/node_template/index.js.in > $*/index.js # Note: we need to use swig in C parse mode, but make node-gyp believe it is c++ (via file extension) swig_and_compile_c = \ - $(setup_node); \ - $(SWIG) -javascript $(SWIGOPT) -o $*_wrap.cxx $(srcdir)/../$*.i; \ - $(NODEGYP) --loglevel=silent --directory $* configure build 1>>/dev/null + $(setup_node) && \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-javascript $(SWIGOPT) -o $*_wrap.cxx $(srcdir)/../$*.i' swiginvoke && \ + $(COMPILETOOL) $(NODEGYP) --loglevel=silent --directory $* configure build 1>>/dev/null swig_and_compile_cpp = \ - $(setup_node); \ - $(SWIG) -c++ -javascript $(SWIGOPT) $(srcdir)/../$*.i; \ - $(NODEGYP) --loglevel=silent --directory $* configure build 1>>/dev/null + $(setup_node) && \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='-c++ -javascript $(SWIGOPT) $(srcdir)/../$*.i' swiginvoke && \ + $(COMPILETOOL) $(NODEGYP) --loglevel=silent --directory $* configure build 1>>/dev/null run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - env NODE_PATH=$$PWD:$(srcdir) $(NODEJS) $(srcdir)/$*$(SCRIPTSUFFIX); \ + env NODE_PATH=$$PWD:$(srcdir) $(RUNTOOL) $(NODEJS) $(srcdir)/$*$(SCRIPTSUFFIX); \ fi diff --git a/Examples/test-suite/javascript/char_binary_runme.js b/Examples/test-suite/javascript/char_binary_runme.js index b2aac920c..01b72ebe1 100644 --- a/Examples/test-suite/javascript/char_binary_runme.js +++ b/Examples/test-suite/javascript/char_binary_runme.js @@ -5,10 +5,17 @@ if (t.strlen('hile') != 4) { print(t.strlen('hile')); throw("bad multi-arg typemap 1"); } +if (t.ustrlen('hile') != 4) { + print(t.ustrlen('hile')); + throw("bad multi-arg typemap 1"); +} if (t.strlen('hil\0') != 4) { throw("bad multi-arg typemap 2"); } +if (t.ustrlen('hil\0') != 4) { + throw("bad multi-arg typemap 2"); +} /* * creating a raw char* @@ -24,6 +31,9 @@ char_binary.pchar_setitem(pc, 4, 0); if (t.strlen(pc) != 4) { throw("bad multi-arg typemap (3)"); } +if (t.ustrlen(pc) != 4) { + throw("bad multi-arg typemap (3)"); +} char_binary.var_pchar = pc; if (char_binary.var_pchar != "hola") { diff --git a/Examples/test-suite/javascript/empty_c_runme.js b/Examples/test-suite/javascript/empty_c_runme.js new file mode 100644 index 000000000..1cc22e4ce --- /dev/null +++ b/Examples/test-suite/javascript/empty_c_runme.js @@ -0,0 +1 @@ +var empty_c = require("empty_c"); diff --git a/Examples/test-suite/javascript/swig_exception_runme.js b/Examples/test-suite/javascript/swig_exception_runme.js new file mode 100644 index 000000000..55435e947 --- /dev/null +++ b/Examples/test-suite/javascript/swig_exception_runme.js @@ -0,0 +1,30 @@ +var swig_exception = require("swig_exception"); + +var c = new swig_exception.Circle(10); +var s = new swig_exception.Square(10); + +if (swig_exception.Shape.nshapes != 2) { + throw "Shape.nshapes should be 2, actually " + swig_exception.Shape.nshapes; +} + +// ----- Throw exception ----- +try { + c.throwException(); + throw "Exception wasn't thrown"; +} catch (e) { + if (e.message != "OK") { + throw "Exception message should be \"OK\", actually \"" + e.message + "\""; + } +} + +// ----- Delete everything ----- + +c = null; +s = null; +e = null; + +/* FIXME: Garbage collection needs to happen before this check will work. +if (swig_exception.Shape.nshapes != 0) { + throw "Shape.nshapes should be 0, actually " + swig_exception.Shape.nshapes; +} +*/ diff --git a/Examples/test-suite/keyword_rename_c.i b/Examples/test-suite/keyword_rename_c.i new file mode 100644 index 000000000..9c3294271 --- /dev/null +++ b/Examples/test-suite/keyword_rename_c.i @@ -0,0 +1,7 @@ +/* + * Test reserved keyword renaming + */ + +%module keyword_rename_c + +%include "keyword_rename.i" diff --git a/Examples/test-suite/li_boost_shared_ptr.i b/Examples/test-suite/li_boost_shared_ptr.i index 25ca6039b..b64197be1 100644 --- a/Examples/test-suite/li_boost_shared_ptr.i +++ b/Examples/test-suite/li_boost_shared_ptr.i @@ -44,7 +44,7 @@ # define SWIG_SHARED_PTR_NAMESPACE SwigBoost #endif -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) || defined(SWIGOCTAVE) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) || defined(SWIGOCTAVE) || defined(SWIGRUBY) #define SHARED_PTR_WRAPPERS_IMPLEMENTED #endif @@ -341,6 +341,7 @@ template struct Base { T2 baseVal2; Base(T1 t1, T2 t2) : baseVal1(t1*2), baseVal2(t2*2) {} virtual std::string getValue() const { return "Base<>"; }; + virtual ~Base() {} }; %} diff --git a/Examples/test-suite/li_boost_shared_ptr_attribute.i b/Examples/test-suite/li_boost_shared_ptr_attribute.i index c4d3dca36..f15baa693 100644 --- a/Examples/test-suite/li_boost_shared_ptr_attribute.i +++ b/Examples/test-suite/li_boost_shared_ptr_attribute.i @@ -1,6 +1,6 @@ %module li_boost_shared_ptr_attribute -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) || defined(SWIGOCTAVE) || defined(SWIGRUBY) #define SHARED_PTR_WRAPPERS_IMPLEMENTED #endif diff --git a/Examples/test-suite/li_boost_shared_ptr_bits.i b/Examples/test-suite/li_boost_shared_ptr_bits.i index c0101b131..b61fd2aa6 100644 --- a/Examples/test-suite/li_boost_shared_ptr_bits.i +++ b/Examples/test-suite/li_boost_shared_ptr_bits.i @@ -1,6 +1,6 @@ %module li_boost_shared_ptr_bits -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) || defined(SWIGOCTAVE) || defined(SWIGRUBY) #define SHARED_PTR_WRAPPERS_IMPLEMENTED #endif @@ -166,3 +166,53 @@ public: int HiddenPrivateDestructor::DeleteCount = 0; %} +///////////////////////////////////////////////// +// Non-public inheritance and shared_ptr +///////////////////////////////////////////////// + +#if defined(SHARED_PTR_WRAPPERS_IMPLEMENTED) +%shared_ptr(Base) +// No %shared_ptr(DerivedPrivate1) to check Warning 520 does not appear +// No %shared_ptr(DerivedProtected1) to check Warning 520 does not appear +%shared_ptr(DerivedPrivate2) +%shared_ptr(DerivedProtected2) + +%ignore Base2; +%shared_ptr(DerivedPublic) +#endif + +%inline %{ +class Base { +public: + virtual int b() = 0; + virtual ~Base() {} +}; + +class DerivedProtected1 : protected Base { +public: + virtual int b() { return 20; } +}; +class DerivedPrivate1 : private Base { +public: + virtual int b() { return 20; } +}; + +class DerivedProtected2 : protected Base { +public: + virtual int b() { return 20; } +}; +class DerivedPrivate2 : private Base { +public: + virtual int b() { return 20; } +}; + +class Base2 { +public: + virtual int b2() = 0; + virtual ~Base2() {} +}; +class DerivedPublic : public Base2 { +public: + virtual int b2() { return 20; } +}; +%} diff --git a/Examples/test-suite/li_boost_shared_ptr_template.i b/Examples/test-suite/li_boost_shared_ptr_template.i index c1cd32ec6..3965a976e 100644 --- a/Examples/test-suite/li_boost_shared_ptr_template.i +++ b/Examples/test-suite/li_boost_shared_ptr_template.i @@ -15,6 +15,7 @@ class Base { public: virtual T bar() {return 1;} + virtual ~Base() {} }; template @@ -29,7 +30,7 @@ %} -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGD) || defined(SWIGOCTAVE) || defined(SWIGRUBY) #define SHARED_PTR_WRAPPERS_IMPLEMENTED #endif @@ -66,7 +67,7 @@ INTEGER bar_getter(Base& foo) { // 2nd test - templates with default template parameters #if defined(SHARED_PTR_WRAPPERS_IMPLEMENTED) -%shared_ptr(Space::BaseDefault) +%shared_ptr(Space::BaseDefault) %shared_ptr(Space::DerivedDefault) %shared_ptr(Space::DerivedDefault2) @@ -79,6 +80,7 @@ template class BaseDefault { public: virtual T bar2() {return 3;} + virtual ~BaseDefault() {} }; template diff --git a/Examples/test-suite/li_carrays_cpp.i b/Examples/test-suite/li_carrays_cpp.i new file mode 100644 index 000000000..c4743420e --- /dev/null +++ b/Examples/test-suite/li_carrays_cpp.i @@ -0,0 +1,28 @@ +%module li_carrays_cpp + +%warnfilter(SWIGWARN_RUBY_WRONG_NAME) doubleArray; /* Ruby, wrong class name */ + +%include + +%array_functions(int,intArray); +%array_class(double, doubleArray); + +%inline %{ +typedef struct { + int x; + int y; +} XY; +XY globalXYArray[3]; + +typedef struct { + int a; + int b; +} AB; + +AB globalABArray[3]; +%} + +// Note that struct XY { ... }; gives compiler error for C when using %array_class or %array_functions, but is okay in C++ +%array_class(XY, XYArray) +%array_functions(AB, ABArray) + diff --git a/Examples/test-suite/li_cdata_carrays_cpp.i b/Examples/test-suite/li_cdata_carrays_cpp.i new file mode 100644 index 000000000..9a88b8480 --- /dev/null +++ b/Examples/test-suite/li_cdata_carrays_cpp.i @@ -0,0 +1,8 @@ +%module li_cdata_carrays_cpp + +%include +%array_class(int, intArray); + +%include + +%cdata(int); diff --git a/Examples/test-suite/li_cdata_cpp.i b/Examples/test-suite/li_cdata_cpp.i new file mode 100644 index 000000000..2d7d300e4 --- /dev/null +++ b/Examples/test-suite/li_cdata_cpp.i @@ -0,0 +1,8 @@ +%module li_cdata_cpp + +%include + +%cdata(int); +%cdata(double); + +void *malloc(size_t size); diff --git a/Examples/test-suite/li_cpointer_cpp.i b/Examples/test-suite/li_cpointer_cpp.i new file mode 100644 index 000000000..869ce6e69 --- /dev/null +++ b/Examples/test-suite/li_cpointer_cpp.i @@ -0,0 +1,10 @@ +%module li_cpointer_cpp + +%warnfilter(SWIGWARN_RUBY_WRONG_NAME) doublep; /* Ruby, wrong class name */ + +%include "cpointer.i" + +%pointer_functions(int,intp); +%pointer_class(double,doublep); +%pointer_cast(int, unsigned int, int_to_uint); + diff --git a/Examples/test-suite/li_std_except.i b/Examples/test-suite/li_std_except.i index fc886dca7..b79d36bc1 100644 --- a/Examples/test-suite/li_std_except.i +++ b/Examples/test-suite/li_std_except.i @@ -24,6 +24,7 @@ int foo3() throw(E1) { return 0; } int foo4() throw(E2) { return 0; } // all the STL exceptions... + void throw_bad_cast() throw(std::bad_cast) { throw std::bad_cast(); } void throw_bad_exception() throw(std::bad_exception) { throw std::bad_exception(); } void throw_domain_error() throw(std::domain_error) { throw std::domain_error("oops"); } void throw_exception() throw(std::exception) { throw std::exception(); } diff --git a/Examples/test-suite/li_std_pair.i b/Examples/test-suite/li_std_pair.i index 9dea1d814..49ccb4aa4 100644 --- a/Examples/test-suite/li_std_pair.i +++ b/Examples/test-suite/li_std_pair.i @@ -60,3 +60,20 @@ int product3(const std::pair *p) { %} +// Test that the digraph <::aa::Holder> is not generated for stl containers +%include + +%inline %{ +namespace aa { + struct Holder { + Holder(int n = 0) : number(n) {} + int number; + }; +} +%} + +%template(PairTest) std::pair< ::aa::Holder, int >; + +%inline %{ +std::pair< ::aa::Holder, int > pair1(std::pair< ::aa::Holder, int > x) { return x; } +%} diff --git a/Examples/test-suite/li_std_vector.i b/Examples/test-suite/li_std_vector.i index 55e0f4f6d..ada146cc4 100644 --- a/Examples/test-suite/li_std_vector.i +++ b/Examples/test-suite/li_std_vector.i @@ -108,3 +108,35 @@ const std::vector & vecstructconstptr(const std::vector LanguageVector; } #endif + + +// Test that the digraph <::aa::Holder> is not generated +%include + +%inline %{ +namespace aa { + struct Holder { + Holder(int n = 0) : number(n) {} + int number; + }; +} +%} + +#if !defined(SWIGOCTAVE) +// To fix: something different in Octave is preventing this from working +%template(VectorTest) std::vector< ::aa::Holder >; + +%inline %{ +std::vector< ::aa::Holder > vec1(std::vector< ::aa::Holder > x) { return x; } +%} +#endif + +// exercising vectors of strings +%inline %{ +std::vector RevStringVec (const std::vector &In) + { + std::vector result(In); + std::reverse(result.begin(), result.end()); + return(result); + } +%} diff --git a/Examples/test-suite/li_std_vector_ptr.i b/Examples/test-suite/li_std_vector_ptr.i index 292c9d700..4d6794717 100644 --- a/Examples/test-suite/li_std_vector_ptr.i +++ b/Examples/test-suite/li_std_vector_ptr.i @@ -1,4 +1,4 @@ -// Bug 2359417 +// SF Bug 2359417 %module li_std_vector_ptr %include "std_vector.i" @@ -15,16 +15,76 @@ double* makeDoublePtr(double v) { return new double(v); } -#if 1 +// pointer to pointer in the wrappers was preventing a vector of pointers from working int** makeIntPtrPtr(int* v) { return new int*(v); } -#endif void displayVector(std::vector vpi) { cout << "displayVector..." << endl; - for (int i=0; i vpi, size_t index) { + return *vpi[index]; +} +%} + +// A not exposed to wrappers +%{ +struct A { + int val; + A(int val) : val(val) {} +}; +%} + +%template(APtrVector) std::vector; + +%inline %{ +A *makeA(int val) { return new A(val); } +int getVal(A* a) { return a->val; } +int getVectorValueA(std::vector vpi, size_t index) { + return vpi[index]->val; +} +%} + +// B is fully exposed to wrappers +%inline %{ +struct B { + int val; + B(int val = 0) : val(val) {} +}; +%} + +%template(BPtrVector) std::vector; + +%inline %{ +B *makeB(int val) { return new B(val); } +int getVal(B* b) { return b->val; } +int getVectorValueB(std::vector vpi, size_t index) { + return vpi[index]->val; +} +%} + +// C is fully exposed to wrappers (includes code using B **) +%inline %{ +struct C { + int val; + C(int val = 0) : val(val) {} +}; +%} + +%template(CPtrVector) std::vector; + +%inline %{ +// pointer to pointer in the wrappers was preventing a vector of pointers from working +C** makeCIntPtrPtr(C* v) { + return new C*(v); +} +C *makeC(int val) { return new C(val); } +int getVal(C* b) { return b->val; } +int getVectorValueC(std::vector vpi, size_t index) { + return vpi[index]->val; +} %} diff --git a/Examples/test-suite/long_long.i b/Examples/test-suite/long_long.i index 74dd87a15..47acc15c6 100644 --- a/Examples/test-suite/long_long.i +++ b/Examples/test-suite/long_long.i @@ -38,3 +38,9 @@ unsigned long long ull; #define lconst5 987654321LL #define lconst6 987654321ULL + +%inline %{ +long long UnsignedToSigned(unsigned long long ull) { + return (long long)ull; +} +%} diff --git a/Examples/test-suite/lua/Makefile.in b/Examples/test-suite/lua/Makefile.in index c562f09df..7a77bbb9e 100644 --- a/Examples/test-suite/lua/Makefile.in +++ b/Examples/test-suite/lua/Makefile.in @@ -14,6 +14,7 @@ top_builddir = @top_builddir@ CPP_TEST_CASES += \ lua_no_module_global \ + lua_inherit_getitem \ C_TEST_CASES += \ @@ -56,7 +57,7 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" lua_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' lua_clean cvsignore: @echo '*wrap* *.so *.dll *.exp *.lib' diff --git a/Examples/test-suite/lua/funcptr_cpp_runme.lua b/Examples/test-suite/lua/funcptr_cpp_runme.lua index 3b8469348..d814e059a 100644 --- a/Examples/test-suite/lua/funcptr_cpp_runme.lua +++ b/Examples/test-suite/lua/funcptr_cpp_runme.lua @@ -16,3 +16,4 @@ assert(fc.addByValue(5,10) == 15) assert(fc.call1(fc.ADD_BY_VALUE, 5, 10) == 15) assert(fc.call2(fc.ADD_BY_POINTER, 7, 9) == 16) assert(fc.call3(fc.ADD_BY_REFERENCE, 8, 9) == 17) +assert(fc.call1(fc.ADD_BY_VALUE_C, 2, 3) == 5) diff --git a/Examples/test-suite/lua/keyword_rename_c_runme.lua b/Examples/test-suite/lua/keyword_rename_c_runme.lua new file mode 100644 index 000000000..ca4f73cf9 --- /dev/null +++ b/Examples/test-suite/lua/keyword_rename_c_runme.lua @@ -0,0 +1,12 @@ +require("import") -- the import fn +import("keyword_rename_c") -- import lib into global +kn=keyword_rename_c--alias + +-- catching undefined variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +-- Check renaming of Lua keywords +assert(kn.c_end(5) == 5) +assert(kn.c_nil(7) == 7) diff --git a/Examples/test-suite/lua/li_carrays_cpp_runme.lua b/Examples/test-suite/lua/li_carrays_cpp_runme.lua new file mode 100644 index 000000000..3ead35457 --- /dev/null +++ b/Examples/test-suite/lua/li_carrays_cpp_runme.lua @@ -0,0 +1,29 @@ +require("import") -- the import fn +import("li_carrays_cpp") -- import code +lc = li_carrays_cpp + +-- catch "undefined" global variables +local env = _ENV -- Lua 5.2 +if not env then env = getfenv () end -- Lua 5.1 +setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) + +-- Testing for %array_functions(int,intArray) +ary = lc.new_intArray(2) +lc.intArray_setitem(ary, 0, 0) +lc.intArray_setitem(ary, 1, 1) +assert(lc.intArray_getitem(ary, 0)==0) +assert(lc.intArray_getitem(ary, 1)==1) +lc.delete_intArray(ary) + +-- Testing for %array_class(double, doubleArray) +d = lc.doubleArray(10) +d[0] = 7 +d[5] = d[0] + 3 +assert(d[5] + d[0] == 17) +--print(d[5] + d[0]) + +ptr = d:cast() -- to ptr +d2 = lc.doubleArray_frompointer(ptr) -- and back to array +assert(d2[5] + d2[0] == 17) +--print(d2[5] + d2[0]) + diff --git a/Examples/test-suite/lua/lua_inherit_getitem_runme.lua b/Examples/test-suite/lua/lua_inherit_getitem_runme.lua new file mode 100644 index 000000000..21c4796f8 --- /dev/null +++ b/Examples/test-suite/lua/lua_inherit_getitem_runme.lua @@ -0,0 +1,12 @@ +require("import") -- the import fn +import("lua_inherit_getitem") -- import lib + +local t = lua_inherit_getitem; +local base = t.CBase() +local derived = t.CDerived() + +assert(base.Foo ~= nil) +assert(base:Foo() == "CBase::Foo") +assert(derived.Foo == base.Foo) +assert(derived:Foo() == "CBase::Foo") + diff --git a/Examples/test-suite/lua_inherit_getitem.i b/Examples/test-suite/lua_inherit_getitem.i new file mode 100644 index 000000000..82c055dd1 --- /dev/null +++ b/Examples/test-suite/lua_inherit_getitem.i @@ -0,0 +1,19 @@ +%module lua_inherit_getitem + +%inline %{ + +class CBase { +public: + const char* Foo(void) { + return "CBase::Foo"; + } +}; + +class CDerived : public CBase { +public: + void *__getitem(const char *name) const { + return NULL; + } +}; + +%} diff --git a/Examples/test-suite/member_funcptr_galore.i b/Examples/test-suite/member_funcptr_galore.i index 962a8bd0e..9a012f306 100644 --- a/Examples/test-suite/member_funcptr_galore.i +++ b/Examples/test-suite/member_funcptr_galore.i @@ -28,6 +28,7 @@ public: void move(double dx, double dy); virtual double area(Shape &ref, int & (FunkSpace::Funktions::*d)(const int &, int)) { return 0.0; } virtual double abc(Thing ts, Thing< const Space::Shape * > tda[]) { return 0.0; } + virtual ~Shape() {} }; } diff --git a/Examples/test-suite/multiple_inheritance_abstract.i b/Examples/test-suite/multiple_inheritance_abstract.i new file mode 100644 index 000000000..b54a37dea --- /dev/null +++ b/Examples/test-suite/multiple_inheritance_abstract.i @@ -0,0 +1,328 @@ +// This is a copy of the multiple_inheritance_abstract test +%module multiple_inheritance_abstract + +%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, + SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%include "swiginterface.i" +%interface_impl(Space::ABase1) +%interface_impl(Space::CBase1) +%interface_impl(Space::CBase2) +#endif + +#if defined(SWIGD) +// Missing multiple inheritance support results in incorrect use of override +%ignore CBase1; +%ignore CBase2; +#endif + +%inline %{ +namespace Space { + struct CBase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 1; + } + int cbase1z() { + return 10; + } + virtual ~CBase1() { + } + }; + + struct CBase2 { + virtual int cbase2() { + return 2; + } + virtual ~CBase2() { + } + }; + + struct ABase1 { + virtual int abase1() = 0; + virtual ~ABase1() { + } + }; + + struct Derived1 : CBase2, CBase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 3; + } + virtual int cbase2() { + return 4; + } + virtual CBase2 *cloneit() { + return new Derived1(*this); + } + void derived1() { + } + }; + + struct Derived2 : CBase1, ABase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 6; + } + virtual int abase1() { + return 5; + } + virtual CBase1 *cloneit() { + return new Derived2(*this); + } + void derived2() { + } + }; + + struct Derived3 : ABase1, CBase1, CBase2 { + virtual int cbase1y() { + return 7; + } + virtual int cbase2() { + return 8; + } + virtual int abase1() { + return 9; + } + virtual void cbase1x() { + } + virtual ABase1 *cloneit() { + return new Derived3(*this); + } + void derived3() { + } + }; + + struct Bottom1 : Derived1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 103; + } + virtual int cbase2() { + return 104; + } + }; + + struct Bottom2 : Derived2 { + virtual int cbase1y() { + return 206; + } + virtual int abase1() { + return 205; + } + }; + + struct Bottom3 : Derived3 { + virtual int cbase1y() { + return 307; + } + virtual int cbase2() { + return 308; + } + virtual int abase1() { + return 309; + } + }; + + // Base classes as input + int InputValCBase1(CBase1 cb1) { + return cb1.cbase1y(); + } + int InputValCBase2(CBase2 cb2) { + return cb2.cbase2(); + } + + int InputPtrABase1(ABase1 *pab1) { + return pab1->abase1(); + } + int InputPtrCBase1(CBase1 *pcb1) { + return pcb1->cbase1y(); + } + int InputPtrCBase2(CBase2 *pcb2) { + return pcb2->cbase2(); + } + + int InputRefABase1(ABase1 &rab1) { + return rab1.abase1(); + } + int InputRefCBase1(CBase1 &rcb1) { + return rcb1.cbase1y(); + } + int InputRefCBase2(CBase2 &rcb2) { + return rcb2.cbase2(); + } + + int InputCPtrRefABase1(ABase1 *const& pab1) { + return pab1->abase1(); + } + int InputCPtrRefCBase1(CBase1 *const& pcb1) { + return pcb1->cbase1y(); + } + int InputCPtrRefCBase2(CBase2 *const& pcb2) { + return pcb2->cbase2(); + } + + // Derived classes as input + int InputValDerived1(Derived1 d) { + return d.cbase1y() + d.cbase2(); + } + int InputValDerived2(Derived2 d) { + return d.cbase1y() + d.abase1(); + } + int InputValDerived3(Derived3 d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputRefDerived1(Derived1 &d) { + return d.cbase1y() + d.cbase2(); + } + int InputRefDerived2(Derived2 &d) { + return d.cbase1y() + d.abase1(); + } + int InputRefDerived3(Derived3 &d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputPtrDerived1(Derived1 *d) { + return d->cbase1y() + d->cbase2(); + } + int InputPtrDerived2(Derived2 *d) { + return d->cbase1y() + d->abase1(); + } + int InputPtrDerived3(Derived3 *d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputCPtrRefDerived1(Derived1 *const& d) { + return d->cbase1y() + d->cbase2(); + } + int InputCPtrRefDerived2(Derived2 *const& d) { + return d->cbase1y() + d->abase1(); + } + int InputCPtrRefDerived3(Derived3 *const& d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + // Bottom classes as input + int InputValBottom1(Bottom1 d) { + return d.cbase1y() + d.cbase2(); + } + int InputValBottom2(Bottom2 d) { + return d.cbase1y() + d.abase1(); + } + int InputValBottom3(Bottom3 d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputRefBottom1(Bottom1 &d) { + return d.cbase1y() + d.cbase2(); + } + int InputRefBottom2(Bottom2 &d) { + return d.cbase1y() + d.abase1(); + } + int InputRefBottom3(Bottom3 &d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputPtrBottom1(Bottom1 *d) { + return d->cbase1y() + d->cbase2(); + } + int InputPtrBottom2(Bottom2 *d) { + return d->cbase1y() + d->abase1(); + } + int InputPtrBottom3(Bottom3 *d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputCPtrRefBottom1(Bottom1 *const& d) { + return d->cbase1y() + d->cbase2(); + } + int InputCPtrRefBottom2(Bottom2 *const& d) { + return d->cbase1y() + d->abase1(); + } + int InputCPtrRefBottom3(Bottom3 *const& d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + // Return pointers + CBase1 *MakePtrDerived1_CBase1() { + return new Derived1(); + } + CBase2 *MakePtrDerived1_CBase2() { + return new Derived1(); + } + CBase1 *MakePtrDerived2_CBase1() { + return new Derived2(); + } + ABase1 *MakePtrDerived2_ABase1() { + return new Derived2(); + } + ABase1 *MakePtrDerived3_ABase1() { + return new Derived3(); + } + CBase1 *MakePtrDerived3_CBase1() { + return new Derived3(); + } + CBase2 *MakePtrDerived3_CBase2() { + return new Derived3(); + } + + // Return references + CBase1 &MakeRefDerived1_CBase1() { + static Derived1 d; + return d; + } + CBase2 &MakeRefDerived1_CBase2() { + static Derived1 d; + return d; + } + CBase1 &MakeRefDerived2_CBase1() { + static Derived2 d; + return d; + } + ABase1 &MakeRefDerived2_ABase1() { + static Derived2 d; + return d; + } + ABase1 &MakeRefDerived3_ABase1() { + static Derived3 d; + return d; + } + CBase1 &MakeRefDerived3_CBase1() { + static Derived3 d; + return d; + } + CBase2 &MakeRefDerived3_CBase2() { + static Derived3 d; + return d; + } + + // Return by value (sliced objects) + CBase1 MakeValDerived1_CBase1() { + return Derived1(); + } + CBase2 MakeValDerived1_CBase2() { + return Derived1(); + } + CBase1 MakeValDerived2_CBase1() { + return Derived2(); + } + CBase1 MakeValDerived3_CBase1() { + return Derived3(); + } + CBase2 MakeValDerived3_CBase2() { + return Derived3(); + } +} + +%} diff --git a/Examples/test-suite/multiple_inheritance_interfaces.i b/Examples/test-suite/multiple_inheritance_interfaces.i new file mode 100644 index 000000000..2972922fb --- /dev/null +++ b/Examples/test-suite/multiple_inheritance_interfaces.i @@ -0,0 +1,66 @@ +%module multiple_inheritance_interfaces + +%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, + SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%include "swiginterface.i" +%interface_custom("A", "IA", IA) +%interface_custom("B", "IB", IB) +%interface_custom("%(strip:[I])s", "I%s", IC) // same as %interface_custom("C", "IC", IC) +#endif + +%inline %{ +struct IA { + virtual void ia() {}; + virtual void ia(const char *s, bool b = true) {} + virtual void ia(int i) {} + virtual ~IA() {} +}; +struct IB { virtual ~IB() {} virtual void ib() {} }; +struct IC : IA, IB {}; +struct D : IC {}; +struct E : D {}; +%} + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%interface_custom("J", "IJ", IJ) +%interface_custom("K", "IK", IK) +%interface_custom("L", "IL", IL) +#endif +%inline %{ +struct IJ { virtual ~IJ() {}; virtual void ij() {} }; +struct IK : IJ {}; +struct IL : IK {}; +struct M : IL {}; +%} + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%interface_custom("Q", "IQ", IQ) +#endif +%inline %{ +struct P { virtual ~P() {} virtual void p() {} }; +struct IQ { virtual ~IQ() {} virtual void iq() {} }; +struct R : IQ, P {}; +struct S : P, IQ {}; +struct T : IQ {}; +struct U : R {}; +struct V : S {}; +struct W : T {}; +%} + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%interface_impl(BaseOverloaded); +#endif +%inline %{ +struct BaseOverloaded { + typedef P PTypedef; + virtual ~BaseOverloaded() {} + virtual void identical_overload(int i, const PTypedef &pp = PTypedef()) {} +}; + +struct DerivedOverloaded : public BaseOverloaded { + virtual void identical_overload(int i, const PTypedef &p = PTypedef()) {} +}; +%} diff --git a/Examples/test-suite/multiple_inheritance_nspace.i b/Examples/test-suite/multiple_inheritance_nspace.i new file mode 100644 index 000000000..4faef5749 --- /dev/null +++ b/Examples/test-suite/multiple_inheritance_nspace.i @@ -0,0 +1,338 @@ +// This is a copy of the multiple_inheritance_abstract test +%module multiple_inheritance_nspace + +%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, + SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ + +// nspace feature only supported by these languages +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) || defined(SWIGJAVASCRIPT) +%nspace; +#endif + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%include "swiginterface.i" +%interface(Space::ABase1) +%interface(Space::CBase1) +%interface(Space::CBase2) +#endif + +#if defined(SWIGD) +// Missing multiple inheritance support results in incorrect use of override +%ignore CBase1; +%ignore CBase2; +#endif + +#if defined(SWIGJAVA) +SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) +#endif + +%inline %{ +namespace Space { + struct CBase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 1; + } + int cbase1z() { + return 10; + } + virtual ~CBase1() { + } + }; + + struct CBase2 { + virtual int cbase2() { + return 2; + } + virtual ~CBase2() { + } + }; + + struct ABase1 { + virtual int abase1() = 0; + virtual ~ABase1() { + } + }; + + struct Derived1 : CBase2, CBase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 3; + } + virtual int cbase2() { + return 4; + } + virtual CBase2 *cloneit() { + return new Derived1(*this); + } + void derived1() { + } + }; + + struct Derived2 : CBase1, ABase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 6; + } + virtual int abase1() { + return 5; + } + virtual CBase1 *cloneit() { + return new Derived2(*this); + } + void derived2() { + } + }; + + struct Derived3 : ABase1, CBase1, CBase2 { + virtual int cbase1y() { + return 7; + } + virtual int cbase2() { + return 8; + } + virtual int abase1() { + return 9; + } + virtual void cbase1x() { + } + virtual ABase1 *cloneit() { + return new Derived3(*this); + } + void derived3() { + } + }; + + struct Bottom1 : Derived1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 103; + } + virtual int cbase2() { + return 104; + } + }; + + struct Bottom2 : Derived2 { + virtual int cbase1y() { + return 206; + } + virtual int abase1() { + return 205; + } + }; + + struct Bottom3 : Derived3 { + virtual int cbase1y() { + return 307; + } + virtual int cbase2() { + return 308; + } + virtual int abase1() { + return 309; + } + }; + + // Base classes as input + int InputValCBase1(CBase1 cb1) { + return cb1.cbase1y(); + } + int InputValCBase2(CBase2 cb2) { + return cb2.cbase2(); + } + + int InputPtrABase1(ABase1 *pab1) { + return pab1->abase1(); + } + int InputPtrCBase1(CBase1 *pcb1) { + return pcb1->cbase1y(); + } + int InputPtrCBase2(CBase2 *pcb2) { + return pcb2->cbase2(); + } + + int InputRefABase1(ABase1 &rab1) { + return rab1.abase1(); + } + int InputRefCBase1(CBase1 &rcb1) { + return rcb1.cbase1y(); + } + int InputRefCBase2(CBase2 &rcb2) { + return rcb2.cbase2(); + } + + int InputCPtrRefABase1(ABase1 *const& pab1) { + return pab1->abase1(); + } + int InputCPtrRefCBase1(CBase1 *const& pcb1) { + return pcb1->cbase1y(); + } + int InputCPtrRefCBase2(CBase2 *const& pcb2) { + return pcb2->cbase2(); + } + + // Derived classes as input + int InputValDerived1(Derived1 d) { + return d.cbase1y() + d.cbase2(); + } + int InputValDerived2(Derived2 d) { + return d.cbase1y() + d.abase1(); + } + int InputValDerived3(Derived3 d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputRefDerived1(Derived1 &d) { + return d.cbase1y() + d.cbase2(); + } + int InputRefDerived2(Derived2 &d) { + return d.cbase1y() + d.abase1(); + } + int InputRefDerived3(Derived3 &d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputPtrDerived1(Derived1 *d) { + return d->cbase1y() + d->cbase2(); + } + int InputPtrDerived2(Derived2 *d) { + return d->cbase1y() + d->abase1(); + } + int InputPtrDerived3(Derived3 *d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputCPtrRefDerived1(Derived1 *const& d) { + return d->cbase1y() + d->cbase2(); + } + int InputCPtrRefDerived2(Derived2 *const& d) { + return d->cbase1y() + d->abase1(); + } + int InputCPtrRefDerived3(Derived3 *const& d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + // Bottom classes as input + int InputValBottom1(Bottom1 d) { + return d.cbase1y() + d.cbase2(); + } + int InputValBottom2(Bottom2 d) { + return d.cbase1y() + d.abase1(); + } + int InputValBottom3(Bottom3 d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputRefBottom1(Bottom1 &d) { + return d.cbase1y() + d.cbase2(); + } + int InputRefBottom2(Bottom2 &d) { + return d.cbase1y() + d.abase1(); + } + int InputRefBottom3(Bottom3 &d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputPtrBottom1(Bottom1 *d) { + return d->cbase1y() + d->cbase2(); + } + int InputPtrBottom2(Bottom2 *d) { + return d->cbase1y() + d->abase1(); + } + int InputPtrBottom3(Bottom3 *d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputCPtrRefBottom1(Bottom1 *const& d) { + return d->cbase1y() + d->cbase2(); + } + int InputCPtrRefBottom2(Bottom2 *const& d) { + return d->cbase1y() + d->abase1(); + } + int InputCPtrRefBottom3(Bottom3 *const& d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + // Return pointers + CBase1 *MakePtrDerived1_CBase1() { + return new Derived1(); + } + CBase2 *MakePtrDerived1_CBase2() { + return new Derived1(); + } + CBase1 *MakePtrDerived2_CBase1() { + return new Derived2(); + } + ABase1 *MakePtrDerived2_ABase1() { + return new Derived2(); + } + ABase1 *MakePtrDerived3_ABase1() { + return new Derived3(); + } + CBase1 *MakePtrDerived3_CBase1() { + return new Derived3(); + } + CBase2 *MakePtrDerived3_CBase2() { + return new Derived3(); + } + + // Return references + CBase1 &MakeRefDerived1_CBase1() { + static Derived1 d; + return d; + } + CBase2 &MakeRefDerived1_CBase2() { + static Derived1 d; + return d; + } + CBase1 &MakeRefDerived2_CBase1() { + static Derived2 d; + return d; + } + ABase1 &MakeRefDerived2_ABase1() { + static Derived2 d; + return d; + } + ABase1 &MakeRefDerived3_ABase1() { + static Derived3 d; + return d; + } + CBase1 &MakeRefDerived3_CBase1() { + static Derived3 d; + return d; + } + CBase2 &MakeRefDerived3_CBase2() { + static Derived3 d; + return d; + } + + // Return by value (sliced objects) + CBase1 MakeValDerived1_CBase1() { + return Derived1(); + } + CBase2 MakeValDerived1_CBase2() { + return Derived1(); + } + CBase1 MakeValDerived2_CBase1() { + return Derived2(); + } + CBase1 MakeValDerived3_CBase1() { + return Derived3(); + } + CBase2 MakeValDerived3_CBase2() { + return Derived3(); + } +} + +%} + diff --git a/Examples/test-suite/multiple_inheritance_shared_ptr.i b/Examples/test-suite/multiple_inheritance_shared_ptr.i new file mode 100644 index 000000000..5a08e5e6e --- /dev/null +++ b/Examples/test-suite/multiple_inheritance_shared_ptr.i @@ -0,0 +1,499 @@ +// This is a copy of the multiple_inheritance_abstract test and extended for testing %shared_ptr and %interface_impl +%module multiple_inheritance_shared_ptr + +%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE, + SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE); /* languages not supporting multiple inheritance or %interface */ + +// Typemap changes required to mix %shared_ptr and %interface_impl +// Note we don't have a way to use $javainterfacename/$csinterfacename (yet), +// so we improvise somewhat by adding the SwigImpl suffix +%define SWIG_SHARED_PTR_INTERFACE_TYPEMAPS(CONST, TYPE...) +#if defined(SWIGJAVA) +%typemap(javain) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "($javainput == null) ? 0 : $javainput.$typemap(jstype, TYPE)_GetInterfaceCPtr()" +%typemap(javaout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& { + long cPtr = $jnicall; + return (cPtr == 0) ? null : ($typemap(jstype, TYPE))new $typemap(jstype, TYPE)SwigImpl(cPtr, true); + } +#elif defined(SWIGCSHARP) +%typemap(csin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "$csinput == null ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : $csinput.GetInterfaceCPtr()" +%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)SwigImpl(cPtr, true);$excode + return ret; + } +#endif +%enddef + +#if defined(SWIGJAVA) || defined(SWIGCSHARP) +%include +%shared_ptr(Space::ABase1) +%shared_ptr(Space::CBase1) +%shared_ptr(Space::CBase2) +%shared_ptr(Space::Derived1) +%shared_ptr(Space::Derived2) +%shared_ptr(Space::Derived3) +%shared_ptr(Space::Bottom1) +%shared_ptr(Space::Bottom2) +%shared_ptr(Space::Bottom3) + +%include "swiginterface.i" +SWIG_SHARED_PTR_INTERFACE_TYPEMAPS(SWIGEMPTYHACK, Space::ABase1) +SWIG_SHARED_PTR_INTERFACE_TYPEMAPS(SWIGEMPTYHACK, Space::CBase1) +SWIG_SHARED_PTR_INTERFACE_TYPEMAPS(SWIGEMPTYHACK, Space::CBase2) +%interface_impl(Space::ABase1) +%interface_impl(Space::CBase1) +%interface_impl(Space::CBase2) +#endif + +#if defined(SWIGD) +// Missing multiple inheritance support results in incorrect use of override +%ignore CBase1; +%ignore CBase2; +#endif + +%inline %{ +#include + +namespace Space { + struct CBase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 1; + } + int cbase1z() { + return 10; + } + virtual ~CBase1() { + } + }; + + struct CBase2 { + virtual int cbase2() { + return 2; + } + virtual ~CBase2() { + } + }; + + struct ABase1 { + virtual int abase1() = 0; + virtual ~ABase1() { + } + }; + + struct Derived1 : CBase2, CBase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 3; + } + virtual int cbase2() { + return 4; + } + virtual CBase2 *cloneit() { + return new Derived1(*this); + } + void derived1() { + } + }; + + struct Derived2 : CBase1, ABase1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 6; + } + virtual int abase1() { + return 5; + } + virtual CBase1 *cloneit() { + return new Derived2(*this); + } + void derived2() { + } + }; + + struct Derived3 : ABase1, CBase1, CBase2 { + virtual int cbase1y() { + return 7; + } + virtual int cbase2() { + return 8; + } + virtual int abase1() { + return 9; + } + virtual void cbase1x() { + } + virtual ABase1 *cloneit() { + return new Derived3(*this); + } + void derived3() { + } + }; + + struct Bottom1 : Derived1 { + virtual void cbase1x() { + return; + } + virtual int cbase1y() { + return 103; + } + virtual int cbase2() { + return 104; + } + }; + + struct Bottom2 : Derived2 { + virtual int cbase1y() { + return 206; + } + virtual int abase1() { + return 205; + } + }; + + struct Bottom3 : Derived3 { + virtual int cbase1y() { + return 307; + } + virtual int cbase2() { + return 308; + } + virtual int abase1() { + return 309; + } + }; + + typedef boost::shared_ptr ABase1_SharedPtr; + typedef boost::shared_ptr CBase1_SharedPtr; + typedef boost::shared_ptr CBase2_SharedPtr; + typedef boost::shared_ptr Derived1_SharedPtr; + typedef boost::shared_ptr Derived2_SharedPtr; + typedef boost::shared_ptr Derived3_SharedPtr; + typedef boost::shared_ptr Bottom1_SharedPtr; + typedef boost::shared_ptr Bottom2_SharedPtr; + typedef boost::shared_ptr Bottom3_SharedPtr; + + // Base classes as input + int InputValCBase1(CBase1 cb1) { + return cb1.cbase1y(); + } + int InputValCBase2(CBase2 cb2) { + return cb2.cbase2(); + } + + int InputPtrABase1(ABase1 *pab1) { + return pab1->abase1(); + } + int InputPtrCBase1(CBase1 *pcb1) { + return pcb1->cbase1y(); + } + int InputPtrCBase2(CBase2 *pcb2) { + return pcb2->cbase2(); + } + + int InputRefABase1(ABase1 &rab1) { + return rab1.abase1(); + } + int InputRefCBase1(CBase1 &rcb1) { + return rcb1.cbase1y(); + } + int InputRefCBase2(CBase2 &rcb2) { + return rcb2.cbase2(); + } + + int InputCPtrRefABase1(ABase1 *const& pab1) { + return pab1->abase1(); + } + int InputCPtrRefCBase1(CBase1 *const& pcb1) { + return pcb1->cbase1y(); + } + int InputCPtrRefCBase2(CBase2 *const& pcb2) { + return pcb2->cbase2(); + } + + int InputSharedPtrABase1(ABase1_SharedPtr pab1) { + return pab1->abase1(); + } + int InputSharedPtrCBase1(CBase1_SharedPtr pcb1) { + return pcb1->cbase1y(); + } + int InputSharedPtrCBase2(CBase2_SharedPtr pcb2) { + return pcb2->cbase2(); + } + + int InputSharedPtrRefABase1(ABase1_SharedPtr &pab1) { + return pab1->abase1(); + } + int InputSharedPtrRefCBase1(CBase1_SharedPtr &pcb1) { + return pcb1->cbase1y(); + } + int InputSharedPtrRefCBase2(CBase2_SharedPtr &pcb2) { + return pcb2->cbase2(); + } + + // Derived classes as input + int InputValDerived1(Derived1 d) { + return d.cbase1y() + d.cbase2(); + } + int InputValDerived2(Derived2 d) { + return d.cbase1y() + d.abase1(); + } + int InputValDerived3(Derived3 d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputRefDerived1(Derived1 &d) { + return d.cbase1y() + d.cbase2(); + } + int InputRefDerived2(Derived2 &d) { + return d.cbase1y() + d.abase1(); + } + int InputRefDerived3(Derived3 &d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputPtrDerived1(Derived1 *d) { + return d->cbase1y() + d->cbase2(); + } + int InputPtrDerived2(Derived2 *d) { + return d->cbase1y() + d->abase1(); + } + int InputPtrDerived3(Derived3 *d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputCPtrRefDerived1(Derived1 *const& d) { + return d->cbase1y() + d->cbase2(); + } + int InputCPtrRefDerived2(Derived2 *const& d) { + return d->cbase1y() + d->abase1(); + } + int InputCPtrRefDerived3(Derived3 *const& d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputSharedPtrDerived1(Derived1_SharedPtr d) { + return d->cbase1y() + d->cbase2(); + } + int InputSharedPtrDerived2(Derived2_SharedPtr d) { + return d->cbase1y() + d->abase1(); + } + int InputSharedPtrDerived3(Derived3_SharedPtr d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputSharedPtrRefDerived1(Derived1_SharedPtr &d) { + return d->cbase1y() + d->cbase2(); + } + int InputSharedPtrRefDerived2(Derived2_SharedPtr &d) { + return d->cbase1y() + d->abase1(); + } + int InputSharedPtrRefDerived3(Derived3_SharedPtr &d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + // Bottom classes as input + int InputValBottom1(Bottom1 d) { + return d.cbase1y() + d.cbase2(); + } + int InputValBottom2(Bottom2 d) { + return d.cbase1y() + d.abase1(); + } + int InputValBottom3(Bottom3 d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputRefBottom1(Bottom1 &d) { + return d.cbase1y() + d.cbase2(); + } + int InputRefBottom2(Bottom2 &d) { + return d.cbase1y() + d.abase1(); + } + int InputRefBottom3(Bottom3 &d) { + return d.cbase1y() + d.cbase2() + d.abase1(); + } + + int InputPtrBottom1(Bottom1 *d) { + return d->cbase1y() + d->cbase2(); + } + int InputPtrBottom2(Bottom2 *d) { + return d->cbase1y() + d->abase1(); + } + int InputPtrBottom3(Bottom3 *d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputCPtrRefBottom1(Bottom1 *const& d) { + return d->cbase1y() + d->cbase2(); + } + int InputCPtrRefBottom2(Bottom2 *const& d) { + return d->cbase1y() + d->abase1(); + } + int InputCPtrRefBottom3(Bottom3 *const& d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputSharedPtrBottom1(Bottom1_SharedPtr d) { + return d->cbase1y() + d->cbase2(); + } + int InputSharedPtrBottom2(Bottom2_SharedPtr d) { + return d->cbase1y() + d->abase1(); + } + int InputSharedPtrBottom3(Bottom3_SharedPtr d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + int InputSharedPtrRefBottom1(Bottom1_SharedPtr &d) { + return d->cbase1y() + d->cbase2(); + } + int InputSharedPtrRefBottom2(Bottom2_SharedPtr &d) { + return d->cbase1y() + d->abase1(); + } + int InputSharedPtrRefBottom3(Bottom3_SharedPtr &d) { + return d->cbase1y() + d->cbase2() + d->abase1(); + } + + // Return pointers + CBase1 *MakePtrDerived1_CBase1() { + return new Derived1(); + } + CBase2 *MakePtrDerived1_CBase2() { + return new Derived1(); + } + CBase1 *MakePtrDerived2_CBase1() { + return new Derived2(); + } + ABase1 *MakePtrDerived2_ABase1() { + return new Derived2(); + } + ABase1 *MakePtrDerived3_ABase1() { + return new Derived3(); + } + CBase1 *MakePtrDerived3_CBase1() { + return new Derived3(); + } + CBase2 *MakePtrDerived3_CBase2() { + return new Derived3(); + } + + // Return references + CBase1 &MakeRefDerived1_CBase1() { + static Derived1 d; + return d; + } + CBase2 &MakeRefDerived1_CBase2() { + static Derived1 d; + return d; + } + CBase1 &MakeRefDerived2_CBase1() { + static Derived2 d; + return d; + } + ABase1 &MakeRefDerived2_ABase1() { + static Derived2 d; + return d; + } + ABase1 &MakeRefDerived3_ABase1() { + static Derived3 d; + return d; + } + CBase1 &MakeRefDerived3_CBase1() { + static Derived3 d; + return d; + } + CBase2 &MakeRefDerived3_CBase2() { + static Derived3 d; + return d; + } + + // Return by value (sliced objects) + CBase1 MakeValDerived1_CBase1() { + return Derived1(); + } + CBase2 MakeValDerived1_CBase2() { + return Derived1(); + } + CBase1 MakeValDerived2_CBase1() { + return Derived2(); + } + CBase1 MakeValDerived3_CBase1() { + return Derived3(); + } + CBase2 MakeValDerived3_CBase2() { + return Derived3(); + } + + // Return smart pointers + CBase1_SharedPtr MakeSharedPtrDerived1_CBase1() { + return CBase1_SharedPtr(new Derived1()); + } + CBase2_SharedPtr MakeSharedPtrDerived1_CBase2() { + return CBase2_SharedPtr(new Derived1()); + } + CBase1_SharedPtr MakeSharedPtrDerived2_CBase1() { + return CBase1_SharedPtr(new Derived2()); + } + ABase1_SharedPtr MakeSharedPtrDerived2_ABase1() { + return ABase1_SharedPtr(new Derived2()); + } + ABase1_SharedPtr MakeSharedPtrDerived3_ABase1() { + return ABase1_SharedPtr(new Derived3()); + } + CBase1_SharedPtr MakeSharedPtrDerived3_CBase1() { + return CBase1_SharedPtr(new Derived3()); + } + CBase2_SharedPtr MakeSharedPtrDerived3_CBase2() { + return CBase2_SharedPtr(new Derived3()); + } + + // Return smart pointer references + CBase1_SharedPtr MakeSharedPtrRefDerived1_CBase1() { + static CBase1_SharedPtr s(new Derived1()); + return s; + } + CBase2_SharedPtr MakeSharedPtrRefDerived1_CBase2() { + static CBase2_SharedPtr s(new Derived1()); + return s; + } + CBase1_SharedPtr MakeSharedPtrRefDerived2_CBase1() { + static CBase1_SharedPtr s(new Derived2()); + return s; + } + ABase1_SharedPtr MakeSharedPtrRefDerived2_ABase1() { + static ABase1_SharedPtr s(new Derived2()); + return s; + } + ABase1_SharedPtr MakeSharedPtrRefDerived3_ABase1() { + static ABase1_SharedPtr s(new Derived3()); + return s; + } + CBase1_SharedPtr MakeSharedPtrRefDerived3_CBase1() { + static CBase1_SharedPtr s(new Derived3()); + return s; + } + CBase2_SharedPtr MakeSharedPtrRefDerived3_CBase2() { + static CBase2_SharedPtr s(new Derived3()); + return s; + } +} + +%} diff --git a/Examples/test-suite/mzscheme/Makefile.in b/Examples/test-suite/mzscheme/Makefile.in index da92f76fd..3e15f8610 100644 --- a/Examples/test-suite/mzscheme/Makefile.in +++ b/Examples/test-suite/mzscheme/Makefile.in @@ -46,4 +46,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" mzscheme_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean diff --git a/Examples/test-suite/namespace_typemap.i b/Examples/test-suite/namespace_typemap.i index 8ead78c6c..9c74715f0 100644 --- a/Examples/test-suite/namespace_typemap.i +++ b/Examples/test-suite/namespace_typemap.i @@ -50,7 +50,7 @@ namespace test { PyComplex_ImagAsDouble($input)); } else { PyErr_SetString(PyExc_TypeError,"Expected test_complex.\n"); - return NULL; + SWIG_fail; } } %typemap(freearg) test::test_complex * { @@ -109,7 +109,11 @@ namespace test { #ifdef SWIGGO %typemap(gotype) string_class * "string" %typemap(in) string_class * { - $1 = new string_class($input.p); + char* buf = new char[$input.n + 1]; + memcpy(buf, $input.p, $input.n); + buf[$input.n] = '\0'; + $1 = new string_class(buf); + delete[] buf; } %typemap(freearg) string_class * { delete $1; @@ -238,7 +242,7 @@ namespace Split { $1 = PyInt_AsLong($input); if ($1 < 0) { PyErr_SetString(PyExc_ValueError,"domain error\n"); - return NULL; + SWIG_fail; } } #endif diff --git a/Examples/test-suite/nested.i b/Examples/test-suite/nested.i index 1d4710128..216ee4224 100644 --- a/Examples/test-suite/nested.i +++ b/Examples/test-suite/nested.i @@ -13,6 +13,18 @@ Also tests reported error when a #define placed in a deeply embedded struct/unio %rename(InUnNamed) OuterStructNamed::Inner_union_named; #endif +#if defined(SWIG_JAVASCRIPT_V8) + +%inline %{ +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for nested C class wrappers compiled as C++ code */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif +%} + +#endif + %inline %{ struct TestStruct { diff --git a/Examples/test-suite/nested_class.i b/Examples/test-suite/nested_class.i index ebfc65f3d..b10c33949 100644 --- a/Examples/test-suite/nested_class.i +++ b/Examples/test-suite/nested_class.i @@ -55,6 +55,10 @@ #pragma GCC diagnostic ignored "-Wpedantic" #endif +namespace bar { + int foo() { return 0; } +} + struct Outer { typedef int Integer; /////////////////////////////////////////// @@ -129,10 +133,16 @@ struct Outer { Integer x; } InnerClass4Typedef; +#ifdef _MSC_VER + int Outer::foo(){ return 1; } // should correctly ignore qualification here (#508) +#endif + typedef struct { Integer x; } InnerStruct4Typedef; + friend int bar::foo(); // should parse correctly (#508) + typedef union { Integer x; double y; diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index 8fde075a4..f1d7ff2c8 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -1,5 +1,17 @@ %module nested_extend_c +#if defined(SWIG_JAVASCRIPT_V8) + +%inline %{ +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for nested C class wrappers compiled as C++ code */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif +%} + +#endif + #if !defined(SWIGOCTAVE) && !defined(SWIG_JAVASCRIPT_V8) %extend hiA { hiA() { @@ -98,5 +110,9 @@ typedef struct { static struct { int i; } THING; + +int useThing() { + return THING.i; +} %} diff --git a/Examples/test-suite/nested_ignore.i b/Examples/test-suite/nested_ignore.i new file mode 100644 index 000000000..e271eca7d --- /dev/null +++ b/Examples/test-suite/nested_ignore.i @@ -0,0 +1,24 @@ +%module nested_ignore +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) B::C::D; + +%rename($ignore) B::C; + +%inline %{ +namespace B { + class C { + public: + struct D { + }; + }; + + class E { + public: + typedef C::D D; + }; + + struct F + { + const E::D foo(){ return E::D(); } + }; +} +%} diff --git a/Examples/test-suite/nested_structs.i b/Examples/test-suite/nested_structs.i index f4f7a275a..c70924958 100644 --- a/Examples/test-suite/nested_structs.i +++ b/Examples/test-suite/nested_structs.i @@ -1,5 +1,17 @@ %module nested_structs +#if defined(SWIG_JAVASCRIPT_V8) + +%inline %{ +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for nested C class wrappers compiled as C++ code */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif +%} + +#endif + // bug #491476 %inline %{ struct Outer { diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index 0956fcbc4..ecdf32e9f 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -74,4 +74,4 @@ include $(srcdir)/../common.mk @rm -f $*.ml $*.mli; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" ocaml_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' ocaml_clean diff --git a/Examples/test-suite/octave/Makefile.in b/Examples/test-suite/octave/Makefile.in index fbffd240c..be47904e2 100644 --- a/Examples/test-suite/octave/Makefile.in +++ b/Examples/test-suite/octave/Makefile.in @@ -68,7 +68,7 @@ run_testcase = \ @rm -f $*.m; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" octave_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' octave_clean cvsignore: @echo '*wrap* *.mc *.so *.dll *.exp *.lib' diff --git a/Examples/test-suite/octave/empty_c_runme.m b/Examples/test-suite/octave/empty_c_runme.m new file mode 100644 index 000000000..81264deb1 --- /dev/null +++ b/Examples/test-suite/octave/empty_c_runme.m @@ -0,0 +1,2 @@ +empty_c + diff --git a/Examples/test-suite/octave/li_boost_shared_ptr_runme.m b/Examples/test-suite/octave/li_boost_shared_ptr_runme.m index a9f4a82c0..1da0a5725 100644 --- a/Examples/test-suite/octave/li_boost_shared_ptr_runme.m +++ b/Examples/test-suite/octave/li_boost_shared_ptr_runme.m @@ -503,7 +503,6 @@ function runtest() #KTODO cvar.GlobalPointer = None # plain reference - kglobal; k = Klass("global reference"); cvar.GlobalReference = k; verifyCount(1, k) diff --git a/Examples/test-suite/octave/li_carrays_cpp_runme.m b/Examples/test-suite/octave/li_carrays_cpp_runme.m new file mode 100644 index 000000000..d5b92139e --- /dev/null +++ b/Examples/test-suite/octave/li_carrays_cpp_runme.m @@ -0,0 +1,10 @@ +li_carrays_cpp + +d = doubleArray(10); + +d(0) = 7; +d(5) = d(0) + 3; + +if (d(5) + d(0) != 17) + error +endif diff --git a/Examples/test-suite/octave/li_cpointer_cpp_runme.m b/Examples/test-suite/octave/li_cpointer_cpp_runme.m new file mode 100644 index 000000000..463cf44f8 --- /dev/null +++ b/Examples/test-suite/octave/li_cpointer_cpp_runme.m @@ -0,0 +1,12 @@ +li_cpointer_cpp + + +p = new_intp(); +intp_assign(p,3); + +if (intp_value(p) != 3) + error +endif + +delete_intp(p); + diff --git a/Examples/test-suite/octave/overload_extendc_runme.m b/Examples/test-suite/octave/overload_extend2_runme.m similarity index 88% rename from Examples/test-suite/octave/overload_extendc_runme.m rename to Examples/test-suite/octave/overload_extend2_runme.m index fec586d4f..6db6b66bb 100644 --- a/Examples/test-suite/octave/overload_extendc_runme.m +++ b/Examples/test-suite/octave/overload_extend2_runme.m @@ -1,6 +1,6 @@ -overload_extendc +overload_extend2 -f = overload_extendc.Foo(); +f = overload_extend2.Foo(); if (f.test(3) != 1) error endif diff --git a/Examples/test-suite/octave/overload_extend_c_runme.m b/Examples/test-suite/octave/overload_extend_c_runme.m new file mode 100644 index 000000000..aa6bb5b5b --- /dev/null +++ b/Examples/test-suite/octave/overload_extend_c_runme.m @@ -0,0 +1,19 @@ +overload_extend_c + +f = overload_extend_c.Foo(); +if (f.test() != 0) + error +endif +if (f.test(3) != 1) + error +endif +if (f.test("hello") != 2) + error +endif +if (f.test(3,2) != 5) + error +endif +if (f.test(3.1)-.1 != 1003) # :) + error +endif + diff --git a/Examples/test-suite/operator_overload.i b/Examples/test-suite/operator_overload.i index 90f767a84..af884e5b4 100644 --- a/Examples/test-suite/operator_overload.i +++ b/Examples/test-suite/operator_overload.i @@ -73,6 +73,10 @@ see bottom for a set of possible tests %rename(OrOperator) operator ||; #endif +#if defined(SWIGPYTHON) +%feature("python:slot", "tp_str", functype="reprfunc") Op::__str__; +#endif + #ifdef SWIGD // Due to the way operator overloading is implemented in D1 and D2, the prefix // increment/decrement operators (D1) resp. the postfix ones (D2) are ignored. @@ -89,8 +93,6 @@ see bottom for a set of possible tests #include /* for named logical operator, eg 'operator or' */ #endif -#include - class Op { public: int i; @@ -109,11 +111,11 @@ public: return *this; } // +=,-=... are member fns - void operator+=(const Op& o){ i+=o.i;} - void operator-=(const Op& o){ i-=o.i;} - void operator*=(const Op& o){ i*=o.i;} - void operator/=(const Op& o){ i/=o.i;} - void operator%=(const Op& o){ i%=o.i;} + Op &operator+=(const Op& o){ i+=o.i; return *this; } + Op &operator-=(const Op& o){ i-=o.i; return *this; } + Op &operator*=(const Op& o){ i*=o.i; return *this; } + Op &operator/=(const Op& o){ i/=o.i; return *this; } + Op &operator%=(const Op& o){ i%=o.i; return *this; } // the +,-,*,... are friends // (just to make life harder) friend Op operator+(const Op& a,const Op& b){return Op(a.i+b.i);} @@ -245,8 +247,8 @@ public: %{ - -#include +#include +#define ASSERT(X) { if (!(X)) { throw std::runtime_error(#X); } } void Op::sanity_check() { @@ -258,66 +260,66 @@ void Op::sanity_check() Op dd=d; // assignment operator // test equality - assert(a!=b); - assert(b==c); - assert(a!=d); - assert(d==dd); + ASSERT(a!=b); + ASSERT(b==c); + ASSERT(a!=d); + ASSERT(d==dd); // test < - assert(a=c); - assert(b>d); - assert(b>=d); + ASSERT(a=c); + ASSERT(b>d); + ASSERT(b>=d); // test += Op e=3; e+=d; - assert(e==b); + ASSERT(e==b); e-=c; - assert(e==a); + ASSERT(e==a); e=Op(1); e*=b; - assert(e==c); + ASSERT(e==c); e/=d; - assert(e==d); + ASSERT(e==d); e%=c; - assert(e==d); + ASSERT(e==d); // test + Op f(1),g(1); - assert(f+g==Op(2)); - assert(f-g==Op(0)); - assert(f*g==Op(1)); - assert(f/g==Op(1)); - assert(f%g==Op(0)); + ASSERT(f+g==Op(2)); + ASSERT(f-g==Op(0)); + ASSERT(f*g==Op(1)); + ASSERT(f/g==Op(1)); + ASSERT(f%g==Op(0)); // test unary operators - assert(!a==true); - assert(!b==false); - assert(-a==a); - assert(-b==Op(-5)); + ASSERT(!a==true); + ASSERT(!b==false); + ASSERT(-a==a); + ASSERT(-b==Op(-5)); // test [] Op h=3; - assert(h[0]==3); - assert(h[1]==0); + ASSERT(h[0]==3); + ASSERT(h[1]==0); h[0]=2; // set - assert(h[0]==2); + ASSERT(h[0]==2); h[1]=2; // ignored - assert(h[0]==2); - assert(h[1]==0); + ASSERT(h[0]==2); + ASSERT(h[1]==0); // test () Op i=3; - assert(i()==3); - assert(i(1)==4); - assert(i(1,2)==6); + ASSERT(i()==3); + ASSERT(i(1)==4); + ASSERT(i(1,2)==6); // plus add some code to check the __str__ fn - //assert(str(Op(1))=="Op(1)"); - //assert(str(Op(-3))=="Op(-3)"); + //ASSERT(str(Op(1))=="Op(1)"); + //ASSERT(str(Op(-3))=="Op(-3)"); // test ++ and -- Op j(100); @@ -325,36 +327,36 @@ void Op::sanity_check() { Op newOp = j++; int newInt = original++; - assert(j.i == original); - assert(newOp.i == newInt); + ASSERT(j.i == original); + ASSERT(newOp.i == newInt); } { Op newOp = j--; int newInt = original--; - assert(j.i == original); - assert(newOp.i == newInt); + ASSERT(j.i == original); + ASSERT(newOp.i == newInt); } { Op newOp = ++j; int newInt = ++original; - assert(j.i == original); - assert(newOp.i == newInt); + ASSERT(j.i == original); + ASSERT(newOp.i == newInt); } { Op newOp = --j; int newInt = --original; - assert(j.i == original); - assert(newOp.i == newInt); + ASSERT(j.i == original); + ASSERT(newOp.i == newInt); } // cast operators Op k=3; int check_k = k; - assert (check_k == 3); + ASSERT (check_k == 3); Op l=4; double check_l = l; - assert (check_l == 4); + ASSERT (check_l == 4); } %} diff --git a/Examples/test-suite/overload_extendc.i b/Examples/test-suite/overload_extend2.i similarity index 94% rename from Examples/test-suite/overload_extendc.i rename to Examples/test-suite/overload_extend2.i index 1c1dd00b6..f91738607 100644 --- a/Examples/test-suite/overload_extendc.i +++ b/Examples/test-suite/overload_extend2.i @@ -1,4 +1,4 @@ -%module overload_extendc +%module overload_extend2 %typemap(default) int int2 "$1=1000;"; diff --git a/Examples/test-suite/overload_extend_c.i b/Examples/test-suite/overload_extend_c.i new file mode 100644 index 000000000..77a9287a2 --- /dev/null +++ b/Examples/test-suite/overload_extend_c.i @@ -0,0 +1,3 @@ +%module overload_extend_c + +%include "overload_extend.i" diff --git a/Examples/test-suite/perl5/Makefile.in b/Examples/test-suite/perl5/Makefile.in index ccd12d6e4..48d5fa5d1 100644 --- a/Examples/test-suite/perl5/Makefile.in +++ b/Examples/test-suite/perl5/Makefile.in @@ -13,14 +13,12 @@ top_builddir = @top_builddir@ CPP_TEST_CASES += \ primitive_types \ - li_cdata \ li_cstring \ - li_cdata_carrays \ + li_cdata_carrays_cpp \ li_reference \ director_nestedmodule \ C_TEST_CASES += \ - li_cdata \ li_cstring \ li_cdata_carrays \ @@ -60,4 +58,4 @@ run_testcase = \ @rm -f $*.pm; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" perl5_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/test-suite/perl5/char_binary_runme.pl b/Examples/test-suite/perl5/char_binary_runme.pl index 4c50ee700..f97d740a6 100644 --- a/Examples/test-suite/perl5/char_binary_runme.pl +++ b/Examples/test-suite/perl5/char_binary_runme.pl @@ -1,14 +1,16 @@ use strict; use warnings; -use Test::More tests => 7; +use Test::More tests => 10; BEGIN { use_ok('char_binary') } require_ok('char_binary'); my $t = char_binary::Test->new(); is($t->strlen('hile'), 4, "string typemap"); +is($t->ustrlen('hile'), 4, "unsigned string typemap"); is($t->strlen("hil\0"), 4, "string typemap"); +is($t->ustrlen("hil\0"), 4, "unsigned string typemap"); # # creating a raw char* @@ -22,6 +24,7 @@ char_binary::pchar_setitem($pc, 4, 0); is($t->strlen($pc), 4, "string typemap"); +is($t->ustrlen($pc), 4, "unsigned string typemap"); $char_binary::var_pchar = $pc; is($char_binary::var_pchar, "hola", "pointer case"); diff --git a/Examples/test-suite/perl5/li_carrays_cpp_runme.pl b/Examples/test-suite/perl5/li_carrays_cpp_runme.pl new file mode 100644 index 000000000..17019253e --- /dev/null +++ b/Examples/test-suite/perl5/li_carrays_cpp_runme.pl @@ -0,0 +1,72 @@ +#!/usr/bin/perl +use strict; +use warnings; +use Test::More tests => 34; +BEGIN { use_ok('li_carrays_cpp') } +require_ok('li_carrays_cpp'); + +# array_class +{ + my $length = 5; + my $xyArray = new li_carrays_cpp::XYArray($length); + for (my $i=0; $i<$length; $i++) { + my $xy = $xyArray->getitem($i); + $xy->{x} = $i*10; + $xy->{y} = $i*100; + $xyArray->setitem($i, $xy); + } + for (my $i=0; $i<$length; $i++) { + is($xyArray->getitem($i)->{x}, $i*10); + is($xyArray->getitem($i)->{y}, $i*100); + } +} + +{ + # global array variable + my $length = 3; + my $xyArrayPointer = $li_carrays_cpp::globalXYArray; + my $xyArray = li_carrays_cpp::XYArray::frompointer($xyArrayPointer); + for (my $i=0; $i<$length; $i++) { + my $xy = $xyArray->getitem($i); + $xy->{x} = $i*10; + $xy->{y} = $i*100; + $xyArray->setitem($i, $xy); + } + for (my $i=0; $i<$length; $i++) { + is($xyArray->getitem($i)->{x}, $i*10); + is($xyArray->getitem($i)->{y}, $i*100); + } +} + +# array_functions +{ + my $length = 5; + my $abArray = li_carrays_cpp::new_ABArray($length); + for (my $i=0; $i<$length; $i++) { + my $ab = li_carrays_cpp::ABArray_getitem($abArray, $i); + $ab->{a} = $i*10; + $ab->{b} = $i*100; + li_carrays_cpp::ABArray_setitem($abArray, $i, $ab); + } + for (my $i=0; $i<$length; $i++) { + is(li_carrays_cpp::ABArray_getitem($abArray, $i)->{a}, $i*10); + is(li_carrays_cpp::ABArray_getitem($abArray, $i)->{b}, $i*100); + } + li_carrays_cpp::delete_ABArray($abArray); +} + +{ + # global array variable + my $length = 3; + my $abArray = $li_carrays_cpp::globalABArray; + for (my $i=0; $i<$length; $i++) { + my $ab = li_carrays_cpp::ABArray_getitem($abArray, $i); + $ab->{a} = $i*10; + $ab->{b} = $i*100; + li_carrays_cpp::ABArray_setitem($abArray, $i, $ab); + } + for (my $i=0; $i<$length; $i++) { + is(li_carrays_cpp::ABArray_getitem($abArray, $i)->{a}, $i*10); + is(li_carrays_cpp::ABArray_getitem($abArray, $i)->{b}, $i*100); + } +} diff --git a/Examples/test-suite/perl5/li_cdata_carrays_cpp_runme.pl b/Examples/test-suite/perl5/li_cdata_carrays_cpp_runme.pl new file mode 100644 index 000000000..34b5e19b4 --- /dev/null +++ b/Examples/test-suite/perl5/li_cdata_carrays_cpp_runme.pl @@ -0,0 +1,14 @@ +use strict; +use warnings; +use Test::More tests => 4; +BEGIN { use_ok('li_cdata_carrays_cpp') } +require_ok('li_cdata_carrays_cpp'); + +my $ia = li_cdata_carrays_cpp::intArray->new(5); +for (0..4) { + $ia->setitem($_, $_**2); +} +ok(1, "setitems"); +my $x = pack q{I5}, map $_**2, (0..4); +my $y = li_cdata_carrays_cpp::cdata_int($ia->cast, 5); +is($x, $y, "carrays"); diff --git a/Examples/test-suite/perl5/overload_simple_runme.pl b/Examples/test-suite/perl5/overload_simple_runme.pl index 624d428c6..57a585a22 100644 --- a/Examples/test-suite/perl5/overload_simple_runme.pl +++ b/Examples/test-suite/perl5/overload_simple_runme.pl @@ -2,7 +2,7 @@ use overload_simple; use vars qw/$DOWARN/; use strict; -use Test::More tests => 75; +use Test::More tests => 97; pass("loaded"); @@ -196,3 +196,40 @@ is(overload_simple::int_object(1), 1, "int_object(1)"); is(overload_simple::int_object(0), 0, "int_object(0)"); is(overload_simple::int_object(undef), 999, "int_object(Spam*)"); is(overload_simple::int_object($s), 999, "int_object(Spam*)"); + +# some of this section is duplication of above tests, but I want to see +# parity with the coverage in wrapmacro_runme.pl. + +sub check { + my($args, $want) = @_; + my($s, $rslt) = defined $want ? ($want, "bar:$want") : ('*boom*', undef); + is(eval("overload_simple::Spam::bar($args)"), $rslt, "bar($args) => $s"); +} + +# normal use patterns +check("11", 'int'); +check("11.0", 'double'); +check("'11'", 'char *'); +check("'11.0'", 'char *'); +check("-13", 'int'); +check("-13.0", 'double'); +check("'-13'", 'char *'); +check("'-13.0'", 'char *'); + +check("' '", 'char *'); +check("' 11 '", 'char *'); +# TypeError explosions +check("\\*STDIN", undef); +check("[]", undef); +check("{}", undef); +check("sub {}", undef); + +# regression cases +check("''", 'char *'); +check("' 11'", 'char *'); +check("' 11.0'", 'char *'); +check("' -11.0'", 'char *'); +check("\"11\x{0}\"", 'char *'); +check("\"\x{0}\"", 'char *'); +check("\"\x{9}11\x{0}this is not eleven.\"", 'char *'); +check("\"\x{9}11.0\x{0}this is also not eleven.\"", 'char *'); diff --git a/Examples/test-suite/perl5/wrapmacro_runme.pl b/Examples/test-suite/perl5/wrapmacro_runme.pl index 8e0154057..f2478b51b 100644 --- a/Examples/test-suite/perl5/wrapmacro_runme.pl +++ b/Examples/test-suite/perl5/wrapmacro_runme.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl use strict; use warnings; -use Test::More tests => 5; +use Test::More tests => 27; BEGIN { use_ok('wrapmacro') } require_ok('wrapmacro'); @@ -12,3 +12,44 @@ my $b = -1; is(wrapmacro::maximum($a,$b), 2); is(wrapmacro::maximum($a/7.0, -$b*256), 256); is(wrapmacro::GUINT16_SWAP_LE_BE_CONSTANT(1), 256); + +# some of this section is duplication of above tests, but I want to see +# parity with the coverage in overload_simple_runme.pl. + +sub check { + my($args, $rslt) = @_; + my $s = defined $rslt ? $rslt : '*boom*'; + is(eval("wrapmacro::maximum($args)"), $rslt, "max($args) => $s"); +} + +# normal use patterns +check("0, 11", 11); +check("0, 11.0", 11); +check("0, '11'", 11); +check("0, '11.0'", 11); +check("11, -13", 11); +check("11, -13.0", 11); +{ local $TODO = 'strtoull() handles /^\s*-\d+$/ amusingly'; +check("11, '-13'", 11); +} +check("11, '-13.0'", 11); + +# TypeError explosions +check("0, ' '", undef); +check("0, ' 11 '", undef); +check("0, \\*STDIN", undef); +check("0, []", undef); +check("0, {}", undef); +check("0, sub {}", undef); + +# regression cases +{ local $TODO = 'strtol() and friends have edge cases we should guard against'; +check("-11, ''", undef); +check("0, ' 11'", undef); +check("0, ' 11.0'", undef); +check("-13, ' -11.0'", undef); +check("0, \"11\x{0}\"", undef); +check("0, \"\x{0}\"", undef); +check("0, \"\x{9}11\x{0}this is not eleven.\"", undef); +check("0, \"\x{9}11.0\x{0}this is also not eleven.\"", undef); +} diff --git a/Examples/test-suite/php/Makefile.in b/Examples/test-suite/php/Makefile.in index c3f8af5cb..c554e2b17 100644 --- a/Examples/test-suite/php/Makefile.in +++ b/Examples/test-suite/php/Makefile.in @@ -10,6 +10,8 @@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ CPP_TEST_CASES += \ + callback \ + li_factory \ php_iterator \ php_namewarn_rename \ @@ -59,9 +61,9 @@ missingtests: missingcpptests missingctests # found, runs testcase.php, except for multicpptests. run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL="$(RUNTOOL)" php_run; \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL='$(RUNTOOL)' php_run; \ elif [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php -a ! -f $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list ]; then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php RUNTOOL="$(RUNTOOL)" php_run; \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php RUNTOOL='$(RUNTOOL)' php_run; \ fi # Clean: remove the generated .php file @@ -69,7 +71,7 @@ run_testcase = \ @rm -f $*.php php_$*.h clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" php_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' php_clean rm -f clientdata_prop_a.php clientdata_prop_b.php php_clientdata_prop_a.h php_clientdata_prop_b.h rm -f import_stl_a.php import_stl_b.php php_import_stl_a.h php_import_stl_b.h rm -f imports_a.php imports_b.php php_imports_a.h php_imports_b.h diff --git a/Examples/test-suite/php/autodoc_runme.php b/Examples/test-suite/php/autodoc_runme.php deleted file mode 100644 index f2e19d3cb..000000000 --- a/Examples/test-suite/php/autodoc_runme.php +++ /dev/null @@ -1,9 +0,0 @@ - diff --git a/Examples/test-suite/php/callback_runme.php b/Examples/test-suite/php/callback_runme.php new file mode 100644 index 000000000..fefa32502 --- /dev/null +++ b/Examples/test-suite/php/callback_runme.php @@ -0,0 +1,9 @@ + diff --git a/Examples/test-suite/php/cpp_basic_runme.php b/Examples/test-suite/php/cpp_basic_runme.php new file mode 100644 index 000000000..6a8522e3e --- /dev/null +++ b/Examples/test-suite/php/cpp_basic_runme.php @@ -0,0 +1,20 @@ +func_ptr = get_func1_ptr(); +check::equal(test_func_ptr($f, 7), 2*7*3, "get_func1_ptr() didn't work"); +$f->func_ptr = get_func2_ptr(); +check::equal(test_func_ptr($f, 7), -7*3, "get_func2_ptr() didn't work"); + +check::done(); +?> diff --git a/Examples/test-suite/php/cpp_static_runme.php b/Examples/test-suite/php/cpp_static_runme.php index e1cc3e733..9b436b87c 100644 --- a/Examples/test-suite/php/cpp_static_runme.php +++ b/Examples/test-suite/php/cpp_static_runme.php @@ -4,11 +4,11 @@ require "tests.php"; require "cpp_static.php"; // New functions -check::functions(array(staticfunctiontest_static_func,staticfunctiontest_static_func_2,staticfunctiontest_static_func_3)); +check::functions(array(staticfunctiontest_static_func,staticfunctiontest_static_func_2,staticfunctiontest_static_func_3,is_python_builtin)); // New classes -check::classes(array(StaticMemberTest,StaticFunctionTest)); +check::classes(array(StaticMemberTest,StaticFunctionTest,cpp_static,StaticBase,StaticDerived)); // New vars -check::globals(array(staticmembertest_static_int)); +check::globals(array(staticmembertest_static_int,staticbase_statty,staticderived_statty)); check::done(); ?> diff --git a/Examples/test-suite/php/director_pass_by_value_runme.php b/Examples/test-suite/php/director_pass_by_value_runme.php new file mode 100644 index 000000000..8a8b84d67 --- /dev/null +++ b/Examples/test-suite/php/director_pass_by_value_runme.php @@ -0,0 +1,24 @@ +call_virtualMethod(new director_pass_by_value_Derived()); +$ret = $passByVal->getVal(); +if ($ret != 0x12345678) { + check::fail("Bad return value, got " . dechex($ret)); +} + +check::done(); +?> diff --git a/Examples/test-suite/php/director_thread_runme.php b/Examples/test-suite/php/director_thread_runme.php index 809dec3e2..ab0563213 100644 --- a/Examples/test-suite/php/director_thread_runme.php +++ b/Examples/test-suite/php/director_thread_runme.php @@ -3,7 +3,8 @@ require "tests.php"; require "director_thread.php"; -# Fails in a ZTS-build of PHP - see: https://github.com/swig/swig/pull/155 +# Fails in a ZTS-build of PHP5 - see: https://github.com/swig/swig/pull/155 +# FIXME: Does this still fail in a threaded build of PHP7? exit(0); // No new functions diff --git a/Examples/test-suite/php/li_carrays_cpp_runme.php b/Examples/test-suite/php/li_carrays_cpp_runme.php new file mode 100644 index 000000000..3be09ca8c --- /dev/null +++ b/Examples/test-suite/php/li_carrays_cpp_runme.php @@ -0,0 +1,22 @@ +setitem(0, 7); +$d->setitem(5, $d->getitem(0) + 3); +check::equal($d->getitem(0) + $d->getitem(5), 17., "7+10==17"); + +check::done(); +?> diff --git a/Examples/test-suite/php/preproc_constants_c_runme.php b/Examples/test-suite/php/preproc_constants_c_runme.php new file mode 100644 index 000000000..af9b76e1c --- /dev/null +++ b/Examples/test-suite/php/preproc_constants_c_runme.php @@ -0,0 +1,66 @@ + diff --git a/Examples/test-suite/php/preproc_constants_runme.php b/Examples/test-suite/php/preproc_constants_runme.php new file mode 100644 index 000000000..5c9119b3e --- /dev/null +++ b/Examples/test-suite/php/preproc_constants_runme.php @@ -0,0 +1,65 @@ + diff --git a/Examples/test-suite/php/swig_exception_runme.php b/Examples/test-suite/php/swig_exception_runme.php new file mode 100644 index 000000000..76641996e --- /dev/null +++ b/Examples/test-suite/php/swig_exception_runme.php @@ -0,0 +1,33 @@ +throwException(); + check::fail("Exception wasn't thrown"); +} catch (Exception $e) { + if ($e->getMessage() != "OK") { + check::fail("Exception getMessage() should be \"OK\", actually \"".$e->getMessage()."\""); + } +} + +# ----- Delete everything ----- + +$c = NULL; +$s = NULL; +$e = NULL; + +if (Shape::nshapes() != 0) { + check::fail("Shape::nshapes() should be 0, actually ".Shape::nshapes()); +} + +?> diff --git a/Examples/test-suite/php/tests.php b/Examples/test-suite/php/tests.php index 57c5c4788..d3fd66868 100644 --- a/Examples/test-suite/php/tests.php +++ b/Examples/test-suite/php/tests.php @@ -35,8 +35,9 @@ class check { foreach($_original_functions[internal] as $func) unset($df[$func]); // Now chop out any get/set accessors foreach(array_keys($df) as $func) - if ((GETSET && ereg('_[gs]et$',$func)) || ereg('^new_', $func) - || ereg('_(alter|get)_newobject$', $func)) + if ((GETSET && preg_match('/_[gs]et$/', $func)) || + preg_match('/^new_/', $func) || + preg_match('/_(alter|get)_newobject$/', $func)) $extrags[]=$func; else $extra[]=$func; // $extra=array_keys($df); @@ -52,7 +53,8 @@ class check { if (GETSET) { $_extra=array(); foreach(check::get_extra_functions(false,1) as $global) { - if (ereg('^(.*)_[sg]et$',$global,$match)) $_extra[$match[1]]=1; + if (preg_match('/^(.*)_[sg]et$/', $global, $match)) + $_extra[$match[1]] = 1; } $extra=array_keys($_extra); } else { @@ -61,7 +63,8 @@ class check { $df=array_flip(array_keys($GLOBALS)); foreach($_original_globals as $func) unset($df[$func]); // MASK xxxx_LOADED__ variables - foreach(array_keys($df) as $func) if (ereg('_LOADED__$',$func)) unset($df[$func]); + foreach(array_keys($df) as $func) + if (preg_match('/_LOADED__$/', $func)) unset($df[$func]); $extra=array_keys($df); } } @@ -185,7 +188,8 @@ class check { } function functionref($a,$type,$message) { - if (! eregi("^_[a-f0-9]+$type$",$a)) return check::fail($message); + if (! preg_match("/^_[a-f0-9]+$type$/i", $a)) + return check::fail($message); return TRUE; } @@ -196,7 +200,8 @@ class check { function resource($a,$b,$message) { $resource=trim(check::var_dump($a)); - if (! eregi("^resource\([0-9]+\) of type \($b\)",$resource)) return check::fail($message); + if (! preg_match("/^resource\([0-9]+\) of type \($b\)/i", $resource)) + return check::fail($message); return TRUE; } diff --git a/Examples/test-suite/php5/Makefile.in b/Examples/test-suite/php5/Makefile.in new file mode 100644 index 000000000..391ca2c53 --- /dev/null +++ b/Examples/test-suite/php5/Makefile.in @@ -0,0 +1,80 @@ +####################################################################### +# Makefile for php5 test-suite +####################################################################### + +LANGUAGE = php5 +SCRIPTSUFFIX = _runme.php + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +CPP_TEST_CASES += \ + callback \ + li_factory \ + php_iterator \ + php_namewarn_rename \ + +include $(srcdir)/../common.mk + +# Overridden variables here +TARGETPREFIX =# Should be php_ for Windows, empty otherwise + +# Custom tests - tests with additional commandline options +prefix.cpptest: SWIGOPT += -prefix Project + +# write out tests without a _runme.php +missingcpptests: + for test in $(CPP_TEST_CASES) ; do test -f $${test}_runme.php || echo $${test}; done + +missingctests: + for test in $(C_TEST_CASES) ; do test -f $${test}_runme.php || echo $${test}; done + +missingtests: missingcpptests missingctests + +# Rules for the different types of tests +%.cpptest: + $(setup) + +$(swig_and_compile_cpp) + +$(run_testcase) + +%.ctest: + $(setup) + +$(swig_and_compile_c) + +$(run_testcase) + +%.multicpptest: + $(setup) + +$(swig_and_compile_multi_cpp) + +$(run_testcase) + +# Smart target +%.test: + @echo ' $(C_TEST_CASES) '|grep -F -v ' $* ' >/dev/null ||\ + $(MAKE) $*.ctest + @echo ' $(CPP_TEST_CASES) '|grep -F -v ' $* ' >/dev/null ||\ + $(MAKE) $*.cpptest + @echo ' $(MULTI_CPP_TEST_CASES) '|grep -F -v ' $* ' >/dev/null ||\ + $(MAKE) $*.multicpptest + +# Runs the testcase. Tries to run testcase_runme.php, and if that's not +# found, runs testcase.php, except for multicpptests. +run_testcase = \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP5_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL='$(RUNTOOL)' php5_run; \ + elif [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php -a ! -f $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list ]; then \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP5_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php RUNTOOL='$(RUNTOOL)' php5_run; \ + fi + +# Clean: remove the generated .php file +%.clean: + @rm -f $*.php php_$*.h + +clean: + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' php5_clean + rm -f clientdata_prop_a.php clientdata_prop_b.php php_clientdata_prop_a.h php_clientdata_prop_b.h + rm -f import_stl_a.php import_stl_b.php php_import_stl_a.h php_import_stl_b.h + rm -f imports_a.php imports_b.php php_imports_a.h php_imports_b.h + rm -f mod_a.php mod_b.php php_mod_a.h php_mod_b.h + rm -f multi_import_a.php multi_import_b.php php_multi_import_a.h php_multi_import_b.h + rm -f packageoption_a.php packageoption_b.php packageoption_c.php php_packageoption_a.h php_packageoption_b.h php_packageoption_c.h diff --git a/Examples/test-suite/php5/abstract_inherit_ok_runme.php b/Examples/test-suite/php5/abstract_inherit_ok_runme.php new file mode 100644 index 000000000..c2d86499b --- /dev/null +++ b/Examples/test-suite/php5/abstract_inherit_ok_runme.php @@ -0,0 +1,12 @@ +blah(),"spam object method"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/abstract_inherit_runme.php b/Examples/test-suite/php5/abstract_inherit_runme.php new file mode 100644 index 000000000..3554e6fd8 --- /dev/null +++ b/Examples/test-suite/php5/abstract_inherit_runme.php @@ -0,0 +1,14 @@ +blah(),"spam object method"); +//check::equal(0,Spam::blah($spam),"spam class method"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/add_link_runme.php b/Examples/test-suite/php5/add_link_runme.php new file mode 100644 index 000000000..7523bd604 --- /dev/null +++ b/Examples/test-suite/php5/add_link_runme.php @@ -0,0 +1,22 @@ +blah(); +check::is_a($foo_blah,foo); + +//fails, can't be called as a class method, should allow and make it nil? +//$class_foo_blah=foo::blah(); +//check::is_a($class_foo_blah,foo); + +check::done(); +?> diff --git a/Examples/test-suite/php5/argout_runme.php b/Examples/test-suite/php5/argout_runme.php new file mode 100644 index 000000000..33fbd8129 --- /dev/null +++ b/Examples/test-suite/php5/argout_runme.php @@ -0,0 +1,38 @@ + diff --git a/Examples/test-suite/php5/arrayptr_runme.php b/Examples/test-suite/php5/arrayptr_runme.php new file mode 100644 index 000000000..3b9baed05 --- /dev/null +++ b/Examples/test-suite/php5/arrayptr_runme.php @@ -0,0 +1,14 @@ + diff --git a/Examples/test-suite/php5/arrays_global_runme.php b/Examples/test-suite/php5/arrays_global_runme.php new file mode 100644 index 000000000..12a7806c9 --- /dev/null +++ b/Examples/test-suite/php5/arrays_global_runme.php @@ -0,0 +1,19 @@ + diff --git a/Examples/test-suite/php5/arrays_global_twodim_runme.php b/Examples/test-suite/php5/arrays_global_twodim_runme.php new file mode 100644 index 000000000..40ecf1719 --- /dev/null +++ b/Examples/test-suite/php5/arrays_global_twodim_runme.php @@ -0,0 +1,22 @@ + diff --git a/Examples/test-suite/php5/arrays_runme.php b/Examples/test-suite/php5/arrays_runme.php new file mode 100644 index 000000000..ae17d05e7 --- /dev/null +++ b/Examples/test-suite/php5/arrays_runme.php @@ -0,0 +1,18 @@ +array_c="abc"; +check::equal($as->array_c,"a",'$as->array_c=="a"'); +check::equal(isset($as->array_const_i),TRUE,'isset($as->array_const_i)'); + +check::done(); +?> diff --git a/Examples/test-suite/php5/arrays_scope_runme.php b/Examples/test-suite/php5/arrays_scope_runme.php new file mode 100644 index 000000000..c208b7518 --- /dev/null +++ b/Examples/test-suite/php5/arrays_scope_runme.php @@ -0,0 +1,16 @@ + diff --git a/Examples/test-suite/php5/callback_runme.php b/Examples/test-suite/php5/callback_runme.php new file mode 100644 index 000000000..fefa32502 --- /dev/null +++ b/Examples/test-suite/php5/callback_runme.php @@ -0,0 +1,9 @@ + diff --git a/Examples/test-suite/php5/casts_runme.php b/Examples/test-suite/php5/casts_runme.php new file mode 100644 index 000000000..10522dca4 --- /dev/null +++ b/Examples/test-suite/php5/casts_runme.php @@ -0,0 +1,18 @@ +hello(); + +check::done(); +?> diff --git a/Examples/test-suite/php5/char_strings_runme.php b/Examples/test-suite/php5/char_strings_runme.php new file mode 100644 index 000000000..e06ee9d2b --- /dev/null +++ b/Examples/test-suite/php5/char_strings_runme.php @@ -0,0 +1,43 @@ + diff --git a/Examples/test-suite/php5/class_ignore_runme.php b/Examples/test-suite/php5/class_ignore_runme.php new file mode 100644 index 000000000..d5ce36217 --- /dev/null +++ b/Examples/test-suite/php5/class_ignore_runme.php @@ -0,0 +1,16 @@ + diff --git a/Examples/test-suite/php5/conversion_namespace_runme.php b/Examples/test-suite/php5/conversion_namespace_runme.php new file mode 100644 index 000000000..e21ff7438 --- /dev/null +++ b/Examples/test-suite/php5/conversion_namespace_runme.php @@ -0,0 +1,13 @@ +toFoo(); +check::classname("foo",$foo); + +check::done(); +?> diff --git a/Examples/test-suite/php5/conversion_ns_template_runme.php b/Examples/test-suite/php5/conversion_ns_template_runme.php new file mode 100644 index 000000000..9702eedb7 --- /dev/null +++ b/Examples/test-suite/php5/conversion_ns_template_runme.php @@ -0,0 +1,10 @@ + diff --git a/Examples/test-suite/php5/conversion_runme.php b/Examples/test-suite/php5/conversion_runme.php new file mode 100644 index 000000000..1a10ff4f4 --- /dev/null +++ b/Examples/test-suite/php5/conversion_runme.php @@ -0,0 +1,13 @@ +toFoo(); +check::classname("foo",$foo); + +check::done(); +?> diff --git a/Examples/test-suite/php5/cpp11_strongly_typed_enumerations_runme.php b/Examples/test-suite/php5/cpp11_strongly_typed_enumerations_runme.php new file mode 100644 index 000000000..bee59b209 --- /dev/null +++ b/Examples/test-suite/php5/cpp11_strongly_typed_enumerations_runme.php @@ -0,0 +1,169 @@ +class1Test1(Enum1_Val5a), 13); +enumCheck($class1->class1Test2(Class1::Enum12_Val5c), 1121); +#enumCheck($class1.class1Test3(Class1::Struct1.Enum12_Val5f), 3121); + +enumCheck(globalTest1(Enum1_Val5a), 13); +enumCheck(globalTest2(Class1::Enum12_Val5c), 1121); +#enumCheck(globalTest3(Class1::Struct1.Enum12_Val5f), 3121); + +?> diff --git a/Examples/test-suite/php5/cpp_basic_runme.php b/Examples/test-suite/php5/cpp_basic_runme.php new file mode 100644 index 000000000..6a8522e3e --- /dev/null +++ b/Examples/test-suite/php5/cpp_basic_runme.php @@ -0,0 +1,20 @@ +func_ptr = get_func1_ptr(); +check::equal(test_func_ptr($f, 7), 2*7*3, "get_func1_ptr() didn't work"); +$f->func_ptr = get_func2_ptr(); +check::equal(test_func_ptr($f, 7), -7*3, "get_func2_ptr() didn't work"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/cpp_static_runme.php b/Examples/test-suite/php5/cpp_static_runme.php new file mode 100644 index 000000000..9b436b87c --- /dev/null +++ b/Examples/test-suite/php5/cpp_static_runme.php @@ -0,0 +1,14 @@ + diff --git a/Examples/test-suite/php5/director_abstract_runme.php b/Examples/test-suite/php5/director_abstract_runme.php new file mode 100644 index 000000000..ca3d676da --- /dev/null +++ b/Examples/test-suite/php5/director_abstract_runme.php @@ -0,0 +1,62 @@ +ping(), "MyFoo::ping()", "MyFoo::ping failed"); + +check::equal($a->pong(), "Foo::pong();MyFoo::ping()", "MyFoo::pong failed"); + +class MyExample1 extends Example1 { + function Color($r, $g, $b) { + return $r; + } +} + +class MyExample2 extends Example1 { + function Color($r, $g, $b) { + return $g; + } +} + +class MyExample3 extends Example1 { + function Color($r, $g, $b) { + return $b; + } +} + +$me1 = new MyExample1(); +check::equal($me1->Color(1, 2, 3), 1, "Example1_get_color failed"); + +$me2 = new MyExample2(1, 2); +check::equal($me2->Color(1, 2, 3), 2, "Example2_get_color failed"); + +$me3 = new MyExample3(); +check::equal($me3->Color(1, 2, 3), 3, "Example3_get_color failed"); + +$class = new ReflectionClass('Example1'); +check::equal($class->isAbstract(), true, "Example1 abstractness failed"); + +$class = new ReflectionClass('Example2'); +check::equal($class->isAbstract(), true, "Example2 abstractness failed"); + +$class = new ReflectionClass('Example3_i'); +check::equal($class->isAbstract(), true, "Example3_i abstractness failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_basic_runme.php b/Examples/test-suite/php5/director_basic_runme.php new file mode 100644 index 000000000..de6b50502 --- /dev/null +++ b/Examples/test-suite/php5/director_basic_runme.php @@ -0,0 +1,58 @@ +ping(), "PhpFoo::ping()", "ping failed"); + +check::equal($a->pong(), "Foo::pong();PhpFoo::ping()", "pong failed"); + +$b = new Foo(); + +check::equal($b->ping(), "Foo::ping()", "ping failed"); + +check::equal($b->pong(), "Foo::pong();Foo::ping()", "pong failed"); + +$a = new A1(1); + +check::equal($a->rg(2), 2, "rg failed"); + +class PhpClass extends MyClass { + function vmethod($b) { + $b->x = $b->x + 31; + return $b; + } +} + +$b = new Bar(3); +$d = new MyClass(); +$c = new PhpClass(); + +$cc = MyClass::get_self($c); +$dd = MyClass::get_self($d); + +$bc = $cc->cmethod($b); +$bd = $dd->cmethod($b); + +$cc->method($b); + +check::equal($bc->x, 34, "bc failed"); +check::equal($bd->x, 16, "bd failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_classic_runme.php b/Examples/test-suite/php5/director_classic_runme.php new file mode 100644 index 000000000..d2da1b1ba --- /dev/null +++ b/Examples/test-suite/php5/director_classic_runme.php @@ -0,0 +1,150 @@ +id(); + if ($debug) + print $ret . "\n"; + check::equal($ret, $expected, "#1 failed"); + + # Polymorphic call from C++ + $caller = new Caller(); + $caller->setCallback($person); + $ret = $caller->call(); + if ($debug) + print $ret . "\n"; + check::equal($ret, $expected, "#2 failed"); + + # Polymorphic call of object created in target language and passed to + # C++ and back again + $baseclass = $caller->baseClass(); + $ret = $baseclass->id(); + if ($debug) + print $ret . "\n"; + # TODO: Currently we do not track the dynamic type of returned + # objects, so in case it's possible that the dynamic type is not equal + # to the static type, we skip this check. + if (get_parent_class($person) === false) + check::equal($ret, $expected, "#3 failed"); + + $caller->resetCallback(); + if ($debug) + print "----------------------------------------\n"; +} + +$person = new Person(); +mycheck($person, "Person"); +unset($person); + +$person = new Child(); +mycheck($person, "Child"); +unset($person); + +$person = new GrandChild(); +mycheck($person, "GrandChild"); +unset($person); + +$person = new TargetLangPerson(); +mycheck($person, "TargetLangPerson"); +unset($person); + +$person = new TargetLangChild(); +mycheck($person, "TargetLangChild"); +unset($person); + +$person = new TargetLangGrandChild(); +mycheck($person, "TargetLangGrandChild"); +unset($person); + +# Semis - don't override id() in target language +$person = new TargetLangSemiPerson(); +mycheck($person, "Person"); +unset($person); + +$person = new TargetLangSemiChild(); +mycheck($person, "Child"); +unset($person); + +$person = new TargetLangSemiGrandChild(); +mycheck($person, "GrandChild"); +unset($person); + +# Orphans - don't override id() in C++ +$person = new OrphanPerson(); +mycheck($person, "Person"); +unset($person); + +$person = new OrphanChild(); +mycheck($person, "Child"); +unset($person); + +$person = new TargetLangOrphanPerson(); +mycheck($person, "TargetLangOrphanPerson"); +unset($person); + +$person = new TargetLangOrphanChild(); +mycheck($person, "TargetLangOrphanChild"); +unset($person); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_default_runme.php b/Examples/test-suite/php5/director_default_runme.php new file mode 100644 index 000000000..f97fc7425 --- /dev/null +++ b/Examples/test-suite/php5/director_default_runme.php @@ -0,0 +1,20 @@ + diff --git a/Examples/test-suite/php5/director_detect_runme.php b/Examples/test-suite/php5/director_detect_runme.php new file mode 100644 index 000000000..cc19c0302 --- /dev/null +++ b/Examples/test-suite/php5/director_detect_runme.php @@ -0,0 +1,55 @@ +val = $val; + } + + function get_value() { + $this->val = $this->val + 1; + return $this->val; + } + + function get_class() { + $this->val = $this->val + 1; + return new A(); + } + + function just_do_it() { + $this->val = $this->val + 1; + } + + /* clone is a reserved keyword */ + function clone_() { + return new MyBar($this->val); + } +} + +$b = new MyBar(); + +$f = $b->baseclass(); + +$v = $f->get_value(); +$a = $f->get_class(); +$f->just_do_it(); + +$c = $b->clone_(); +$vc = $c->get_value(); + +check::equal($v, 3, "f: Bad virtual detection"); +check::equal($b->val, 5, "b: Bad virtual detection"); +check::equal($vc, 6, "c: Bad virtual detection"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_enum_runme.php b/Examples/test-suite/php5/director_enum_runme.php new file mode 100644 index 000000000..8f6487a28 --- /dev/null +++ b/Examples/test-suite/php5/director_enum_runme.php @@ -0,0 +1,25 @@ +say_hi(director_enum::hello), $b->say_hello(director_enum::hi), "say failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_exception_runme.php b/Examples/test-suite/php5/director_exception_runme.php new file mode 100644 index 000000000..8b852c2ce --- /dev/null +++ b/Examples/test-suite/php5/director_exception_runme.php @@ -0,0 +1,127 @@ +msg = $a . $b; + } +} + +class MyFoo extends Foo { + function ping() { + throw new Exception("MyFoo::ping() EXCEPTION"); + } +} + +class MyFoo2 extends Foo { + function ping() { + return true; + } +} + +class MyFoo3 extends Foo { + function ping() { + throw new MyException("foo", "bar"); + } +} + +# Check that the Exception raised by MyFoo.ping() is returned by +# MyFoo.pong(). +$ok = 0; +$a = new MyFoo(); +# TODO: Currently we do not track the dynamic type of returned +# objects, so we skip the launder() call. +#$b = director_exception::launder($a); +$b = $a; +try { + $b->pong(); +} catch (Exception $e) { + $ok = 1; + check::equal($e->getMessage(), "MyFoo::ping() EXCEPTION", "Unexpected error message #1"); +} +check::equal($ok, 1, "Got no exception while expected one #1"); + +# Check that the director can return an exception which requires two +# arguments to the constructor, without mangling it. +$ok = 0; +$a = new MyFoo3(); +#$b = director_exception::launder($a); +$b = $a; +try { + $b->pong(); +} catch (Exception $e) { + $ok = 1; + check::equal($e->msg, "foobar", "Unexpected error message #2"); +} +check::equal($ok, 1, "Got no exception while expected one #2"); + +try { + throw new Exception2(); +} catch (Exception2 $e2) { +} + +try { + throw new Exception1(); +} catch (Exception1 $e1) { +} + +// Check that we can throw exceptions from director methods (this didn't used +// to work in all cases, as the exception gets "set" in PHP and the method +// then returns PHP NULL, which the directorout template may fail to convert. + +class Bad extends ReturnAllTypes { + function return_int() { throw new Exception("bad int"); } + function return_double() { throw new Exception("bad double"); } + function return_const_char_star() { throw new Exception("bad const_char_star"); } + function return_std_string() { throw new Exception("bad std_string"); } + function return_Bar() { throw new Exception("bad Bar"); } +} + +$bad = new Bad(); + +try { + $bad->call_int(); + check::fail("Exception wasn't propagated from Bad::return_int()"); +} catch (Exception $e) { + check::equal($e->getMessage(), "bad int", "propagated exception incorrect"); +} + +try { + $bad->call_double(); + check::fail("Exception wasn't propagated from Bad::return_double()"); +} catch (Exception $e) { + check::equal($e->getMessage(), "bad double", "propagated exception incorrect"); +} + +try { + $bad->call_const_char_star(); + check::fail("Exception wasn't propagated from Bad::return_const_char_star()"); +} catch (Exception $e) { + check::equal($e->getMessage(), "bad const_char_star", "propagated exception incorrect"); +} + +try { + $bad->call_std_string(); + check::fail("Exception wasn't propagated from Bad::return_std_string()"); +} catch (Exception $e) { + check::equal($e->getMessage(), "bad std_string", "propagated exception incorrect"); +} + +try { + $bad->call_Bar(); + check::fail("Exception wasn't propagated from Bad::return_Bar()"); +} catch (Exception $e) { + check::equal($e->getMessage(), "bad Bar", "propagated exception incorrect"); +} + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_extend_runme.php b/Examples/test-suite/php5/director_extend_runme.php new file mode 100644 index 000000000..f283aefbe --- /dev/null +++ b/Examples/test-suite/php5/director_extend_runme.php @@ -0,0 +1,24 @@ +dummy(), 666, "1st call"); +check::equal($m->dummy(), 666, "2st call"); // Locked system + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_finalizer_runme.php b/Examples/test-suite/php5/director_finalizer_runme.php new file mode 100644 index 000000000..0fcddfd8b --- /dev/null +++ b/Examples/test-suite/php5/director_finalizer_runme.php @@ -0,0 +1,61 @@ +orStatus(2); + if (method_exists(parent, "__destruct")) { + parent::__destruct(); + } + } +} + +resetStatus(); + +$a = new MyFoo(); +unset($a); + +check::equal(getStatus(), 3, "getStatus() failed #1"); + +resetStatus(); + +$a = new MyFoo(); +launder($a); + +check::equal(getStatus(), 0, "getStatus() failed #2"); + +unset($a); + +check::equal(getStatus(), 3, "getStatus() failed #3"); + +resetStatus(); + +$a = new MyFoo(); +$a->thisown = 0; +deleteFoo($a); +unset($a); + +check::equal(getStatus(), 3, "getStatus() failed #4"); + +resetStatus(); + +$a = new MyFoo(); +$a->thisown = 0; +deleteFoo(launder($a)); +unset($a); + +check::equal(getStatus(), 3, "getStatus() failed #5"); + +resetStatus(); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_frob_runme.php b/Examples/test-suite/php5/director_frob_runme.php new file mode 100644 index 000000000..548b0b804 --- /dev/null +++ b/Examples/test-suite/php5/director_frob_runme.php @@ -0,0 +1,19 @@ +abs_method(); + +check::equal($s, "Bravo::abs_method()", "s failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_nested_runme.php b/Examples/test-suite/php5/director_nested_runme.php new file mode 100644 index 000000000..4965e94f7 --- /dev/null +++ b/Examples/test-suite/php5/director_nested_runme.php @@ -0,0 +1,74 @@ +step(), "Bar::step;Foo::advance;Bar::do_advance;A::do_step;", "Bad A virtual resolution"); + +class B extends FooBar_int { + function do_advance() { + return "B::do_advance;" . $this->do_step(); + } + + function do_step() { + return "B::do_step;"; + } + + function get_value() { + return 1; + } +} + +$b = new B(); + +check::equal($b->step(), "Bar::step;Foo::advance;B::do_advance;B::do_step;", "Bad B virtual resolution"); + +class C extends FooBar_int { + function do_advance() { + return "C::do_advance;" . parent::do_advance(); + } + + function do_step() { + return "C::do_step;"; + } + + function get_value() { + return 2; + } + + function get_name() { + return parent::get_name() . " hello"; + } +} + +$cc = new C(); +# TODO: Currently we do not track the dynamic type of returned +# objects, so we skip the get_self() call. +#$c = Foobar_int::get_self($cc); +$c = $cc; +$c->advance(); + +check::equal($c->get_name(), "FooBar::get_name hello", "get_name failed"); + +check::equal($c->name(), "FooBar::get_name hello", "name failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_pass_by_value_runme.php b/Examples/test-suite/php5/director_pass_by_value_runme.php new file mode 100644 index 000000000..8a8b84d67 --- /dev/null +++ b/Examples/test-suite/php5/director_pass_by_value_runme.php @@ -0,0 +1,24 @@ +call_virtualMethod(new director_pass_by_value_Derived()); +$ret = $passByVal->getVal(); +if ($ret != 0x12345678) { + check::fail("Bad return value, got " . dechex($ret)); +} + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_profile_runme.php b/Examples/test-suite/php5/director_profile_runme.php new file mode 100644 index 000000000..c72421341 --- /dev/null +++ b/Examples/test-suite/php5/director_profile_runme.php @@ -0,0 +1,53 @@ +fi($a); #1 + $a = $b->fi($a); #2 + $a = $b->fi($a); #3 + $a = $b->fi($a); #4 + $a = $b->fi($a); #5 + $a = $b->fi($a); #6 + $a = $b->fi($a); #7 + $a = $b->fi($a); #8 + $a = $b->fi($a); #9 + $a = $b->fi($a); #10 + $a = $b->fi($a); #1 + $a = $b->fi($a); #2 + $a = $b->fi($a); #3 + $a = $b->fi($a); #4 + $a = $b->fi($a); #5 + $a = $b->fi($a); #6 + $a = $b->fi($a); #7 + $a = $b->fi($a); #8 + $a = $b->fi($a); #9 + $a = $b->fi($a); #20 + $i -= 1; +} + +print $a . "\n"; + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_protected_runme.php b/Examples/test-suite/php5/director_protected_runme.php new file mode 100644 index 000000000..18586ca62 --- /dev/null +++ b/Examples/test-suite/php5/director_protected_runme.php @@ -0,0 +1,70 @@ +create(); +$fb = new FooBar(); +$fb2 = new FooBar2(); +$fb3 = new FooBar3(); + +check::equal($fb->used(), "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();", "bad FooBar::used"); + +check::equal($fb2->used(), "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();", "bad FooBar2::used"); + +check::equal($b->pong(), "Bar::pong();Foo::pong();Bar::ping();", "bad Bar::pong"); + +check::equal($f->pong(), "Bar::pong();Foo::pong();Bar::ping();", "bad Foo::pong"); + +check::equal($fb->pong(), "Bar::pong();Foo::pong();FooBar::ping();", "bad FooBar::pong"); + +$method = new ReflectionMethod('Bar', 'ping'); +check::equal($method->isProtected(), true, "Foo::ping should be protected"); + +$method = new ReflectionMethod('Foo', 'ping'); +check::equal($method->isProtected(), true, "Foo::ping should be protected"); + +$method = new ReflectionMethod('FooBar', 'pang'); +check::equal($method->isProtected(), true, "FooBar::pang should be protected"); + +$method = new ReflectionMethod('Bar', 'cheer'); +check::equal($method->isProtected(), true, "Bar::cheer should be protected"); + +$method = new ReflectionMethod('Foo', 'cheer'); +check::equal($method->isProtected(), true, "Foo::cheer should be protected"); + +check::equal($fb3->cheer(), "FooBar3::cheer();", "bad fb3::pong"); +check::equal($fb2->callping(), "FooBar2::ping();", "bad fb2::callping"); +check::equal($fb2->callcheer(), "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();", "bad fb2::callcheer"); +check::equal($fb3->callping(), "Bar::ping();", "bad fb3::callping"); +check::equal($fb3->callcheer(), "FooBar3::cheer();", "bad fb3::callcheer"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_stl_runme.php b/Examples/test-suite/php5/director_stl_runme.php new file mode 100644 index 000000000..29addd261 --- /dev/null +++ b/Examples/test-suite/php5/director_stl_runme.php @@ -0,0 +1,60 @@ +tping("hello"); +$a->tpong("hello"); + +# TODO: automatic conversion between PHP arrays and std::pair or +# std::vector is not yet implemented. +/*$p = array(1, 2); +$a->pident($p); +$v = array(3, 4); +$a->vident($v); + +$a->tpident($p); +$a->tvident($v); + +$v1 = array(3, 4); +$v2 = array(5, 6); + +$a->tvsecond($v1, $v2); + +$vs = array("hi", "hello"); +$vs; +$a->tvidents($vs);*/ + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_string_runme.php b/Examples/test-suite/php5/director_string_runme.php new file mode 100644 index 000000000..5ac583f78 --- /dev/null +++ b/Examples/test-suite/php5/director_string_runme.php @@ -0,0 +1,34 @@ +smem = "hello"; + } +} + +$b = new B("hello"); + +$b->get(0); +check::equal($b->get_first(),"hello world!", "get_first failed"); + +$b->call_process_func(); + +check::equal($b->smem, "hello", "smem failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_thread_runme.php b/Examples/test-suite/php5/director_thread_runme.php new file mode 100644 index 000000000..809dec3e2 --- /dev/null +++ b/Examples/test-suite/php5/director_thread_runme.php @@ -0,0 +1,32 @@ +val = $this->val - 1; + } +} + +$d = new Derived(); +$d->run(); + +if ($d->val >= 0) { + check::fail($d->val); +} + +$d->stop(); + +check::done(); +?> diff --git a/Examples/test-suite/php5/director_unroll_runme.php b/Examples/test-suite/php5/director_unroll_runme.php new file mode 100644 index 000000000..626b1f07d --- /dev/null +++ b/Examples/test-suite/php5/director_unroll_runme.php @@ -0,0 +1,29 @@ +set($a); +$c = $b->get(); + +check::equal($a->this, $c->this, "this failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/enum_scope_template_runme.php b/Examples/test-suite/php5/enum_scope_template_runme.php new file mode 100644 index 000000000..85ba467b7 --- /dev/null +++ b/Examples/test-suite/php5/enum_scope_template_runme.php @@ -0,0 +1,15 @@ + diff --git a/Examples/test-suite/php5/evil_diamond_ns_runme.php b/Examples/test-suite/php5/evil_diamond_ns_runme.php new file mode 100644 index 000000000..fcce0f767 --- /dev/null +++ b/Examples/test-suite/php5/evil_diamond_ns_runme.php @@ -0,0 +1,18 @@ + diff --git a/Examples/test-suite/php5/evil_diamond_prop_runme.php b/Examples/test-suite/php5/evil_diamond_prop_runme.php new file mode 100644 index 000000000..02d9944d6 --- /dev/null +++ b/Examples/test-suite/php5/evil_diamond_prop_runme.php @@ -0,0 +1,38 @@ +_foo,"1==foo->_foo"); + +$bar=new bar(); +check::is_a($bar,"bar"); +check::equal(1,$bar->_foo,"1==bar->_foo"); +check::equal(2,$bar->_bar,"2==bar->_bar"); + +$baz=new baz(); +check::is_a($baz,"baz"); +check::equal(1,$baz->_foo,"1==baz->_foo"); +check::equal(3,$baz->_baz,"3==baz->_baz"); + +$spam=new spam(); +check::is_a($spam,"spam"); +check::equal(1,$spam->_foo,"1==spam->_foo"); +check::equal(2,$spam->_bar,"2==spam->_bar"); +// multiple inheritance not supported in PHP +check::equal(null,$spam->_baz,"null==spam->_baz"); +check::equal(4,$spam->_spam,"4==spam->_spam"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/evil_diamond_runme.php b/Examples/test-suite/php5/evil_diamond_runme.php new file mode 100644 index 000000000..a587ca359 --- /dev/null +++ b/Examples/test-suite/php5/evil_diamond_runme.php @@ -0,0 +1,16 @@ + diff --git a/Examples/test-suite/php5/exception_order_runme.php b/Examples/test-suite/php5/exception_order_runme.php new file mode 100644 index 000000000..acb83561a --- /dev/null +++ b/Examples/test-suite/php5/exception_order_runme.php @@ -0,0 +1,39 @@ +foo(); +} catch (Exception $e) { + check::equal($e->getMessage(), 'C++ E1 exception thrown', ''); +} + +try { + $a->bar(); +} catch (Exception $e) { + check::equal($e->getMessage(), 'C++ E2 exception thrown', ''); +} + +try { + $a->foobar(); +} catch (Exception $e) { + check::equal($e->getMessage(), 'postcatch unknown', ''); +} + +try { + $a->barfoo(1); +} catch (Exception $e) { + check::equal($e->getMessage(), 'C++ E1 exception thrown', ''); +} + +try { + $a->barfoo(2); +} catch (Exception $e) { + check::equal($e->getMessage(), 'C++ E2 * exception thrown', ''); +} +?> diff --git a/Examples/test-suite/php5/extend_template_ns_runme.php b/Examples/test-suite/php5/extend_template_ns_runme.php new file mode 100644 index 000000000..e6d3e9f73 --- /dev/null +++ b/Examples/test-suite/php5/extend_template_ns_runme.php @@ -0,0 +1,12 @@ +test1(2),"test1"); +check::equal(3,$foo->test2(3),"test2"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/extend_template_runme.php b/Examples/test-suite/php5/extend_template_runme.php new file mode 100644 index 000000000..41bde4458 --- /dev/null +++ b/Examples/test-suite/php5/extend_template_runme.php @@ -0,0 +1,12 @@ +test1(2),"test1"); +check::equal(3,$foo->test2(3),"test2"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/grouping_runme.php b/Examples/test-suite/php5/grouping_runme.php new file mode 100644 index 000000000..51446f473 --- /dev/null +++ b/Examples/test-suite/php5/grouping_runme.php @@ -0,0 +1,22 @@ + diff --git a/Examples/test-suite/php5/ignore_parameter_runme.php b/Examples/test-suite/php5/ignore_parameter_runme.php new file mode 100644 index 000000000..1c8c76ad4 --- /dev/null +++ b/Examples/test-suite/php5/ignore_parameter_runme.php @@ -0,0 +1,38 @@ +daimler(2,3.4),"hello",'$sc->daimler(2,3.4)=="hello"'); +check::equal($sc->astonmartin("eek",3.4),101,'$sc->mastonmartin("eek",3.4)==101'); +check::equal($sc->bugatti("eek",2),8.8,'$sc->bugatti("eek",2)==8.8'); +check::equal($sc->lamborghini(),101,'$sc->lamborghini(2)==101'); + +$mc=new minicooper(2,3.4); +check::classname("minicooper",$mc); + +$mm=new morrisminor("eek",3.4); +check::classname("morrisminor",$mm); + +$fa=new fordanglia("eek",2); +check::classname("fordanglia",$fa); + +$aa=new austinallegro(); +check::classname("austinallegro",$aa); + +check::done(); +?> diff --git a/Examples/test-suite/php5/import_nomodule_runme.php b/Examples/test-suite/php5/import_nomodule_runme.php new file mode 100644 index 000000000..41836ba0f --- /dev/null +++ b/Examples/test-suite/php5/import_nomodule_runme.php @@ -0,0 +1,20 @@ + diff --git a/Examples/test-suite/php5/li_carrays_cpp_runme.php b/Examples/test-suite/php5/li_carrays_cpp_runme.php new file mode 100644 index 000000000..3be09ca8c --- /dev/null +++ b/Examples/test-suite/php5/li_carrays_cpp_runme.php @@ -0,0 +1,22 @@ +setitem(0, 7); +$d->setitem(5, $d->getitem(0) + 3); +check::equal($d->getitem(0) + $d->getitem(5), 17., "7+10==17"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/li_carrays_runme.php b/Examples/test-suite/php5/li_carrays_runme.php new file mode 100644 index 000000000..fbe5cc793 --- /dev/null +++ b/Examples/test-suite/php5/li_carrays_runme.php @@ -0,0 +1,22 @@ +setitem(0, 7); +$d->setitem(5, $d->getitem(0) + 3); +check::equal($d->getitem(0) + $d->getitem(5), 17., "7+10==17"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/li_factory_runme.php b/Examples/test-suite/php5/li_factory_runme.php new file mode 100644 index 000000000..6623e2a8c --- /dev/null +++ b/Examples/test-suite/php5/li_factory_runme.php @@ -0,0 +1,22 @@ +radius(); +check::equal($r, 1.5, "r failed"); + +$point = Geometry::create(Geometry::POINT); +$w = $point->width(); +check::equal($w, 1.0, "w failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/li_std_string_runme.php b/Examples/test-suite/php5/li_std_string_runme.php new file mode 100644 index 000000000..ad62247e1 --- /dev/null +++ b/Examples/test-suite/php5/li_std_string_runme.php @@ -0,0 +1,31 @@ +MemberString2, "member string 2", "MemberString2 test 1"); +$myStructure->MemberString2 = $s; +check::equal($myStructure->MemberString2, $s, "MemberString2 test 2"); +check::equal($myStructure->ConstMemberString, "const member string", "ConstMemberString test"); + +check::equal(Structure::StaticMemberString2(), "static member string 2", "StaticMemberString2 test 1"); +Structure::StaticMemberString2($s); +check::equal(Structure::StaticMemberString2(), $s, "StaticMemberString2 test 2"); +// below broken ? +//check::equal(Structure::ConstStaticMemberString(), "const static member string", "ConstStaticMemberString test"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/li_std_vector_member_var_runme.php b/Examples/test-suite/php5/li_std_vector_member_var_runme.php new file mode 100644 index 000000000..238350352 --- /dev/null +++ b/Examples/test-suite/php5/li_std_vector_member_var_runme.php @@ -0,0 +1,30 @@ +x, 0, "Test::x != 0"); +check::equal($t->v->size(), 0, "Test::v.size() != 0"); + +$t->f(1); +check::equal($t->x, 1, "Test::x != 1"); +check::equal($t->v->size(), 1, "Test::v.size() != 1"); + +$t->f(2); +check::equal($t->x, 3, "Test::x != 3"); +check::equal($t->v->size(), 2, "Test::v.size() != 2"); + +$t->f(3); +check::equal($t->x, 6, "Test::x != 6"); +check::equal($t->v->size(), 3, "Test::v.size() != 3"); + +$T = new T(); +$T->start_t = new S(); +$T->length = 7; +check::equal($T->start_t->x, 4, "S::x != 4"); +check::equal($T->length, 7, "T::length != 7"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/newobject1_runme.php b/Examples/test-suite/php5/newobject1_runme.php new file mode 100644 index 000000000..5853a72c0 --- /dev/null +++ b/Examples/test-suite/php5/newobject1_runme.php @@ -0,0 +1,19 @@ +makeMore(); +check::equal(get_class($bar), "Foo", "regular failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/overload_rename_runme.php b/Examples/test-suite/php5/overload_rename_runme.php new file mode 100644 index 000000000..dce4c6cb3 --- /dev/null +++ b/Examples/test-suite/php5/overload_rename_runme.php @@ -0,0 +1,19 @@ + diff --git a/Examples/test-suite/php5/overload_return_type_runme.php b/Examples/test-suite/php5/overload_return_type_runme.php new file mode 100644 index 000000000..4fa19d22a --- /dev/null +++ b/Examples/test-suite/php5/overload_return_type_runme.php @@ -0,0 +1,13 @@ +foo(1), 0, ""); +check::classname("A", $b->foo("test")); + +check::equal(overload_return_type::foo(), 1, "overload_return_type::foo() should be 1"); +check::equal(overload_return_type::bar(), 1, "overload_return_type::bar() should be 1"); + +?> diff --git a/Examples/test-suite/php5/php_iterator_runme.php b/Examples/test-suite/php5/php_iterator_runme.php new file mode 100644 index 000000000..d69a5b385 --- /dev/null +++ b/Examples/test-suite/php5/php_iterator_runme.php @@ -0,0 +1,24 @@ + $v) { + $s .= "($k=>$v)"; +} +check::equal($s, '(0=>2)(1=>3)(2=>4)', 'Simple iteration failed'); + +check::done(); +?> diff --git a/Examples/test-suite/php5/pointer_reference_runme.php b/Examples/test-suite/php5/pointer_reference_runme.php new file mode 100644 index 000000000..52946177e --- /dev/null +++ b/Examples/test-suite/php5/pointer_reference_runme.php @@ -0,0 +1,18 @@ +value, 10, "pointer_reference::get() failed"); + +$ss = new Struct(20); +pointer_reference::set($ss); +$i = Struct::instance(); +check::equal($i->value, 20, "pointer_reference::set() failed"); + +check::equal(pointer_reference::overloading(1), 111, "overload test 1 failed"); +check::equal(pointer_reference::overloading($ss), 222, "overload test 2 failed"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/prefix_runme.php b/Examples/test-suite/php5/prefix_runme.php new file mode 100644 index 000000000..ead064f5b --- /dev/null +++ b/Examples/test-suite/php5/prefix_runme.php @@ -0,0 +1,18 @@ +get_self(); + +check::done(); +?> diff --git a/Examples/test-suite/php5/preproc_constants_c_runme.php b/Examples/test-suite/php5/preproc_constants_c_runme.php new file mode 100644 index 000000000..1ea01950e --- /dev/null +++ b/Examples/test-suite/php5/preproc_constants_c_runme.php @@ -0,0 +1,66 @@ + diff --git a/Examples/test-suite/php5/preproc_constants_runme.php b/Examples/test-suite/php5/preproc_constants_runme.php new file mode 100644 index 000000000..fb9ee4fa7 --- /dev/null +++ b/Examples/test-suite/php5/preproc_constants_runme.php @@ -0,0 +1,74 @@ + diff --git a/Examples/test-suite/php5/primitive_ref_runme.php b/Examples/test-suite/php5/primitive_ref_runme.php new file mode 100644 index 000000000..263a28074 --- /dev/null +++ b/Examples/test-suite/php5/primitive_ref_runme.php @@ -0,0 +1,34 @@ + diff --git a/Examples/test-suite/php5/rename_scope_runme.php b/Examples/test-suite/php5/rename_scope_runme.php new file mode 100644 index 000000000..df620d796 --- /dev/null +++ b/Examples/test-suite/php5/rename_scope_runme.php @@ -0,0 +1,16 @@ + diff --git a/Examples/test-suite/php5/skel.php b/Examples/test-suite/php5/skel.php new file mode 100644 index 000000000..780a999ed --- /dev/null +++ b/Examples/test-suite/php5/skel.php @@ -0,0 +1,15 @@ + diff --git a/Examples/test-suite/php5/smart_pointer_rename_runme.php b/Examples/test-suite/php5/smart_pointer_rename_runme.php new file mode 100644 index 000000000..26692dde5 --- /dev/null +++ b/Examples/test-suite/php5/smart_pointer_rename_runme.php @@ -0,0 +1,27 @@ +ftest1(1),"foo->ftest1"); +check::equal(2,$foo->ftest2(1,2),"foo->ftest2"); + +# check bar's ftest1, ftest2, ftest +check::equal(1,$bar->ftest1(1),"bar->ftest1"); +check::equal(2,$bar->ftest2(1,2),"bar->ftest2"); +check::equal(3,$bar->test(),"bar->test"); + +# check deref returns foo +check::classname("foo",$bar->__deref__()); + +check::done(); +?> diff --git a/Examples/test-suite/php5/swig_exception_runme.php b/Examples/test-suite/php5/swig_exception_runme.php new file mode 100644 index 000000000..76641996e --- /dev/null +++ b/Examples/test-suite/php5/swig_exception_runme.php @@ -0,0 +1,33 @@ +throwException(); + check::fail("Exception wasn't thrown"); +} catch (Exception $e) { + if ($e->getMessage() != "OK") { + check::fail("Exception getMessage() should be \"OK\", actually \"".$e->getMessage()."\""); + } +} + +# ----- Delete everything ----- + +$c = NULL; +$s = NULL; +$e = NULL; + +if (Shape::nshapes() != 0) { + check::fail("Shape::nshapes() should be 0, actually ".Shape::nshapes()); +} + +?> diff --git a/Examples/test-suite/php5/sym_runme.php b/Examples/test-suite/php5/sym_runme.php new file mode 100644 index 000000000..483aaa980 --- /dev/null +++ b/Examples/test-suite/php5/sym_runme.php @@ -0,0 +1,22 @@ +hulahoops(),"flim-jam","flim()->hulahoops==flim-jam"); +check::equal($flim->jar(),"flim-jar","flim()->jar==flim-jar"); +check::equal($flam->jam(),"flam-jam","flam()->jam==flam-jam"); +check::equal($flam->jar(),"flam-jar","flam()->jar==flam-jar"); + +check::done(); +?> diff --git a/Examples/test-suite/php5/template_arg_typename_runme.php b/Examples/test-suite/php5/template_arg_typename_runme.php new file mode 100644 index 000000000..7d60285e3 --- /dev/null +++ b/Examples/test-suite/php5/template_arg_typename_runme.php @@ -0,0 +1,18 @@ + diff --git a/Examples/test-suite/php5/template_construct_runme.php b/Examples/test-suite/php5/template_construct_runme.php new file mode 100644 index 000000000..3a3986f7e --- /dev/null +++ b/Examples/test-suite/php5/template_construct_runme.php @@ -0,0 +1,11 @@ + diff --git a/Examples/test-suite/php5/tests.php b/Examples/test-suite/php5/tests.php new file mode 100644 index 000000000..d3fd66868 --- /dev/null +++ b/Examples/test-suite/php5/tests.php @@ -0,0 +1,237 @@ + diff --git a/Examples/test-suite/php5/threads_exception_runme.php b/Examples/test-suite/php5/threads_exception_runme.php new file mode 100644 index 000000000..9e4d04e10 --- /dev/null +++ b/Examples/test-suite/php5/threads_exception_runme.php @@ -0,0 +1,43 @@ +unknown(); +} catch (Exception $e) { + check::equal($e->getMessage(), 'C++ A * exception thrown', ''); +} + +try { + $t->simple(); +} catch (Exception $e) { + check::equal($e->getCode(), 37, ''); +} + +try { + $t->message(); +} catch (Exception $e) { + check::equal($e->getMessage(), 'I died.', ''); +} + +try { + $t->hosed(); +} catch (Exception $e) { + check::equal($e->getMessage(), 'C++ Exc exception thrown', ''); +} + +foreach (Array(1,2,3,4) as $i) { + try { + $t->multi($i); + } catch (Exception $e) { + } +} diff --git a/Examples/test-suite/php5/typedef_reference_runme.php b/Examples/test-suite/php5/typedef_reference_runme.php new file mode 100644 index 000000000..88a70f8d3 --- /dev/null +++ b/Examples/test-suite/php5/typedef_reference_runme.php @@ -0,0 +1,13 @@ + diff --git a/Examples/test-suite/php5/typemap_ns_using_runme.php b/Examples/test-suite/php5/typemap_ns_using_runme.php new file mode 100644 index 000000000..6a599f008 --- /dev/null +++ b/Examples/test-suite/php5/typemap_ns_using_runme.php @@ -0,0 +1,9 @@ + diff --git a/Examples/test-suite/php5/using1_runme.php b/Examples/test-suite/php5/using1_runme.php new file mode 100644 index 000000000..51841bc78 --- /dev/null +++ b/Examples/test-suite/php5/using1_runme.php @@ -0,0 +1,9 @@ + diff --git a/Examples/test-suite/php5/using2_runme.php b/Examples/test-suite/php5/using2_runme.php new file mode 100644 index 000000000..391a98f52 --- /dev/null +++ b/Examples/test-suite/php5/using2_runme.php @@ -0,0 +1,9 @@ + diff --git a/Examples/test-suite/php5/valuewrapper_base_runme.php b/Examples/test-suite/php5/valuewrapper_base_runme.php new file mode 100644 index 000000000..6a1abdbd2 --- /dev/null +++ b/Examples/test-suite/php5/valuewrapper_base_runme.php @@ -0,0 +1,13 @@ + diff --git a/Examples/test-suite/php5/virtual_vs_nonvirtual_base_runme.php b/Examples/test-suite/php5/virtual_vs_nonvirtual_base_runme.php new file mode 100644 index 000000000..0d4aa3d5f --- /dev/null +++ b/Examples/test-suite/php5/virtual_vs_nonvirtual_base_runme.php @@ -0,0 +1,11 @@ +getInner()->get(), $fail->getInner()->get(), "should both be 10"); + +?> diff --git a/Examples/test-suite/php5/wrapmacro_runme.php b/Examples/test-suite/php5/wrapmacro_runme.php new file mode 100644 index 000000000..f32da990e --- /dev/null +++ b/Examples/test-suite/php5/wrapmacro_runme.php @@ -0,0 +1,12 @@ + diff --git a/Examples/test-suite/pike/Makefile.in b/Examples/test-suite/pike/Makefile.in index 92054dd9d..6e1bdfbff 100644 --- a/Examples/test-suite/pike/Makefile.in +++ b/Examples/test-suite/pike/Makefile.in @@ -46,4 +46,4 @@ run_testcase = \ @rm -f $*.pike; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" pike_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/test-suite/preproc_constants.i b/Examples/test-suite/preproc_constants.i index db71bd2d7..3a999ada3 100644 --- a/Examples/test-suite/preproc_constants.i +++ b/Examples/test-suite/preproc_constants.i @@ -51,7 +51,7 @@ // Expressions - runtime tests check the type for any necessary type promotions of the expressions #define INT_AND_BOOL 0xFF & true -//#define INT_AND_CHAR 0xFF & 'A' /* FIXME compile error */ +#define INT_AND_CHAR 0xFF & 'A' #define INT_AND_INT 0xFF & 2 #define INT_AND_UINT 0xFF & 2u #define INT_AND_LONG 0xFF & 2l @@ -60,8 +60,7 @@ #define INT_AND_ULLONG 0xFF & 2ull #define BOOL_AND_BOOL true & true // Note integral promotion to type int -//#define CHAR_AND_CHAR 'A' & 'B' // Note integral promotion to type int -/* FIXME ABOVE */ +#define CHAR_AND_CHAR 'A' & 'B' // Note integral promotion to type int #define EXPR_MULTIPLY 0xFF * 2 @@ -88,6 +87,9 @@ #define EXPR_LOR 0xFF || 1 #define EXPR_CONDITIONAL true ? 2 : 2.2 +#define EXPR_CHAR_COMPOUND_ADD 'A' + 12 +#define EXPR_CHAR_COMPOUND_LSHIFT 'B' << 6 +#define H_SUPPRESS_SCALING_MAGIC (('s'<<24) | ('u'<<16) | ('p'<<8) | 'p') /// constant assignment in enum #if defined(SWIGCSHARP) diff --git a/Examples/test-suite/preproc_defined.i b/Examples/test-suite/preproc_defined.i index 0a91bd98a..e1958515d 100644 --- a/Examples/test-suite/preproc_defined.i +++ b/Examples/test-suite/preproc_defined.i @@ -102,6 +102,7 @@ ANOTHER_MACRO(int) void another_macro_checking(void) { struct Defined d; d.defined = 10; + (void)d; thing(10); stuff(10); bumpf(10); diff --git a/Examples/test-suite/primitive_types.i b/Examples/test-suite/primitive_types.i index 82a673536..b9b973a2b 100644 --- a/Examples/test-suite/primitive_types.i +++ b/Examples/test-suite/primitive_types.i @@ -2,6 +2,7 @@ %module(directors="1") primitive_types #if defined(SWIGSCILAB) +%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) ovr_str; %warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) ovr_val; %rename(TestDir) TestDirector; #endif @@ -365,8 +366,24 @@ macro(size_t, pfx, sizet) %define ovr_decl(type, pfx, name) virtual int pfx##_##val(type x) { return 1; } virtual int pfx##_##ref(const type& x) { return 1; } + virtual const char* pfx##_##str(type x) { return "name"; } %enddef +/* checking size_t and ptrdiff_t typemaps */ +%begin %{ +// Must be defined before Python.h is included, since this may indirectly include stdint.h +#define __STDC_LIMIT_MACROS +%} +%include "stdint.i" +%inline { + size_t get_size_min() { return 0; } + size_t get_size_max() { return SIZE_MAX; } + ptrdiff_t get_ptrdiff_min() { return PTRDIFF_MIN; } + ptrdiff_t get_ptrdiff_max() { return PTRDIFF_MAX; } + + size_t size_echo (size_t val) { return val; } + ptrdiff_t ptrdiff_echo(ptrdiff_t val) { return val; } +} %inline { struct Foo diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index a99c30439..133b7056a 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -11,7 +11,7 @@ endif LANGUAGE = python PYTHON = $(PYBIN) PEP8 = @PEP8@ -PEP8_FLAGS = --ignore=E402,E501,E30,W291,W391 +PEP8_FLAGS = --ignore=E30,E402,E501,E731,W291,W391 #*_runme.py for Python 2.x, *_runme3.py for Python 3.x PY2SCRIPTSUFFIX = _runme.py @@ -58,11 +58,18 @@ CPP_TEST_CASES += \ primitive_types \ python_abstractbase \ python_append \ + python_builtin \ + python_destructor_exception \ python_director \ + python_docstring \ + python_extranative \ + python_moduleimport \ python_nondynamic \ python_overload_simple_cast \ + python_pickle \ python_pythoncode \ python_richcompare \ + python_strict_unicode \ simutry \ std_containers \ swigobject \ @@ -127,11 +134,11 @@ py2_runme = $(SCRIPTPREFIX)$*$(PY2SCRIPTSUFFIX) py3_runme = $(SCRIPTPREFIX)$*$(PY3SCRIPTSUFFIX) ifneq (,$(PEP8)) -check_pep8 = $(PEP8) $(PEP8_FLAGS) $(SCRIPTPREFIX)$*.py +check_pep8 = $(COMPILETOOL) $(PEP8) $(PEP8_FLAGS) $(SCRIPTPREFIX)$*.py check_pep8_multi_cpp = \ for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ - $(PEP8) $(PEP8_FLAGS) $$f.py; \ + $(COMPILETOOL) $(PEP8) $(PEP8_FLAGS) $$f.py; \ done endif @@ -166,7 +173,7 @@ endif @if test "x$(SCRIPTDIR)" != "x$(srcdir)"; then rm -f $(SCRIPTDIR)/$(py2_runme); fi clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" python_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' python_clean rm -f hugemod.h hugemod_a.i hugemod_b.i hugemod_a.py hugemod_b.py hugemod_runme.py rm -f clientdata_prop_a.py clientdata_prop_b.py import_stl_a.py import_stl_b.py rm -f imports_a.py imports_b.py mod_a.py mod_b.py multi_import_a.py diff --git a/Examples/test-suite/python/autodoc_runme.py b/Examples/test-suite/python/autodoc_runme.py index 9629ef011..474599a50 100644 --- a/Examples/test-suite/python/autodoc_runme.py +++ b/Examples/test-suite/python/autodoc_runme.py @@ -1,5 +1,6 @@ from autodoc import * import commentVerifier +import inspect import sys def check(got, expected, expected_builtin=None, skip=False): @@ -12,174 +13,191 @@ def check(got, expected, expected_builtin=None, skip=False): def is_new_style_class(cls): return hasattr(cls, "__class__") +def is_fastproxy(module): + return "new_instancemethod" in module + if not is_new_style_class(A): # Missing static methods make this hard to test... skip if -classic is # used! sys.exit(0) +if is_fastproxy(dir()): + # Detect when -fastproxy is specified and skip test as it changes the function names making it + # hard to test... skip until the number of options are reduced in SWIG-3.1 and autodoc is improved + sys.exit(0) + # skip builtin check - the autodoc is missing, but it probably should not be skip = True -check(A.__doc__, "Proxy of C++ A class", "::A") -check(A.funk.__doc__, "just a string") -check(A.func0.__doc__, "func0(self, arg2, hello) -> int") -check(A.func1.__doc__, "func1(A self, short arg2, Tuple hello) -> int") -check(A.func2.__doc__, +check(inspect.getdoc(A), "Proxy of C++ A class.", "::A") +check(inspect.getdoc(A.funk), "just a string.") +check(inspect.getdoc(A.func0), + "func0(self, arg2, hello) -> int") +check(inspect.getdoc(A.func1), + "func1(A self, short arg2, Tuple hello) -> int") +check(inspect.getdoc(A.func2), "func2(self, arg2, hello) -> int\n" "\n" - "Parameters:\n" - " arg2: short\n" - " hello: int tuple[2]\n" - ) -check(A.func3.__doc__, + "Parameters\n" + "----------\n" + "arg2: short\n" + "hello: int tuple[2]") +check(inspect.getdoc(A.func3), "func3(A self, short arg2, Tuple hello) -> int\n" "\n" - "Parameters:\n" - " arg2: short\n" - " hello: int tuple[2]\n" - ) + "Parameters\n" + "----------\n" + "arg2: short\n" + "hello: int tuple[2]") -check(A.func0default.__doc__, +check(inspect.getdoc(A.func0default), "func0default(self, e, arg3, hello, f=2) -> int\n" - "func0default(self, e, arg3, hello) -> int" - ) -check(A.func1default.__doc__, + "func0default(self, e, arg3, hello) -> int") +check(inspect.getdoc(A.func1default), "func1default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n" - "func1default(A self, A e, short arg3, Tuple hello) -> int" - ) -check(A.func2default.__doc__, + "func1default(A self, A e, short arg3, Tuple hello) -> int") +check(inspect.getdoc(A.func2default), "func2default(self, e, arg3, hello, f=2) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg3: short\n" - " hello: int tuple[2]\n" - " f: double\n" + "Parameters\n" + "----------\n" + "e: A *\n" + "arg3: short\n" + "hello: int tuple[2]\n" + "f: double\n" "\n" "func2default(self, e, arg3, hello) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg3: short\n" - " hello: int tuple[2]\n" - ) -check(A.func3default.__doc__, + "Parameters\n" + "----------\n" + "e: A *\n" + "arg3: short\n" + "hello: int tuple[2]") +check(inspect.getdoc(A.func3default), "func3default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg3: short\n" - " hello: int tuple[2]\n" - " f: double\n" + "Parameters\n" + "----------\n" + "e: A *\n" + "arg3: short\n" + "hello: int tuple[2]\n" + "f: double\n" "\n" "func3default(A self, A e, short arg3, Tuple hello) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg3: short\n" - " hello: int tuple[2]\n" - ) + "Parameters\n" + "----------\n" + "e: A *\n" + "arg3: short\n" + "hello: int tuple[2]") -check(A.func0static.__doc__, +check(inspect.getdoc(A.func0static), "func0static(e, arg2, hello, f=2) -> int\n" - "func0static(e, arg2, hello) -> int" - ) -check(A.func1static.__doc__, + "func0static(e, arg2, hello) -> int") +check(inspect.getdoc(A.func1static), "func1static(A e, short arg2, Tuple hello, double f=2) -> int\n" - "func1static(A e, short arg2, Tuple hello) -> int" - ) -check(A.func2static.__doc__, + "func1static(A e, short arg2, Tuple hello) -> int") +check(inspect.getdoc(A.func2static), "func2static(e, arg2, hello, f=2) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg2: short\n" - " hello: int tuple[2]\n" - " f: double\n" + "Parameters\n" + "----------\n" + "e: A *\n" + "arg2: short\n" + "hello: int tuple[2]\n" + "f: double\n" "\n" "func2static(e, arg2, hello) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg2: short\n" - " hello: int tuple[2]\n" - ) -check(A.func3static.__doc__, + "Parameters\n" + "----------\n" + "e: A *\n" + "arg2: short\n" + "hello: int tuple[2]") +check(inspect.getdoc(A.func3static), "func3static(A e, short arg2, Tuple hello, double f=2) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg2: short\n" - " hello: int tuple[2]\n" - " f: double\n" + "Parameters\n" + "----------\n" + "e: A *\n" + "arg2: short\n" + "hello: int tuple[2]\n" + "f: double\n" "\n" "func3static(A e, short arg2, Tuple hello) -> int\n" "\n" - "Parameters:\n" - " e: A *\n" - " arg2: short\n" - " hello: int tuple[2]\n" - ) + "Parameters\n" + "----------\n" + "e: A *\n" + "arg2: short\n" + "hello: int tuple[2]") if sys.version_info[0:2] > (2, 4): # Python 2.4 does not seem to work - check(A.variable_a.__doc__, + check(inspect.getdoc(A.variable_a), "A_variable_a_get(self) -> int", "A.variable_a" ) - check(A.variable_b.__doc__, + check(inspect.getdoc(A.variable_b), "A_variable_b_get(A self) -> int", "A.variable_b" ) - check(A.variable_c.__doc__, + check(inspect.getdoc(A.variable_c), "A_variable_c_get(self) -> int\n" "\n" - "Parameters:\n" - " self: A *\n", + "Parameters\n" + "----------\n" + "self: A *", "A.variable_c" - ) - check(A.variable_d.__doc__, + ) + check(inspect.getdoc(A.variable_d), "A_variable_d_get(A self) -> int\n" "\n" - "Parameters:\n" - " self: A *\n", + "Parameters\n" + "----------\n" + "self: A *", "A.variable_d" - ) + ) -check(B.__doc__, - "Proxy of C++ B class", +check(inspect.getdoc(B), + "Proxy of C++ B class.", "::B" ) -check(C.__init__.__doc__, "__init__(self, a, b, h) -> C", None, skip) -check(D.__init__.__doc__, +check(inspect.getdoc(C.__init__), "__init__(self, a, b, h) -> C", None, skip) +check(inspect.getdoc(D.__init__), "__init__(D self, int a, int b, Hola h) -> D", None, skip) -check(E.__init__.__doc__, +check(inspect.getdoc(E.__init__), "__init__(self, a, b, h) -> E\n" "\n" - "Parameters:\n" - " a: special comment for parameter a\n" - " b: another special comment for parameter b\n" - " h: enum Hola\n", - None, skip + "__init__(self, a, b, h) -> E\n" + "\n" + "Parameters\n" + "----------\n" + "a: special comment for parameter a\n" + "b: another special comment for parameter b\n" + "h: enum Hola", None, skip ) -check(F.__init__.__doc__, +check(inspect.getdoc(F.__init__), "__init__(F self, int a, int b, Hola h) -> F\n" "\n" - "Parameters:\n" - " a: special comment for parameter a\n" - " b: another special comment for parameter b\n" - " h: enum Hola\n", - None, skip + "__init__(F self, int a, int b, Hola h) -> F\n" + "\n" + "Parameters\n" + "----------\n" + "a: special comment for parameter a\n" + "b: another special comment for parameter b\n" + "h: enum Hola", None, skip ) -check(B.funk.__doc__, "funk(B self, int c, int d) -> int") -check(funk.__doc__, "funk(A e, short arg2, int c, int d) -> int") -check(funkdefaults.__doc__, +check(inspect.getdoc(B.funk), + "funk(B self, int c, int d) -> int") +check(inspect.getdoc(funk), "funk(A e, short arg2, int c, int d) -> int") +check(inspect.getdoc(funkdefaults), "funkdefaults(A e, short arg2, int c, int d, double f=2) -> int\n" - "funkdefaults(A e, short arg2, int c, int d) -> int" - ) + "funkdefaults(A e, short arg2, int c, int d) -> int") -check(func_input.__doc__, "func_input(int * INPUT) -> int") -check(func_output.__doc__, "func_output() -> int") -check(func_inout.__doc__, "func_inout(int * INOUT) -> int") -check(banana.__doc__, "banana(S a, S b, int c, Integer d)") +check(inspect.getdoc(func_input), "func_input(int * INPUT) -> int") +check(inspect.getdoc(func_output), "func_output() -> int") +check(inspect.getdoc(func_inout), "func_inout(int * INOUT) -> int") +check(inspect.getdoc(func_cb), "func_cb(int c, int d) -> int") +check(inspect.getdoc(banana), "banana(S a, S b, int c, Integer d)") diff --git a/Examples/test-suite/python/char_binary_runme.py b/Examples/test-suite/python/char_binary_runme.py index 13457253f..34caa3208 100644 --- a/Examples/test-suite/python/char_binary_runme.py +++ b/Examples/test-suite/python/char_binary_runme.py @@ -4,9 +4,14 @@ t = Test() if t.strlen('hile') != 4: print t.strlen('hile') raise RuntimeError, "bad multi-arg typemap" +if t.ustrlen('hile') != 4: + print t.ustrlen('hile') + raise RuntimeError, "bad multi-arg typemap" if t.strlen('hil\0') != 4: raise RuntimeError, "bad multi-arg typemap" +if t.ustrlen('hil\0') != 4: + raise RuntimeError, "bad multi-arg typemap" # # creating a raw char* @@ -21,6 +26,8 @@ pchar_setitem(pc, 4, 0) if t.strlen(pc) != 4: raise RuntimeError, "bad multi-arg typemap" +if t.ustrlen(pc) != 4: + raise RuntimeError, "bad multi-arg typemap" cvar.var_pchar = pc if cvar.var_pchar != "hola": diff --git a/Examples/test-suite/python/compactdefaultargs_runme.py b/Examples/test-suite/python/compactdefaultargs_runme.py index e81c8d173..1096619f4 100644 --- a/Examples/test-suite/python/compactdefaultargs_runme.py +++ b/Examples/test-suite/python/compactdefaultargs_runme.py @@ -17,3 +17,6 @@ if defaults2.ret(10.0) != 10.0: if defaults2.ret() != -1.0: raise RuntimeError + +if defaults2.nodefault(-2) != -2: + raise RuntimeError diff --git a/Examples/test-suite/python/constant_directive_runme.py b/Examples/test-suite/python/constant_directive_runme.py index a7ed82b8b..e223cd261 100644 --- a/Examples/test-suite/python/constant_directive_runme.py +++ b/Examples/test-suite/python/constant_directive_runme.py @@ -18,3 +18,11 @@ if constant_directive.TYPE1_CONSTANT2.val != 2: if constant_directive.TYPE1_CONSTANT3.val != 3: raise RuntimeError("constant_directive.TYPE1_CONSTANT3.val is %r (should be 3)" % constant_directive.TYPE1_CONSTANT3.val) + +if constant_directive.TYPE1CONST_CONSTANT1.val != 1: + raise RuntimeError("constant_directive.TYPE1CONST_CONSTANT1.val is %r (should be 1)" % + constant_directive.TYPE1CONST_CONSTANT1.val) + +if constant_directive.TYPE1CPTR_CONSTANT1.val != 1: + raise RuntimeError("constant_directive.TYPE1CPTR_CONSTANT1.val is %r (should be 1)" % + constant_directive.TYPE1CPTR_CONSTANT1.val) diff --git a/Examples/test-suite/python/cpp11_li_std_array_runme.py b/Examples/test-suite/python/cpp11_li_std_array_runme.py new file mode 100644 index 000000000..3b1ceb2f8 --- /dev/null +++ b/Examples/test-suite/python/cpp11_li_std_array_runme.py @@ -0,0 +1,163 @@ +from cpp11_li_std_array import * +import sys + + +def failed(a, b, msg): + raise RuntimeError, msg + " " + str(list(a)) + " " + str(list(b)) + + +def compare_sequences(a, b): + if len(a) != len(b): + failed(a, b, "different sizes") + for i in range(len(a)): + if a[i] != b[i]: + failed(a, b, "elements are different") + +def compare_containers(pythonlist, swigarray): + compare_sequences(pythonlist, swigarray) + +def steps_exception(swigarray, i, j, step): + try: + if i == None and j == None: + a = swigarray[::step] + elif i == None: + a = swigarray[:j:step] + elif j == None: + a = swigarray[i::step] + else: + a = swigarray[i:j:step] + raise RuntimeError, "swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed steps exception for " + str(list(swigarray)) + except ValueError, e: +# print("exception: {}".format(e)) + pass + +def del_exception(swigarray, i, j, step): + try: + if i == None and j == None: + del swigarray[::step] + elif j == None and step == None: + del swigarray[i] + elif i == None: + del swigarray[:j:step] + elif j == None: + del swigarray[i::step] + else: + del swigarray[i:j:step] + raise RuntimeError, "swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed del exception for " + str(list(swigarray)) + except ValueError, e: +# print("exception: {}".format(e)) + pass + +def setslice_exception(swigarray, newval): + try: + swigarray[::] = newval + raise RuntimeError, "swigarray[::] = " + str(newval) + " missed set exception for swigarray:" + str(list(swigarray)) + except TypeError, e: +# print("exception: {}".format(e)) + pass + + +# Check std::array has similar behaviour to a Python list +# except it is not resizable + +ps = [0, 1, 2, 3, 4, 5] + +ai = ArrayInt6(ps) + +compare_containers(ps, ai) + +# slices +compare_containers(ps[0:6], ai[0:6]) +compare_containers(ps[0:10], ai[0:10]) +compare_containers(ps[-10:6], ai[-10:6]) +compare_containers(ps[-10:10], ai[-10:10]) + +compare_containers(ps[0:6:1], ai[0:6:1]) +compare_containers(ps[::], ai[::]) +compare_containers(ps[::1], ai[::1]) + +compare_containers([x for x in ps], [x for x in ai]) + +# Reverse +compare_containers(ps[::-1], ai[::-1]) +compare_containers(ps[5::-1], ai[5::-1]) +compare_containers(ps[10::-1], ai[10::-1]) + +# Steps other than +1 and -1 not supported +steps_exception(ai, 0, 6, 3) +steps_exception(ai, None, None, 0) +steps_exception(ai, None, None, 2) +steps_exception(ai, None, None, -2) +steps_exception(ai, 1, 3, 1) +steps_exception(ai, 3, 1, -1) + +# Modify content +for i in range(len(ps)): + ps[i] = (ps[i] + 1) * 10 + ai[i] = (ai[i] + 1) * 10 +compare_containers(ps, ai) + +# Delete +del_exception(ai, 0, 6, 3) +del_exception(ai, None, None, 0) +del_exception(ai, None, None, 2) +del_exception(ai, None, None, -2) +del_exception(ai, 1, 3, 1) +del_exception(ai, 3, 1, -1) + +del_exception(ai, 0, None, None) +del_exception(ai, 5, None, None) + +# Empty +ai = ArrayInt6() +compare_containers([0, 0, 0, 0, 0, 0], ai) + +# Set slice +newvals = [10, 20, 30, 40, 50, 60] +ai[::] = newvals +compare_containers(ai, newvals) + +newvals = [100, 200, 300, 400, 500, 600] +ai[0:6:1] = newvals +compare_containers(ai, newvals) + +newvals = [1000, 2000, 3000, 4000, 5000, 6000] +ai[::-1] = newvals +compare_containers(ai, newvals[::-1]) + +newvals = [10000, 20000, 30000, 40000, 50000, 60000] +ai[-10:100:1] = newvals +compare_containers(ai, newvals[-10:100:1]) + +setslice_exception(ai, [1, 2, 3, 4, 5, 6, 7]) +setslice_exception(ai, [1, 2, 3, 4, 5]) +setslice_exception(ai, [1, 2, 3, 4]) +setslice_exception(ai, [1, 2, 3]) +setslice_exception(ai, [1, 2]) +setslice_exception(ai, [1]) +setslice_exception(ai, []) + +# Check return +compare_containers(arrayOutVal(), [-2, -1, 0, 0, 1, 2]) +compare_containers(arrayOutConstRef(), [-2, -1, 0, 0, 1, 2]) +compare_containers(arrayOutRef(), [-2, -1, 0, 0, 1, 2]) +compare_containers(arrayOutPtr(), [-2, -1, 0, 0, 1, 2]) + +# Check passing arguments +ai = arrayInVal([9, 8, 7, 6, 5, 4]) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +ai = arrayInConstRef([9, 8, 7, 6, 5, 4]) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +ai = ArrayInt6([9, 8, 7, 6, 5, 4]) +arrayInRef(ai) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +ai = ArrayInt6([9, 8, 7, 6, 5, 4]) +arrayInPtr(ai) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +# fill +ai.fill(111) +compare_containers(ai, [111, 111, 111, 111, 111, 111]) diff --git a/Examples/test-suite/python/cpp11_template_typedefs_runme.py b/Examples/test-suite/python/cpp11_template_typedefs_runme.py new file mode 100644 index 000000000..4d6fc2629 --- /dev/null +++ b/Examples/test-suite/python/cpp11_template_typedefs_runme.py @@ -0,0 +1,43 @@ +from cpp11_template_typedefs import * + +t = create_TypedefName() +if type(t).__name__ != "SomeTypeInt5": + raise RuntimeError("type(t) is '%s' and should be 'SomeTypeInt5'" % type(t).__name__) + +if t.a != "hello": + raise RuntimeError("t.a should be 'hello'") +if t.b != 10: + raise RuntimeError("t.b should be 10") +if t.get_n() != 5: + raise RuntimeError("t.get_n() should be 5") + +t_bool = create_TypedefNameBool() +if type(t_bool).__name__ != "SomeTypeBool5": + raise RuntimeError("type(t_bool) is '%s' and should be 'SomeTypeBool5'" % type(t_bool).__name__) + +if t_bool.a != "hello": + raise RuntimeError("t_bool.a should be 'hello'") +if t_bool.b != True: + raise RuntimeError("t_bool.b should be True") +if t_bool.get_n() != 15: + raise RuntimeError("t_bool.get_n() should be 15") + +if get_SomeType_b(t) != 10: + raise RuntimeError("get_SomeType_b(t) should be 10") + +if get_SomeType_b2(t) != 10: + raise RuntimeError("get_SomeType_b2(t) should be 10") + +t2 = SomeTypeInt4() +t2.b = 0 +t3 = identity(t2) +t3.b = 5 +if t2.b != 5: + raise RuntimeError("t2.b should be 5") + +if get_bucket_allocator1() != 1: + raise RuntimeError("bucket_allocator1 should be 1") + +# SWIG doesn't handle ::MyClass as a template argument. Skip this test. +#if get_bucket_allocator2() != 2: +# raise RuntimeError("bucket_allocator2 should be 2") diff --git a/Examples/test-suite/python/cpp11_type_aliasing_runme.py b/Examples/test-suite/python/cpp11_type_aliasing_runme.py new file mode 100644 index 000000000..52cc81d1c --- /dev/null +++ b/Examples/test-suite/python/cpp11_type_aliasing_runme.py @@ -0,0 +1,32 @@ +from cpp11_type_aliasing import * + +if get_host_target().bits != 32: + raise RuntimeError("get_host_target().bits should return 32") + +if mult2(10) != 20: + raise RuntimeError("mult2(10) should return 20") + +int_ptr = allocate_int() +inplace_mult2(int_ptr) +if read_int(int_ptr) != 24: + raise RuntimeError("read_int should return 24") +free_int(int_ptr) + +pair = PairSubclass(3, 4) +if pair.first() != 3: + raise RuntimeError("pair.first() should return 3") + +if pair.second() != 4: + raise RuntimeError("pair.second() should return 4") + +if pair.a != 3: + raise RuntimeError("pair.a should be 3") + +if plus1(5) != 6: + raise RuntimeError("plus1(5) should return 6") + +if call(mult2_cb, 7) != 14: + raise RuntimeError("call(mult2_cb, 7) should return 14") + +if call(get_callback(), 7) != 14: + raise RuntimeError("call(get_callback(), 7) should return 14") diff --git a/Examples/test-suite/python/cpp_static_runme.py b/Examples/test-suite/python/cpp_static_runme.py index b742de285..ef31f88af 100644 --- a/Examples/test-suite/python/cpp_static_runme.py +++ b/Examples/test-suite/python/cpp_static_runme.py @@ -13,5 +13,31 @@ else: StaticFunctionTest().static_func() StaticFunctionTest().static_func_2(1) StaticFunctionTest().static_func_3(1, 2) -StaticMemberTest.static_int = 10 -assert StaticMemberTest.static_int == 10 + +if is_python_builtin(): + if not StaticMemberTest.static_int == 99: raise RuntimeError("static_int not 99") + StaticMemberTest.static_int = 10 + if not StaticMemberTest.static_int == 10: raise RuntimeError("static_int not 10") + + if not StaticBase.statty == 11: raise RuntimeError("statty not 11") + if not StaticDerived.statty == 111: raise RuntimeError("statty not 111") + StaticBase.statty = 22 + StaticDerived.statty = 222 + if not StaticBase.statty == 22: raise RuntimeError("statty not 22") + if not StaticDerived.statty == 222: raise RuntimeError("statty not 222") + + # Restore + StaticMemberTest.static_int = 99 + StaticBase.statty = 11 + StaticDerived.statty = 111 + +if not cvar.StaticMemberTest_static_int == 99: raise RuntimeError("cvar static_int not 99") +cvar.StaticMemberTest_static_int = 10 +if not cvar.StaticMemberTest_static_int == 10: raise RuntimeError("cvar static_int not 10") + +if not cvar.StaticBase_statty == 11: raise RuntimeError("cvar statty not 11") +if not cvar.StaticDerived_statty == 111: raise RuntimeError("cvar statty not 111") +cvar.StaticBase_statty = 22 +cvar.StaticDerived_statty = 222 +if not cvar.StaticBase_statty == 22: raise RuntimeError("cvar statty not 22") +if not cvar.StaticDerived_statty == 222: raise RuntimeError("cvar statty not 222") diff --git a/Examples/test-suite/python/default_args_c_runme.py b/Examples/test-suite/python/default_args_c_runme.py new file mode 100644 index 000000000..5985fd75c --- /dev/null +++ b/Examples/test-suite/python/default_args_c_runme.py @@ -0,0 +1,6 @@ +import default_args_c + +if default_args_c.foo1() != 1: + raise RuntimeError("failed") +if default_args_c.foo43() != 43: + raise RuntimeError("failed") diff --git a/Examples/test-suite/python/default_args_runme.py b/Examples/test-suite/python/default_args_runme.py index 6610a4ec4..9d275e4a1 100644 --- a/Examples/test-suite/python/default_args_runme.py +++ b/Examples/test-suite/python/default_args_runme.py @@ -136,5 +136,23 @@ def run(module_name): if default_args.CDA().cdefaultargs_test2() != 1: raise RuntimeError + if default_args.chartest1() != 'x': + raise RuntimeError + + if default_args.chartest2() != '\0': + raise RuntimeError + + if default_args.chartest3() != '\1': + raise RuntimeError + + if default_args.chartest4() != '\n': + raise RuntimeError + + if default_args.chartest5() != 'B': + raise RuntimeError + + if default_args.chartest6() != 'C': + raise RuntimeError + if __name__ == "__main__": run('default_args') diff --git a/Examples/test-suite/python/director_classic_runme.py b/Examples/test-suite/python/director_classic_runme.py index 9dd5f5967..a4d78f19c 100644 --- a/Examples/test-suite/python/director_classic_runme.py +++ b/Examples/test-suite/python/director_classic_runme.py @@ -69,7 +69,7 @@ class TargetLangOrphanPerson(OrphanPerson): class TargetLangOrphanChild(OrphanChild): def __init__(self): - Child.__init__(self) + OrphanChild.__init__(self) def id(self): identifier = "TargetLangOrphanChild" diff --git a/Examples/test-suite/python/director_pass_by_value_runme.py b/Examples/test-suite/python/director_pass_by_value_runme.py new file mode 100644 index 000000000..7744db962 --- /dev/null +++ b/Examples/test-suite/python/director_pass_by_value_runme.py @@ -0,0 +1,13 @@ +import director_pass_by_value + +passByVal = None +class director_pass_by_value_Derived(director_pass_by_value.DirectorPassByValueAbstractBase): + def virtualMethod(self, b): + global passByVal + passByVal = b + +# bug was the passByVal global object was destroyed after the call to virtualMethod had finished. +director_pass_by_value.Caller().call_virtualMethod(director_pass_by_value_Derived()) +ret = passByVal.getVal(); +if ret != 0x12345678: + raise RuntimeError("Bad return value, got " + hex(ret)) diff --git a/Examples/test-suite/python/director_smartptr_runme.py b/Examples/test-suite/python/director_smartptr_runme.py new file mode 100644 index 000000000..c8bab9d7a --- /dev/null +++ b/Examples/test-suite/python/director_smartptr_runme.py @@ -0,0 +1,37 @@ +from director_smartptr import * + + +class director_smartptr_MyBarFoo(Foo): + + def ping(self): + return "director_smartptr_MyBarFoo.ping()" + + def pong(self): + return "director_smartptr_MyBarFoo.pong();" + self.ping() + + def upcall(self, fooBarPtr): + return "override;" + fooBarPtr.FooBarDo() + + def makeFoo(self): + return Foo() + +def check(got, expected): + if (got != expected): + raise RuntimeError, "Failed, got: " + got + " expected: " + expected + +fooBar = FooBar() + +myBarFoo = director_smartptr_MyBarFoo() +check(myBarFoo.ping(), "director_smartptr_MyBarFoo.ping()") +check(Foo.callPong(myBarFoo), "director_smartptr_MyBarFoo.pong();director_smartptr_MyBarFoo.ping()") +check(Foo.callUpcall(myBarFoo, fooBar), "override;Bar::Foo2::Foo2Bar()") + +myFoo = myBarFoo.makeFoo() +check(myFoo.pong(), "Foo::pong();Foo::ping()") +check(Foo.callPong(myFoo), "Foo::pong();Foo::ping()") +check(myFoo.upcall(FooBar()), "Bar::Foo2::Foo2Bar()") + +myFoo2 = Foo().makeFoo() +check(myFoo2.pong(), "Foo::pong();Foo::ping()") +check(Foo.callPong(myFoo2), "Foo::pong();Foo::ping()") +check(myFoo2.upcall(FooBar()), "Bar::Foo2::Foo2Bar()") diff --git a/Examples/test-suite/python/empty_c_runme.py b/Examples/test-suite/python/empty_c_runme.py new file mode 100644 index 000000000..b7cfbd673 --- /dev/null +++ b/Examples/test-suite/python/empty_c_runme.py @@ -0,0 +1 @@ +import empty_c diff --git a/Examples/test-suite/python/exception_classname_runme.py b/Examples/test-suite/python/exception_classname_runme.py new file mode 100644 index 000000000..9a82c9105 --- /dev/null +++ b/Examples/test-suite/python/exception_classname_runme.py @@ -0,0 +1,5 @@ +import exception_classname + +a = exception_classname.Exception() +if a.testfunc() != 42: + raise RuntimeError("Not 42!") diff --git a/Examples/test-suite/python/funcptr_cpp_runme.py b/Examples/test-suite/python/funcptr_cpp_runme.py index 08e85ad7b..eb113d226 100644 --- a/Examples/test-suite/python/funcptr_cpp_runme.py +++ b/Examples/test-suite/python/funcptr_cpp_runme.py @@ -6,3 +6,5 @@ if call2(ADD_BY_POINTER, 12, 13) != 25: raise RuntimeError if call3(ADD_BY_REFERENCE, 14, 15) != 29: raise RuntimeError +if call1(ADD_BY_VALUE_C, 2, 3) != 5: + raise RuntimeError diff --git a/Examples/test-suite/python/keyword_rename_c_runme.py b/Examples/test-suite/python/keyword_rename_c_runme.py new file mode 100644 index 000000000..c17aede4c --- /dev/null +++ b/Examples/test-suite/python/keyword_rename_c_runme.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python +import keyword_rename_c +keyword_rename_c._in(1) +keyword_rename_c._except(1) diff --git a/Examples/test-suite/python/li_attribute_runme.py b/Examples/test-suite/python/li_attribute_runme.py index 13a01c97d..80e793618 100644 --- a/Examples/test-suite/python/li_attribute_runme.py +++ b/Examples/test-suite/python/li_attribute_runme.py @@ -71,3 +71,13 @@ if myStringyClass.ReadWriteString != "changed string": raise RuntimeError if myStringyClass.ReadOnlyString != "changed string": raise RuntimeError + +# Check a proper AttributeError is raised for non-existent attributes, old versions used to raise unhelpful error: +# AttributeError: type object 'object' has no attribute '__getattr__' +try: + x = myFoo.does_not_exist + raise RuntimeError +except AttributeError, e: + if str(e).find("does_not_exist") == -1: + raise RuntimeError + diff --git a/Examples/test-suite/python/li_boost_shared_ptr_runme.py b/Examples/test-suite/python/li_boost_shared_ptr_runme.py index 7214add3e..c960625ad 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_runme.py @@ -521,7 +521,6 @@ class li_boost_shared_ptr_runme: li_boost_shared_ptr.cvar.GlobalPointer = None # plain reference - kglobal k = li_boost_shared_ptr.Klass("global reference") li_boost_shared_ptr.cvar.GlobalReference = k diff --git a/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py b/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py index 6b56ec479..eab7e282a 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py @@ -8,9 +8,8 @@ if d.bar() != 2: raise RuntimeError if bar_getter(b) != 1: raise RuntimeError -# Fix reverted in rev 12953 -# if bar_getter(d) != 2: -# raise RuntimeError +if bar_getter(d) != 2: + raise RuntimeError b = BaseDefaultInt() d = DerivedDefaultInt() @@ -23,8 +22,11 @@ if d2.bar2() != 4: raise RuntimeError if bar2_getter(b) != 3: raise RuntimeError -# Fix reverted in rev 12953 -# if bar2_getter(d) != 4: -# raise RuntimeError -# if bar2_getter(d2) != 4: -# raise RuntimeError +# SWIG fix reverted in Subversion rev 12953 +# Testcase has now been modified to mask the problem by providing the default parameter 'int' in: +# %shared_ptr(Space::BaseDefault) +# If this is not done then d fails to convert to BaseDefault& +if bar2_getter(d) != 4: + raise RuntimeError +if bar2_getter(d2) != 4: + raise RuntimeError diff --git a/Examples/test-suite/python/li_carrays_cpp_runme.py b/Examples/test-suite/python/li_carrays_cpp_runme.py new file mode 100644 index 000000000..54d79aa46 --- /dev/null +++ b/Examples/test-suite/python/li_carrays_cpp_runme.py @@ -0,0 +1,9 @@ +from li_carrays_cpp import * + +d = doubleArray(10) + +d[0] = 7 +d[5] = d[0] + 3 + +if d[5] + d[0] != 17: + raise RuntimeError diff --git a/Examples/test-suite/python/li_cdata_cpp_runme.py b/Examples/test-suite/python/li_cdata_cpp_runme.py new file mode 100644 index 000000000..30e4b9386 --- /dev/null +++ b/Examples/test-suite/python/li_cdata_cpp_runme.py @@ -0,0 +1,9 @@ + +from li_cdata_cpp import * + +s = "ABC abc" +m = malloc(256) +memmove(m, s) +ss = cdata(m, 7) +if ss != "ABC abc": + raise "failed" diff --git a/Examples/test-suite/python/li_cpointer_cpp_runme.py b/Examples/test-suite/python/li_cpointer_cpp_runme.py new file mode 100644 index 000000000..c49e9fc28 --- /dev/null +++ b/Examples/test-suite/python/li_cpointer_cpp_runme.py @@ -0,0 +1,10 @@ +from li_cpointer_cpp import * + + +p = new_intp() +intp_assign(p, 3) + +if intp_value(p) != 3: + raise RuntimeError + +delete_intp(p) diff --git a/Examples/test-suite/python/li_std_vector_ptr_runme.py b/Examples/test-suite/python/li_std_vector_ptr_runme.py index 01c654109..baa92cfee 100644 --- a/Examples/test-suite/python/li_std_vector_ptr_runme.py +++ b/Examples/test-suite/python/li_std_vector_ptr_runme.py @@ -1,7 +1,56 @@ from li_std_vector_ptr import * +def check(val1, val2): + if val1 != val2: + raise RuntimeError("Values are not the same %s %s" % (val1, val2)) ip1 = makeIntPtr(11) ip2 = makeIntPtr(22) vi = IntPtrVector((ip1, ip2)) -displayVector(vi) +check(getValueFromVector(vi, 0), 11) +check(getValueFromVector(vi, 1), 22) + +vA = APtrVector([makeA(33), makeA(34)]) +check(getVectorValueA(vA, 0), 33) + +vB = BPtrVector([makeB(133), makeB(134)]) +check(getVectorValueB(vB, 0), 133) + +vC = CPtrVector([makeC(1133), makeC(1134)]) +check(getVectorValueC(vC, 0), 1133) + + +vA = [makeA(233), makeA(234)] +check(getVectorValueA(vA, 0), 233) + +vB = [makeB(333), makeB(334)] +check(getVectorValueB(vB, 0), 333) + +vC = [makeC(3333), makeC(3334)] +check(getVectorValueC(vC, 0), 3333) + +# mixed A and B should not be accepted +vAB = [makeA(999), makeB(999)] +try: + check(getVectorValueA(vAB, 0), 999) + raise RuntimeError("missed exception") +except TypeError: + pass + +b111 = makeB(111) +bNones = BPtrVector([None, b111, None]) + +bCount = 0 +noneCount = 0 +for b in bNones: + if b == None: + noneCount = noneCount + 1 + else: + if b.val != 111: + raise RuntimeError("b.val is wrong") + bCount = bCount + 1 + +if bCount != 1: + raise RuntimeError("bCount wrong") +if noneCount != 2: + raise RuntimeError("noneCount wrong") diff --git a/Examples/test-suite/python/li_std_vector_runme.py b/Examples/test-suite/python/li_std_vector_runme.py new file mode 100644 index 000000000..71460519d --- /dev/null +++ b/Examples/test-suite/python/li_std_vector_runme.py @@ -0,0 +1,10 @@ +from li_std_vector import * + +if typedef_test(101) != 101: + raise RuntimeError + +try: + sv = StructVector([None, None]) + raise RuntimeError("Using None should result in a TypeError") +except TypeError: + pass diff --git a/Examples/test-suite/python/operator_overload_runme.py b/Examples/test-suite/python/operator_overload_runme.py new file mode 100644 index 000000000..cf4277f35 --- /dev/null +++ b/Examples/test-suite/python/operator_overload_runme.py @@ -0,0 +1,77 @@ +from operator_overload import * + +# first check all the operators are implemented correctly from pure C++ code +Op_sanity_check() + +pop = Op(6)/Op(3) + +# test routine: +a=Op() +b=Op(5) +c=Op(b) # copy construct +d=Op(2) +dd=d # assignment operator + +# test equality +if not a!=b: + raise RuntimeError("a!=b") +if not b==c: + raise RuntimeError("b==c") +if not a!=d: + raise RuntimeError("a!=d") +if not d==dd: + raise RuntimeError("d==dd") + +# test < +if not a=c: + raise RuntimeError("b>=c") +if not b>d: + raise RuntimeError("b>d") +if not b>=d: + raise RuntimeError("b>=d") + +# test += +e=Op(3) +e+=d +if not e==b: + raise RuntimeError("e==b (%s==%s)" % (e.i, b.i)) +e-=c +if not e==a: + raise RuntimeError("e==a") +e=Op(1) +e*=b +if not e==c: + raise RuntimeError("e==c") +e/=d +if not e==d: + raise RuntimeError("e==d") +e%=c; +if not e==d: + raise RuntimeError("e==d") + +# test + +f=Op(1) +g=Op(1) +if not f+g==Op(2): + raise RuntimeError("f+g==Op(2)") +if not f-g==Op(0): + raise RuntimeError("f-g==Op(0)") +if not f*g==Op(1): + raise RuntimeError("f*g==Op(1)") +if not f/g==Op(1): + raise RuntimeError("f/g==Op(1)") +if not f%g==Op(0): + raise RuntimeError("f%g==Op(0)") + +# test unary operators +if not -a==a: + raise RuntimeError("-a==a") +if not -b==Op(-5): + raise RuntimeError("-b==Op(-5)") + diff --git a/Examples/test-suite/python/operbool_runme.py b/Examples/test-suite/python/operbool_runme.py index 708dea786..cdef85abc 100644 --- a/Examples/test-suite/python/operbool_runme.py +++ b/Examples/test-suite/python/operbool_runme.py @@ -1,3 +1,4 @@ #!/usr/bin/env python import operbool -assert not operbool.Test() +if operbool.Test(): + raise RuntimeError("operbool failed") diff --git a/Examples/test-suite/python/overload_extendc_runme.py b/Examples/test-suite/python/overload_extend2_runme.py similarity index 89% rename from Examples/test-suite/python/overload_extendc_runme.py rename to Examples/test-suite/python/overload_extend2_runme.py index ffd074a9d..923a9a7e3 100644 --- a/Examples/test-suite/python/overload_extendc_runme.py +++ b/Examples/test-suite/python/overload_extend2_runme.py @@ -1,6 +1,6 @@ -import overload_extendc +import overload_extend2 -f = overload_extendc.Foo() +f = overload_extend2.Foo() if f.test(3) != 1: raise RuntimeError if f.test("hello") != 2: diff --git a/Examples/test-suite/python/overload_extend_c_runme.py b/Examples/test-suite/python/overload_extend_c_runme.py new file mode 100644 index 000000000..35e6811f5 --- /dev/null +++ b/Examples/test-suite/python/overload_extend_c_runme.py @@ -0,0 +1,13 @@ +import overload_extend_c + +f = overload_extend_c.Foo() +if f.test() != 0: + raise RuntimeError +if f.test(3) != 1: + raise RuntimeError +if f.test("hello") != 2: + raise RuntimeError +if f.test(3, 2) != 5: + raise RuntimeError +if f.test(3.0) != 1003: + raise RuntimeError diff --git a/Examples/test-suite/python/primitive_types_runme.py b/Examples/test-suite/python/primitive_types_runme.py index 2e7ed7db7..b2060a028 100644 --- a/Examples/test-suite/python/primitive_types_runme.py +++ b/Examples/test-suite/python/primitive_types_runme.py @@ -1,3 +1,4 @@ +import sys from primitive_types import * var_init() @@ -436,3 +437,175 @@ if s != "hello": v = SetPos(1, 3) if v != 4: raise RuntimeError, "bad int typemap" + +# +# Check the bounds for converting various types +# + +# ctypes not available until 2.5 +if sys.version_info[0:2] <= (2, 4): + sys.exit(0) +import ctypes + +# Get the minimum and maximum values that fit in signed char, short, int, long, and long long +overchar = 2 ** 7 +while ctypes.c_byte(overchar).value > 0: + overchar *= 2 +minchar = -overchar +maxchar = overchar - 1 +maxuchar = 2 * maxchar + 1 +overshort = overchar +while ctypes.c_short(overshort).value > 0: + overshort *= 2 +minshort = -overshort +maxshort = overshort - 1 +maxushort = 2 * maxshort + 1 +overint = overshort +while ctypes.c_int(overint).value > 0: + overint *= 2 +minint = -overint +maxint = overint - 1 +maxuint = 2 * maxint + 1 +overlong = overint +while ctypes.c_long(overlong).value > 0: + overlong *= 2 +minlong = -overlong +maxlong = overlong - 1 +maxulong = 2 * maxlong + 1 +overllong = overlong +while ctypes.c_longlong(overllong).value > 0: + overllong *= 2 +minllong = -overllong +maxllong = overllong - 1 +maxullong = 2 * maxllong + 1 + +# Make sure Python 2's sys.maxint is the same as the maxlong we calculated +if sys.version_info[0] <= 2 and maxlong != sys.maxint: + raise RuntimeError, "sys.maxint is not the maximum value of a signed long" + +def checkType(t, e, val, delta): + """t = Test object, e = type name (e.g. ulong), val = max or min allowed value, delta = +1 for max, -1 for min""" + error = 0 + # Set the extreme valid value for var_* + setattr(t, 'var_' + e, val) + # Make sure it was set properly and works properly in the val_* and ref_* methods + if getattr(t, 'var_' + e) != val or getattr(t, 'val_' + e)(val) != val or getattr(t, 'ref_' + e)(val) != val: + error = 1 + # Make sure setting a more extreme value fails without changing the value + try: + a = getattr(t, 'var_' + e) + setattr(t, 'var_' + e, val + delta) + error = 1 + except OverflowError: + if a != getattr(t, 'var_' + e): + error = 1 + # Make sure the val_* and ref_* methods fail with a more extreme value + try: + getattr(t, 'val_' + e)(val + delta) + error = 1 + except OverflowError: + pass + try: + getattr(t, 'ref_' + e)(val + delta) + error = 1 + except OverflowError: + pass + if error: + raise RuntimeError, "bad " + e + " typemap" + +def checkFull(t, e, maxval, minval): + """Check the maximum and minimum bounds for the type given by e""" + checkType(t, e, maxval, 1) + checkType(t, e, minval, -1) + +checkFull(t, 'llong', maxllong, minllong) +checkFull(t, 'long', maxlong, minlong) +checkFull(t, 'int', maxint, minint) +checkFull(t, 'short', maxshort, minshort) +checkFull(t, 'schar', maxchar, minchar) +checkFull(t, 'ullong', maxullong, 0) +checkFull(t, 'ulong', maxulong, 0) +checkFull(t, 'uint', maxuint, 0) +checkFull(t, 'ushort', maxushort, 0) +checkFull(t, 'uchar', maxuchar, 0) + +def checkOverload(t, name, val, delta, prevval, limit): + """ + Check that overloading works + t = Test object + name = type name (e.g. ulong) + val = max or min allowed value + delta = +1 for max, -1 for min + prevval = corresponding value for one smaller type + limit = most extreme value for any type + """ + # If val == prevval, then the smaller typemap will win + if val != prevval: + # Make sure the most extreme value of this type gives the name of this type + if t.ovr_str(val) != name: + raise RuntimeError, "bad " + name + " typemap" + # Make sure a more extreme value doesn't give the name of this type + try: + if t.ovr_str(val + delta) == name: + raise RuntimeError, "bad " + name + " typemap" + if val == limit: + # Should raise NotImplementedError here since this is the largest integral type + raise RuntimeError, "bad " + name + " typemap" + except NotImplementedError: + # NotImplementedError is expected only if this is the most extreme type + if val != limit: + raise RuntimeError, "bad " + name + " typemap" + except TypeError: + # TypeError is raised instead if swig is run with -O or -fastdispatch + if val != limit: + raise RuntimeError, "bad " + name + " typemap" + +# Check that overloading works: uchar > schar > ushort > short > uint > int > ulong > long > ullong > llong +checkOverload(t, 'uchar', maxuchar, +1, 0, maxullong) +checkOverload(t, 'ushort', maxushort, +1, maxuchar, maxullong) +checkOverload(t, 'uint', maxuint, +1, maxushort, maxullong) +checkOverload(t, 'ulong', maxulong, +1, maxuint, maxullong) +checkOverload(t, 'ullong', maxullong, +1, maxulong, maxullong) +checkOverload(t, 'schar', minchar, -1, 0, minllong) +checkOverload(t, 'short', minshort, -1, minchar, minllong) +checkOverload(t, 'int', minint, -1, minshort, minllong) +checkOverload(t, 'long', minlong, -1, minint, minllong) +checkOverload(t, 'llong', minllong, -1, minlong, minllong) + +# Make sure that large ints can be converted to doubles properly +if val_double(sys.maxint + 1) != float(sys.maxint + 1): + raise RuntimeError, "bad double typemap" +if val_double(-sys.maxint - 2) != float(-sys.maxint - 2): + raise RuntimeError, "bad double typemap" + + +# Check the minimum and maximum values that fit in ptrdiff_t and size_t +def checkType(name, maxfunc, maxval, minfunc, minval, echofunc): + if maxfunc() != maxval: + raise RuntimeError, "bad " + name + " typemap" + if minfunc() != minval: + raise RuntimeError, "bad " + name + " typemap" + if echofunc(maxval) != maxval: + raise RuntimeError, "bad " + name + " typemap" + if echofunc(minval) != minval: + raise RuntimeError, "bad " + name + " typemap" + error = 0 + try: + echofunc(maxval + 1) + error = 1 + except OverflowError: + pass + if error == 1: + raise RuntimeError, "bad " + name + " typemap" + try: + echofunc(minval - 1) + error = 1 + except OverflowError: + pass + if error == 1: + raise RuntimeError, "bad " + name + " typemap" + +# sys.maxsize is the largest value supported by Py_ssize_t, which should be the same as ptrdiff_t +if sys.version_info[0:2] >= (2, 6): + checkType("ptrdiff_t", get_ptrdiff_max, sys.maxsize, get_ptrdiff_min, -(sys.maxsize + 1), ptrdiff_echo) + checkType("size_t", get_size_max, (2 * sys.maxsize) + 1, get_size_min, 0, size_echo) diff --git a/Examples/test-suite/python/python_abstractbase_runme3.py b/Examples/test-suite/python/python_abstractbase_runme3.py index b4a20f085..4fdc79935 100644 --- a/Examples/test-suite/python/python_abstractbase_runme3.py +++ b/Examples/test-suite/python/python_abstractbase_runme3.py @@ -6,6 +6,10 @@ from collections import * if is_python_builtin(): exit(0) +# Python abc is only turned on when -py3 option is passed to SWIG +if not is_swig_py3: + exit(0) + assert issubclass(Mapii, MutableMapping) assert issubclass(Multimapii, MutableMapping) assert issubclass(IntSet, MutableSet) diff --git a/Examples/test-suite/python/python_append_runme.py b/Examples/test-suite/python/python_append_runme.py index 2f6d94d9c..6675f3509 100644 --- a/Examples/test-suite/python/python_append_runme.py +++ b/Examples/test-suite/python/python_append_runme.py @@ -20,3 +20,10 @@ if grabpath() != os.path.dirname(mypath): if grabstaticpath() != os.path.basename(mypath): raise RuntimeError("grabstaticpath failed") + +clearstaticpath() +if grabstaticpath() != None: + raise RuntimeError("Resetting staticfuncpath failed") +Test.static_func() +if grabstaticpath() != os.path.basename(mypath): + raise RuntimeError("grabstaticpath failed") diff --git a/Examples/test-suite/python/python_builtin_runme.py b/Examples/test-suite/python/python_builtin_runme.py new file mode 100644 index 000000000..dc46b63f5 --- /dev/null +++ b/Examples/test-suite/python/python_builtin_runme.py @@ -0,0 +1,94 @@ +from python_builtin import * + +if is_python_builtin(): + # Test 0 for default tp_hash + vs = ValueStruct(1234) + h = hash(vs) + d = dict() + d[h] = "hi" + if h not in d: + raise RuntimeError("h should be in d") + h2 = hash(ValueStruct.inout(vs)) + if h != h2: + raise RuntimeError("default tp_hash not working") + + # Test 1 for tp_hash + if hash(SimpleValue(222)) != 222: + raise RuntimeError("tp_hash not working") + + # Test 2 for tp_hash + try: + # Was incorrectly raising: SystemError: error return without exception set + h = hash(BadHashFunctionReturnType()) + raise RuntimeError("Missing TypeError") + except TypeError: + pass + + # Test 3 for tp_hash + passed = False + try: + h = hash(ExceptionHashFunction()) + except RuntimeError, e: + passed = str(e).find("oops") != -1 + pass + + if not passed: + raise RuntimeError("did not catch exception in hash()") + + # Test 4 for tp_dealloc (which is handled differently to other slots in the SWIG source) + d = Dealloc1() + if cvar.Dealloc1CalledCount != 0: + raise RuntimeError("count should be 0") + del d + if cvar.Dealloc1CalledCount != 1: + raise RuntimeError("count should be 1") + + d = Dealloc2() + if cvar.Dealloc2CalledCount != 0: + raise RuntimeError("count should be 0") + del d + if cvar.Dealloc2CalledCount != 1: + raise RuntimeError("count should be 1") + + d = Dealloc3() + if cvar.Dealloc3CalledCount != 0: + raise RuntimeError("count should be 0") + del d + if cvar.Dealloc3CalledCount != 1: + raise RuntimeError("count should be 1") + + # Test 5 for python:compare feature + m10 = MyClass(10) + m20 = MyClass(20) + m15 = MyClass(15) + + if not m10 < m15: + raise RuntimeError("m10 < m15") + if not m10 < m20: + raise RuntimeError("m10 < m20") + if not m15 < m20: + raise RuntimeError("m15 < m20") + + if m10 > m15: + raise RuntimeError("m10 > m15") + if m10 > m20: + raise RuntimeError("m10 > m20") + if m15 > m20: + raise RuntimeError("m15 > m20") + + if MyClass.less_than_counts != 6: + raise RuntimeError("python:compare feature not working") + +sa = SimpleArray(5) +elements = [x for x in sa] +if elements != [0, 10, 20, 30, 40]: + raise RuntimeError("Iteration not working") +if len(sa) != 5: + raise RuntimeError("len not working") +for i in range(5): + if sa[i] != i*10: + raise RuntimeError("indexing not working") +subslice = sa[1:3] +elements = [x for x in subslice] +if elements != [10, 20]: + raise RuntimeError("slice not working") diff --git a/Examples/test-suite/python/python_destructor_exception_runme.py b/Examples/test-suite/python/python_destructor_exception_runme.py new file mode 100644 index 000000000..ee71ab33b --- /dev/null +++ b/Examples/test-suite/python/python_destructor_exception_runme.py @@ -0,0 +1,66 @@ +import python_destructor_exception +from StringIO import StringIO +import sys + +def error_function(): + python_destructor_exception.ClassWithThrowingDestructor().GetBlah() + +def runtest(): + attributeErrorOccurred = False + try: + error_function() + except AttributeError, e: + attributeErrorOccurred = True + return attributeErrorOccurred + +def test1(): + stderr_saved = sys.stderr + buffer = StringIO() + attributeErrorOccurred = False + try: + # Suppress stderr while making this call to suppress the output shown by PyErr_WriteUnraisable + sys.stderr = buffer + + attributeErrorOccurred = runtest() + finally: + sys.stderr.flush() + sys.stderr = stderr_saved + + if not attributeErrorOccurred: + raise RuntimeError("attributeErrorOccurred failed") + if not buffer.getvalue().count("I am the ClassWithThrowingDestructor dtor doing bad things") >= 1: + raise RuntimeError("ClassWithThrowingDestructor dtor doing bad things failed") + +class VectorHolder(object): + def __init__(self, v): + self.v = v + def gen(self): + for e in self.v: + yield e + +# See issue #559, #560, #573 - In Python 3.5, test2() call to the generator 'gen' was +# resulting in the following (not for -builtin where there is no call to SWIG_Python_CallFunctor +# as SwigPyObject_dealloc is not used): +# +# StopIteration +# +# During handling of the above exception, another exception occurred: +# ... +# SystemError: returned a result with an error set + +def addup(): + sum = 0 + for i in VectorHolder(python_destructor_exception.VectorInt([1, 2, 3])).gen(): + sum = sum + i + return sum + +def test2(): + sum = addup() + + if sum != 6: + raise RuntimeError("Sum is incorrect") + +# These two tests are different are two different ways to recreate essentially the same problem +# reported by Python 3.5 that an exception was already set when destroying a wrapped object +test1() +test2() diff --git a/Examples/test-suite/python/python_docstring_runme.py b/Examples/test-suite/python/python_docstring_runme.py new file mode 100644 index 000000000..0284ea0de --- /dev/null +++ b/Examples/test-suite/python/python_docstring_runme.py @@ -0,0 +1,100 @@ +from python_docstring import * +import inspect + +def check(got, expected): + expected_list = expected.split("\n") + got_list = got.split("\n") + + if expected_list != got_list: + raise RuntimeError("\n" + "Expected: " + str(expected_list) + "\n" + "Got : " + str(got_list)) + +# When getting docstrings, use inspect.getdoc(x) instead of x.__doc__ otherwise the different options +# such as -O, -builtin, -classic produce different initial indentation. + +check(inspect.getdoc(DocStrings.docstring1), + " line 1\n" + "line 2\n" + "\n" + "\n" + "\n" + "line 3" + ) + +check(inspect.getdoc(DocStrings.docstring2), + "line 1\n" + " line 2\n" + "\n" + "\n" + "\n" + " line 3" + ) + +check(inspect.getdoc(DocStrings.docstring3), + "line 1\n" + " line 2\n" + "\n" + "\n" + "\n" + " line 3" + ) + +check(inspect.getdoc(DocStrings.docstring4), + "line 1\n" + " line 2\n" + "\n" + "\n" + "\n" + " line 3" + ) + +check(inspect.getdoc(DocStrings.docstring5), + "line 1\n" + " line 2\n" + "\n" + "\n" + "\n" + " line 3" + ) + +check(inspect.getdoc(DocStrings.docstring6), + "line 1\n" + " line 2\n" + "\n" + "\n" + "\n" + " line 3" + ) + +check(inspect.getdoc(DocStrings.docstring7), + "line 1\n" + "line 2\n" + "line 3" + ) + +check(inspect.getdoc(DocStrings.docstringA), + "first line\n" + "second line" + ) + +check(inspect.getdoc(DocStrings.docstringB), + "first line\n" + "second line" + ) + +check(inspect.getdoc(DocStrings.docstringC), + "first line\n" + "second line" + ) + +# One line doc special case, use __doc__ +check(DocStrings.docstringX.__doc__, + " one line docs" + ) + +check(inspect.getdoc(DocStrings.docstringX), + "one line docs" + ) + +check(inspect.getdoc(DocStrings.docstringY), + "one line docs" + ) diff --git a/Examples/test-suite/python/python_extranative_runme.py b/Examples/test-suite/python/python_extranative_runme.py new file mode 100644 index 000000000..7be13a7ee --- /dev/null +++ b/Examples/test-suite/python/python_extranative_runme.py @@ -0,0 +1,11 @@ +import python_extranative + +vs = python_extranative.make_vector_string() +if not isinstance(vs, python_extranative.VectorString): + # will be of type tuple if extranative not working + raise RuntimeError("Not of type VectorString") + +for s1, s2 in zip(vs, ["one", "two"]): + if s1 != s2: + raise RuntimeError("Mismatch: " + s1 + " " + s2) + diff --git a/Examples/test-suite/python/python_moduleimport_runme.py b/Examples/test-suite/python/python_moduleimport_runme.py new file mode 100644 index 000000000..cdb860730 --- /dev/null +++ b/Examples/test-suite/python/python_moduleimport_runme.py @@ -0,0 +1,7 @@ +import python_moduleimport + +if python_moduleimport.simple_function(99) != 99: + raise RuntimeError("simple_function") + +if python_moduleimport.extra_import_variable != "custom import of _python_moduleimport": + raise RuntimeError("custom import") diff --git a/Examples/test-suite/python/python_pickle_runme.py b/Examples/test-suite/python/python_pickle_runme.py new file mode 100644 index 000000000..cf2847919 --- /dev/null +++ b/Examples/test-suite/python/python_pickle_runme.py @@ -0,0 +1,35 @@ +import python_pickle + +import pickle +import sys + +def is_new_style_class(cls): + return hasattr(cls, "__class__") + +def check(p): + msg = p.msg + if msg != "hi there": + raise RuntimeError("Bad, got: " + msg) + +if not is_new_style_class(python_pickle.PickleMe): + sys.exit(0) + +python_pickle.cvar.debug = False + +p = python_pickle.PickleMe("hi there") +check(p) + +r = p.__reduce__() +if python_pickle.cvar.debug: + print "__reduce__ returned:", r +pickle_string = pickle.dumps(p) +newp = pickle.loads(pickle_string) +check(newp) + +# Not yet working... some crash and others are not producing a sensible "can't be pickled" error +#nfp = python_pickle.NotForPickling("no no") +#print nfp.__reduce__() +#pickle_string = pickle.dumps(nfp) +#print pickle_string +#newp = pickle.loads(pickle_string) +#print newp.msg diff --git a/Examples/test-suite/python/python_strict_unicode_runme.py b/Examples/test-suite/python/python_strict_unicode_runme.py new file mode 100644 index 000000000..642e127fa --- /dev/null +++ b/Examples/test-suite/python/python_strict_unicode_runme.py @@ -0,0 +1,79 @@ +import python_strict_unicode +from sys import version_info + +test_bytes = 'hello \x01world\x99' +BYTES = 'BYTES' +test_unicode = u'h\udce9llo w\u00f6rld' + +# Python < 2.6 rejects the b prefix for byte string literals as a SyntaxError, +# so instead create Python3 bytes objects by encoding unicode strings as +# latin-1, which maps code points 0-255 directly to the corresponding bytes. +if version_info[0] >= 3: + test_bytes = test_bytes.encode('latin-1') + BYTES = BYTES.encode('latin-1') + +# Test that byte string inputs and outputs work as expected +bdbl = python_strict_unicode.double_str(test_bytes) +if bdbl != test_bytes + test_bytes: + raise RuntimeError("Failed to double string") +if type(bdbl) != type(BYTES): + raise RuntimeError("Wrong type output for string") +bout = python_strict_unicode.same_str(test_bytes) +if bout != test_bytes: + raise RuntimeError("Failed to copy char*") +if type(bout) != type(BYTES): + raise RuntimeError("Wrong type output for char*") + +# Test that unicode string inputs and outputs work as expected +udbl = python_strict_unicode.double_wstr(test_unicode) +if udbl != test_unicode + test_unicode: + raise RuntimeError("Failed to double wide string") +if type(udbl) != type(u''): + raise RuntimeError("Wrong type output for wide string") +uout = python_strict_unicode.same_wstr(test_unicode) +if uout != test_unicode: + raise RuntimeError("Failed to copy wchar_t*") +if type(uout) != type(u''): + raise RuntimeError("Wrong type output for wchar_t*") + +# Test that overloading is handled properly +bovr = python_strict_unicode.overload(test_bytes) +if bovr != BYTES: + raise RuntimeError("Failed to return bytes from overload") +if type(bovr) != type(BYTES): + raise RuntimeError("Wrong type output from overload") +uovr = python_strict_unicode.overload(test_unicode) +if uovr != u'UNICODE': + raise RuntimeError("Failed to return unicode from overload") +if type(uovr) != type(u''): + raise RuntimeERror("Wrong type output from overload") + +# Test that bytes aren't accepted as wide strings and unicode isn't accepted as narrow strings +try: + python_strict_unicode.double_str(test_unicode) + error = 1 +except TypeError: + error = 0 +if error: + raise RuntimeError("Unicode accepted for string") +try: + python_strict_unicode.same_str(test_unicode) + error = 1 +except TypeError: + error = 0 +if error: + raise RuntimeError("Unicode accepted for char*") +try: + python_strict_unicode.double_wstr(test_bytes) + error = 1 +except TypeError: + error = 0 +if error: + raise RuntimeError("Bytes accepted for wstring") +try: + python_strict_unicode.same_wstr(test_bytes) + error = 1 +except TypeError: + error = 0 +if error: + raise RuntimeError("Bytes accepted for wchar_t*") diff --git a/Examples/test-suite/python/rename_rstrip_encoder_runme.py b/Examples/test-suite/python/rename_rstrip_encoder_runme.py new file mode 100644 index 000000000..84072f7f2 --- /dev/null +++ b/Examples/test-suite/python/rename_rstrip_encoder_runme.py @@ -0,0 +1,5 @@ +from rename_rstrip_encoder import * + +s = SomeThing() +a = AnotherThing() +a.DoClsX() diff --git a/Examples/test-suite/python/template_default_arg_overloaded_extend_runme.py b/Examples/test-suite/python/template_default_arg_overloaded_extend_runme.py new file mode 100644 index 000000000..1f71066cb --- /dev/null +++ b/Examples/test-suite/python/template_default_arg_overloaded_extend_runme.py @@ -0,0 +1,20 @@ +from template_default_arg_overloaded_extend import * + +def check(flag): + if not flag: + raise RuntimeError("failed") + +rs = ResultSet() + +check(rs.go_get_method(0, SearchPoint()) == -1) +check(rs.go_get_method(0, SearchPoint(), 100) == 100) + +check(rs.go_get_template(0, SearchPoint()) == -2) +check(rs.go_get_template(0, SearchPoint(), 100) == 100) + +check(rs.over() == "over(int)") +check(rs.over(10) == "over(int)") +check(rs.over(SearchPoint()) == "over(giai2::SearchPoint, int)") +check(rs.over(SearchPoint(), 10) == "over(giai2::SearchPoint, int)") +check(rs.over(True, SearchPoint()) == "over(bool, gaia2::SearchPoint, int)") +check(rs.over(True, SearchPoint(), 10) == "over(bool, gaia2::SearchPoint, int)") diff --git a/Examples/test-suite/python/template_default_arg_overloaded_runme.py b/Examples/test-suite/python/template_default_arg_overloaded_runme.py new file mode 100644 index 000000000..22d46b39d --- /dev/null +++ b/Examples/test-suite/python/template_default_arg_overloaded_runme.py @@ -0,0 +1,47 @@ +from template_default_arg_overloaded import * + +def check(expected, got): + if expected != got: + raise RuntimeError("Expected: " + str(expected) + " got: " + str(got)) + + +pl = PropertyList() +check(1, pl.setInt("int", 10)) +check(1, pl.setInt("int", 10, False)) + +check(2, pl.set("int", pl)) +check(2, pl.set("int", pl, False)) + +check(3, pl.setInt("int", 10, "int")) +check(3, pl.setInt("int", 10, "int", False)) + + +pl = PropertyListGlobal() +check(1, pl.setIntGlobal("int", 10)) +check(1, pl.setIntGlobal("int", 10, False)) + +check(2, pl.set("int", pl)) +check(2, pl.set("int", pl, False)) + +check(3, pl.setIntGlobal("int", 10, "int")) +check(3, pl.setIntGlobal("int", 10, "int", False)) + + +check(1, GoopIntGlobal(10)) +check(1, GoopIntGlobal(10, True)) + +check(2, goopGlobal(3)) +check(2, goopGlobal()) + +check(3, GoopIntGlobal("int", False)) +check(3, GoopIntGlobal("int")) + + +check(1, GoopInt(10)) +check(1, GoopInt(10, True)) + +check(2, goop(3)) +check(2, goop()) + +check(3, GoopInt("int", False)) +check(3, GoopInt("int")) diff --git a/Examples/test-suite/python/typemap_documentation_runme.py b/Examples/test-suite/python/typemap_documentation_runme.py new file mode 100644 index 000000000..3d1c6fa8c --- /dev/null +++ b/Examples/test-suite/python/typemap_documentation_runme.py @@ -0,0 +1,20 @@ +import typemap_documentation + +f = typemap_documentation.Foo() +f.x = 55 +b = typemap_documentation.Bar() +b.y = 44 + +if 55 != typemap_documentation.GrabVal(f): + raise RuntimeError("bad value") + +try: + typemap_documentation.GrabVal(b) + raise RuntimeError("unexpected exception") +except TypeError: + pass + +if 55 != typemap_documentation.GrabValFooBar(f): + raise RuntimeError("bad f value") +if 44 != typemap_documentation.GrabValFooBar(b): + raise RuntimeError("bad b value") diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py index e1fc7adec..fa9c51437 100644 --- a/Examples/test-suite/python/unicode_strings_runme.py +++ b/Examples/test-suite/python/unicode_strings_runme.py @@ -12,3 +12,16 @@ if sys.version_info[0:2] >= (3, 1): raise ValueError('Test comparison mismatch') if unicode_strings.non_utf8_std_string() != test_string: raise ValueError('Test comparison mismatch') + +def check(s1, s2): + if s1 != s2: + raise RuntimeError("{} != {}".format(s1, s2)) + +# Testing SWIG_PYTHON_2_UNICODE flag which allows unicode strings to be passed to C +if sys.version_info[0:2] < (3, 0): + check(unicode_strings.charstring("hello1"), "hello1") + check(unicode_strings.charstring(str(u"hello2")), "hello2") + check(unicode_strings.charstring(u"hello3"), "hello3") + check(unicode_strings.charstring(unicode("hello4")), "hello4") + unicode_strings.charstring(u"hell\xb05") + unicode_strings.charstring(u"hell\u00f66") diff --git a/Examples/test-suite/python_abstractbase.i b/Examples/test-suite/python_abstractbase.i index 65f3d9931..2146e758e 100644 --- a/Examples/test-suite/python_abstractbase.i +++ b/Examples/test-suite/python_abstractbase.i @@ -24,3 +24,9 @@ bool is_python_builtin() { return true; } bool is_python_builtin() { return false; } #endif %} + +#ifdef SWIGPYTHON_PY3 // set when using -py3 +#define is_swig_py3 1 +#else +#define is_swig_py3 0 +#endif diff --git a/Examples/test-suite/python_append.i b/Examples/test-suite/python_append.i index f37a6c199..2a71b5784 100644 --- a/Examples/test-suite/python_append.i +++ b/Examples/test-suite/python_append.i @@ -12,6 +12,9 @@ def grabpath(): return funcpath def grabstaticpath(): return staticfuncpath +def clearstaticpath(): + global staticfuncpath + staticfuncpath = None %} %pythonappend Test::func %{ diff --git a/Examples/test-suite/python_builtin.i b/Examples/test-suite/python_builtin.i new file mode 100644 index 000000000..4108f6753 --- /dev/null +++ b/Examples/test-suite/python_builtin.i @@ -0,0 +1,207 @@ +// Test customizing slots when using the -builtin option + +%module python_builtin + +%{ +#if defined(_MSC_VER) + #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif +%} + +%inline %{ +#ifdef SWIGPYTHON_BUILTIN +bool is_python_builtin() { return true; } +#else +bool is_python_builtin() { return false; } +#endif +%} + +// Test 0 for default tp_hash +%inline %{ +struct ValueStruct { + int value; + ValueStruct(int value) : value(value) {} + static ValueStruct *inout(ValueStruct *v) { + return v; + } +}; +%} + +// Test 1 for tp_hash +#if defined(SWIGPYTHON_BUILTIN) +%feature("python:tp_hash") SimpleValue "SimpleValueHashFunction" +#endif + +%inline %{ +struct SimpleValue { + int value; + SimpleValue(int value) : value(value) {} +}; +%} + +%{ +#if PY_VERSION_HEX >= 0x03020000 +Py_hash_t SimpleValueHashFunction(PyObject *v) +#else +long SimpleValueHashFunction(PyObject *v) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *) v; + SimpleValue *p = (SimpleValue *)sobj->ptr; + return p->value; +} +hashfunc test_hashfunc_cast() { + return SimpleValueHashFunction; +} +%} + +// Test 2 for tp_hash +#if defined(SWIGPYTHON_BUILTIN) +%feature("python:slot", "tp_hash", functype="hashfunc") BadHashFunctionReturnType::bad_hash_function; +#endif + +%inline %{ +struct BadHashFunctionReturnType { + static const char * bad_hash_function() { + return "bad hash function"; + } +}; +%} + +// Test 3 for tp_hash +#if defined(SWIGPYTHON_BUILTIN) +%feature("python:slot", "tp_hash", functype="hashfunc") ExceptionHashFunction::exception_hash_function; +#endif + +%catches(const char *) exception_hash_function; + +%inline %{ +#if PY_VERSION_HEX < 0x03020000 + #define Py_hash_t long +#endif +struct ExceptionHashFunction { + static Py_hash_t exception_hash_function() { + throw "oops"; + } +}; +%} + +// Test 4 for tp_dealloc (which is handled differently to other slots in the SWIG source) +#if defined(SWIGPYTHON_BUILTIN) +%feature("python:tp_dealloc") Dealloc1 "Dealloc1Destroyer" +%feature("python:tp_dealloc") Dealloc2 "Dealloc2Destroyer" +%feature("python:slot", "tp_dealloc", functype="destructor") Dealloc3::Destroyer; +#endif + +%inline %{ +static int Dealloc1CalledCount = 0; +static int Dealloc2CalledCount = 0; +static int Dealloc3CalledCount = 0; + +struct Dealloc1 { +}; +struct Dealloc2 { + ~Dealloc2() {} +}; +struct Dealloc3 { + void Destroyer() { + Dealloc3CalledCount++; + delete this; + } +}; +%} + +%{ +void Dealloc1Destroyer(PyObject *v) { + SwigPyObject *sobj = (SwigPyObject *) v; + Dealloc1 *p = (Dealloc1 *)sobj->ptr; + delete p; + Dealloc1CalledCount++; +} +void Dealloc2Destroyer(PyObject *v) { + SwigPyObject *sobj = (SwigPyObject *) v; + Dealloc2 *p = (Dealloc2 *)sobj->ptr; + delete p; + Dealloc2CalledCount++; +} +%} + +// Test 5 for python:compare feature +%feature("python:compare", "Py_LT") MyClass::lessThan; + +%inline %{ + class MyClass { + public: + MyClass(int val = 0) : val(val) {} + bool lessThan(const MyClass& other) const { + less_than_counts++; + return val < other.val; + } + int val; + static int less_than_counts; + }; + int MyClass::less_than_counts = 0; +%} + +// Test 6 add in container __getitem__ to support basic sequence protocol +// Tests overloaded functions being used for more than one slot (mp_subscript and sq_item) +%include +%include +%apply int {Py_ssize_t} +%typemap(in) PySliceObject * { + if (!PySlice_Check($input)) + SWIG_exception(SWIG_TypeError, "in method '$symname', argument $argnum of type '$type'"); + $1 = (PySliceObject *)$input; +} +%typemap(typecheck,precedence=300) PySliceObject* { + $1 = PySlice_Check($input); +} + +%feature("python:slot", "mp_subscript", functype="binaryfunc") SimpleArray::__getitem__(PySliceObject *slice); +%feature("python:slot", "sq_item", functype="ssizeargfunc") SimpleArray::__getitem__(Py_ssize_t n); +%feature("python:slot", "sq_length", functype="lenfunc") SimpleArray::__len__; +%inline %{ + class SimpleArray { + Py_ssize_t size; + int numbers[5]; + public: + SimpleArray(Py_ssize_t size) : size(size) { + for (Py_ssize_t x = 0; x= (int)size) + throw std::out_of_range("Index too large"); + return numbers[n]; + } + + SimpleArray __getitem__(PySliceObject *slice) throw (std::out_of_range, std::invalid_argument) { + if (!PySlice_Check(slice)) + throw std::invalid_argument("Slice object expected"); + Py_ssize_t i, j, step; +#if PY_VERSION_HEX >= 0x03020000 + PySlice_GetIndices((PyObject *)slice, size, &i, &j, &step); +#else + PySlice_GetIndices((PySliceObject *)slice, size, &i, &j, &step); +#endif + if (step != 1) + throw std::invalid_argument("Only a step size of 1 is implemented"); + + { + Py_ssize_t ii = i<0 ? 0 : i>=size ? size-1 : i; + Py_ssize_t jj = j<0 ? 0 : j>=size ? size-1 : j; + if (ii > jj) + throw std::invalid_argument("getitem i should not be larger than j"); + SimpleArray n(jj-ii); + for (Py_ssize_t x = 0; x +%template(VectorInt) std::vector; diff --git a/Examples/test-suite/python_docstring.i b/Examples/test-suite/python_docstring.i new file mode 100644 index 000000000..3b88167eb --- /dev/null +++ b/Examples/test-suite/python_docstring.i @@ -0,0 +1,98 @@ +%module python_docstring + +// Test indentation when using the docstring feature. +// Checks tabs and spaces as input for indentation. + +%feature("docstring") docstring1 %{ + line 1 +line 2 + + + +line 3 +%} + +%feature("docstring") docstring2 %{ +line 1 + line 2 + + + + line 3 + %} + +%feature("docstring") docstring3 %{ + line 1 + line 2 + + + + line 3 + %} + +%feature("docstring") docstring4 %{ + line 1 + line 2 + + + + line 3 + %} + +%feature("docstring") docstring5 +%{ line 1 + line 2 + + + + line 3 + %} + +%feature("docstring") docstring6 +{ + line 1 + line 2 + + + + line 3 +} + +%feature("docstring") docstring7 +{ +line 1 +line 2 +line 3 +} + +%feature("docstring") docstringA +%{ first line + second line%} + +%feature("docstring") docstringB +%{ first line + second line%} + +%feature("docstring") docstringC +%{ first line + second line%} + +%feature("docstring") docstringX " one line docs" +%feature("docstring") docstringY "one line docs" + +%inline %{ +struct DocStrings { + void docstring1() {} + void docstring2() {} + void docstring3() {} + void docstring4() {} + void docstring5() {} + void docstring6() {} + void docstring7() {} + void docstringA() {} + void docstringB() {} + void docstringC() {} + void docstringX() {} + void docstringY() {} +}; +%} diff --git a/Examples/test-suite/python_extranative.i b/Examples/test-suite/python_extranative.i new file mode 100644 index 000000000..04361b3e6 --- /dev/null +++ b/Examples/test-suite/python_extranative.i @@ -0,0 +1,16 @@ +%module(extranative="1") python_extranative + +%include +%include + +%template(VectorString) std::vector; + +%inline %{ +std::vector make_vector_string() { + std::vector vs; + vs.push_back("one"); + vs.push_back("two"); + return vs; +} +%} + diff --git a/Examples/test-suite/python_moduleimport.i b/Examples/test-suite/python_moduleimport.i new file mode 100644 index 000000000..48b794cbc --- /dev/null +++ b/Examples/test-suite/python_moduleimport.i @@ -0,0 +1,26 @@ +#if !defined(SWIGPYTHON_BUILTIN) +%define MODULEIMPORT +" +#print 'Loading low-level module $module' +import $module +#print 'Module has loaded' +extra_import_variable = 'custom import of $module' +" +%enddef + +#else +%define MODULEIMPORT +" +#print 'Loading low-level module $module' +extra_import_variable = 'custom import of $module' +from $module import * +#print 'Module has loaded' +" +%enddef +#endif + +%module(moduleimport=MODULEIMPORT) python_moduleimport + +%inline %{ +int simple_function(int i) { return i; } +%} diff --git a/Examples/test-suite/python_pickle.i b/Examples/test-suite/python_pickle.i new file mode 100644 index 000000000..fbb3d05a8 --- /dev/null +++ b/Examples/test-suite/python_pickle.i @@ -0,0 +1,56 @@ +%module python_pickle + + +%include + +%extend PickleMe { +#if 0 +// Note: %pythoncode can't be used with -builtin +%pythoncode %{ +def __reduce__(self): + print "In Python __reduce__" + return (type(self), (self.msg, )) +%} +#else + // Equivalent to Python code above + PyObject *__reduce__() { + if (debug) + std::cout << "In C++ __reduce__" << std::endl; + PyObject *args = PyTuple_New(1); + PyTuple_SetItem(args, 0, SWIG_From_std_string(self->msg)); + + swig_type_info *ty = SWIGTYPE_p_PickleMe; + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; +#if defined(SWIGPYTHON_BUILTIN) + PyObject *callable = (PyObject *)data->pytype; +#else + PyObject *callable = data->klass; +#endif + Py_INCREF(callable); + + PyObject *ret = PyTuple_New(2); + PyTuple_SetItem(ret, 0, callable); + PyTuple_SetItem(ret, 1, args); + return ret; + } +#endif +} + +%inline %{ +#include + +bool debug = false; + +struct PickleMe { + std::string msg; + PickleMe(const std::string& msg) : msg(msg) { + if (debug) + std::cout << "In C++ constructor " << " [" << msg << "]" << std::endl; + } +}; + +struct NotForPickling { + std::string msg; + NotForPickling(const std::string& msg) : msg(msg) {} +}; +%} diff --git a/Examples/test-suite/python_strict_unicode.i b/Examples/test-suite/python_strict_unicode.i new file mode 100644 index 000000000..93240a9b7 --- /dev/null +++ b/Examples/test-suite/python_strict_unicode.i @@ -0,0 +1,41 @@ +%module python_strict_unicode + +%include +%include + +%begin %{ +#define SWIG_PYTHON_STRICT_BYTE_CHAR +#define SWIG_PYTHON_STRICT_UNICODE_WCHAR +%} + +%inline %{ +std::string double_str(const std::string& in) +{ + return in + in; +} + +char *same_str(char* in) +{ + return in; +} + +std::wstring double_wstr(const std::wstring& in) +{ + return in + in; +} + +wchar_t *same_wstr(wchar_t* in) +{ + return in; +} + +std::wstring overload(const std::wstring& in) +{ + return L"UNICODE"; +} + +std::string overload(const std::string& in) +{ + return "BYTES"; +} +%} diff --git a/Examples/test-suite/python_varargs_typemap.i b/Examples/test-suite/python_varargs_typemap.i index c7d8b83ec..f05fb98eb 100644 --- a/Examples/test-suite/python_varargs_typemap.i +++ b/Examples/test-suite/python_varargs_typemap.i @@ -11,7 +11,7 @@ argc = PyTuple_Size(varargs); if (argc > 10) { PyErr_SetString(PyExc_ValueError, "Too many arguments"); - return NULL; + SWIG_fail; } for (i = 0; i < argc; i++) { PyObject *pyobj = PyTuple_GetItem(varargs, i); @@ -20,7 +20,7 @@ PyObject *pystr; if (!PyUnicode_Check(pyobj)) { PyErr_SetString(PyExc_ValueError, "Expected a string"); - return NULL; + SWIG_fail; } pystr = PyUnicode_AsUTF8String(pyobj); str = strdup(PyBytes_AsString(pystr)); @@ -28,7 +28,7 @@ %#else if (!PyString_Check(pyobj)) { PyErr_SetString(PyExc_ValueError, "Expected a string"); - return NULL; + SWIG_fail; } str = PyString_AsString(pyobj); %#endif diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index d0489531f..d75d4c042 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -5,7 +5,8 @@ LANGUAGE = r SCRIPTSUFFIX = _runme.R WRAPSUFFIX = .R -RUNR = R CMD BATCH --no-save --no-restore +R_OPT = --quiet --no-save --no-restore +RUNR = R CMD BATCH $(R_OPT) '--args $(SCRIPTDIR)' srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -18,7 +19,8 @@ C_TEST_CASES += \ CPP_TEST_CASES += \ r_double_delete \ r_overload_array \ - r_sexp + r_sexp \ + r_overload_comma include $(srcdir)/../common.mk @@ -44,29 +46,29 @@ include $(srcdir)/../common.mk +$(swig_and_compile_multi_cpp) $(run_multitestcase) + # Runs the testcase. # # Run the runme if it exists. If not just load the R wrapper to # check for syntactic correctness run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) || (cat $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX)out ; false); \ else \ - $(RUNTOOL) $(RUNR) ./$(SCRIPTPREFIX)$*$(WRAPSUFFIX); \ + $(RUNTOOL) $(RUNR) ./$(SCRIPTPREFIX)$*$(WRAPSUFFIX) || (cat ./$(SCRIPTPREFIX)$*$(WRAPSUFFIX)out ; false); \ fi run_multitestcase = \ for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" \ - $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX); \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX) || (cat $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX)out ; false); \ else \ - $(RUNTOOL) $(RUNR) ./$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX); \ + $(RUNTOOL) $(RUNR) ./$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX) || (cat ./$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX)out ; false); \ fi; \ done # Clean clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" r_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' r_clean %.clean: @rm -f $*.R $*_wrap.so $*_wrap.cpp $*_wrap.c $*_wrap.o $*_runme.Rout $*.Rout diff --git a/Examples/test-suite/r/arrays_dimensionless_runme.R b/Examples/test-suite/r/arrays_dimensionless_runme.R index 9b97de2d8..4fc2541ff 100644 --- a/Examples/test-suite/r/arrays_dimensionless_runme.R +++ b/Examples/test-suite/r/arrays_dimensionless_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("arrays_dimensionless", .Platform$dynlib.ext, sep="")) source("arrays_dimensionless.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/funcptr_runme.R b/Examples/test-suite/r/funcptr_runme.R index 3d5281bfa..c6127ef68 100644 --- a/Examples/test-suite/r/funcptr_runme.R +++ b/Examples/test-suite/r/funcptr_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("funcptr", .Platform$dynlib.ext, sep="")) source("funcptr.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/ignore_parameter_runme.R b/Examples/test-suite/r/ignore_parameter_runme.R index 89e461d71..612b70013 100644 --- a/Examples/test-suite/r/ignore_parameter_runme.R +++ b/Examples/test-suite/r/ignore_parameter_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("ignore_parameter", .Platform$dynlib.ext, sep="")) source("ignore_parameter.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/integers_runme.R b/Examples/test-suite/r/integers_runme.R index e31099a3b..6e2f63b70 100644 --- a/Examples/test-suite/r/integers_runme.R +++ b/Examples/test-suite/r/integers_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("integers", .Platform$dynlib.ext, sep="")) source("integers.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/li_std_vector_runme.R b/Examples/test-suite/r/li_std_vector_runme.R new file mode 100644 index 000000000..bd02d840a --- /dev/null +++ b/Examples/test-suite/r/li_std_vector_runme.R @@ -0,0 +1,19 @@ +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + +dyn.load(paste("li_std_vector", .Platform$dynlib.ext, sep="")) +source("li_std_vector.R") +cacheMetaData(1) + +testvec <- c(1, 2, 3) + +unittest(half(testvec), testvec/2) +unittest(average(testvec), mean(testvec)) +## string vector test +vlen <- 13 +stringvec <- paste(letters[1:vlen], as.character(rnorm(vlen))) +unittest(rev(stringvec), RevStringVec(stringvec)) +q(save="no") + + + diff --git a/Examples/test-suite/r/overload_method_runme.R b/Examples/test-suite/r/overload_method_runme.R index afb590a74..790f3df10 100644 --- a/Examples/test-suite/r/overload_method_runme.R +++ b/Examples/test-suite/r/overload_method_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("overload_method", .Platform$dynlib.ext, sep="")) source("overload_method.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/preproc_constants_runme.R b/Examples/test-suite/r/preproc_constants_runme.R new file mode 100644 index 000000000..138786e67 --- /dev/null +++ b/Examples/test-suite/r/preproc_constants_runme.R @@ -0,0 +1,12 @@ +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + +dyn.load(paste("preproc_constants", .Platform$dynlib.ext, sep="")) +source("preproc_constants.R") +cacheMetaData(1) + +v <- enumToInteger('kValue', '_MyEnum') +print(v) +# temporarily removed until fixed (in progress, see Github patch #500) +#unittest(v,4) +q(save="no") diff --git a/Examples/test-suite/r/r_copy_struct_runme.R b/Examples/test-suite/r/r_copy_struct_runme.R index 21bd93b64..deadc61fe 100644 --- a/Examples/test-suite/r/r_copy_struct_runme.R +++ b/Examples/test-suite/r/r_copy_struct_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("r_copy_struct", .Platform$dynlib.ext, sep="")) source("r_copy_struct.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/r_legacy_runme.R b/Examples/test-suite/r/r_legacy_runme.R index 7e5ade87f..3ca229ff8 100644 --- a/Examples/test-suite/r/r_legacy_runme.R +++ b/Examples/test-suite/r/r_legacy_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("r_legacy", .Platform$dynlib.ext, sep="")) source("r_legacy.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/r_sexp_runme.R b/Examples/test-suite/r/r_sexp_runme.R index 96b36e8af..e7b28a965 100644 --- a/Examples/test-suite/r/r_sexp_runme.R +++ b/Examples/test-suite/r/r_sexp_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("r_sexp", .Platform$dynlib.ext, sep="")) source("r_sexp.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/rename_simple_runme.R b/Examples/test-suite/r/rename_simple_runme.R index b25aeb844..0628ca6c9 100644 --- a/Examples/test-suite/r/rename_simple_runme.R +++ b/Examples/test-suite/r/rename_simple_runme.R @@ -1,4 +1,6 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) + dyn.load(paste("rename_simple", .Platform$dynlib.ext, sep="")) source("rename_simple.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/simple_array_runme.R b/Examples/test-suite/r/simple_array_runme.R index a6758dedd..fe70dc324 100644 --- a/Examples/test-suite/r/simple_array_runme.R +++ b/Examples/test-suite/r/simple_array_runme.R @@ -1,4 +1,5 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) dyn.load(paste("simple_array", .Platform$dynlib.ext, sep="")) source("simple_array.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/unions_runme.R b/Examples/test-suite/r/unions_runme.R index 76870d10c..fd148c7ef 100644 --- a/Examples/test-suite/r/unions_runme.R +++ b/Examples/test-suite/r/unions_runme.R @@ -1,4 +1,5 @@ -source("unittest.R") +clargs <- commandArgs(trailing=TRUE) +source(file.path(clargs[1], "unittest.R")) dyn.load(paste("unions", .Platform$dynlib.ext, sep="")) source("unions.R") cacheMetaData(1) diff --git a/Examples/test-suite/r/unittest.R b/Examples/test-suite/r/unittest.R index 0633c7715..b55b4a3f3 100644 --- a/Examples/test-suite/r/unittest.R +++ b/Examples/test-suite/r/unittest.R @@ -1,5 +1,5 @@ unittest <- function (x,y) { - if (x==y) { + if (all(x==y)) { print("PASS") } else { print("FAIL") @@ -8,7 +8,7 @@ unittest <- function (x,y) { } unittesttol <- function(x,y,z) { - if (abs(x-y) < z) { + if (all(abs(x-y) < z)) { print("PASS") } else { print("FAIL") diff --git a/Examples/test-suite/r_copy_struct.i b/Examples/test-suite/r_copy_struct.i index fda321afb..6a79b5422 100644 --- a/Examples/test-suite/r_copy_struct.i +++ b/Examples/test-suite/r_copy_struct.i @@ -48,7 +48,7 @@ getA() return a; } -static struct A fixed = {20, 3, 42.0}; +static struct A fixed = {20, 3, 42.0, 0, 0}; struct A * getARef() diff --git a/Examples/test-suite/r_overload_comma.i b/Examples/test-suite/r_overload_comma.i new file mode 100644 index 000000000..020adb387 --- /dev/null +++ b/Examples/test-suite/r_overload_comma.i @@ -0,0 +1,14 @@ +%module r_overload_comma + +%inline %{ +class r_overload_comma +{ + public: + int getMember1()const {return _member1;} + void setMember1ThatEndsWithWord_get(int arg) { _member1=arg; } + void setMember1ThatEndsWithWord_get(char* arg) {_member1=atoi(arg);} + + private: + int _member1; +}; + %} diff --git a/Examples/test-suite/rename_rstrip_encoder.i b/Examples/test-suite/rename_rstrip_encoder.i new file mode 100644 index 000000000..4ecbe129f --- /dev/null +++ b/Examples/test-suite/rename_rstrip_encoder.i @@ -0,0 +1,15 @@ +%module rename_rstrip_encoder + +// strip the Cls suffix from all identifiers +%rename("%(rstrip:[Cls])s") ""; + +%inline %{ + +class SomeThingCls { +}; + +struct AnotherThingCls { + void DoClsXCls() {} +}; + +%} diff --git a/Examples/test-suite/rename_wildcard.i b/Examples/test-suite/rename_wildcard.i new file mode 100644 index 000000000..f9e0347b0 --- /dev/null +++ b/Examples/test-suite/rename_wildcard.i @@ -0,0 +1,140 @@ +// Test rename overriding a wildcard rename +%module rename_wildcard + +%rename(mm1) *::m1; +%rename(mm2) *::m2; +%rename(tt2) *::t2; +%rename(mm3) *::m3(); +%rename(tt3) *::t3(); +%rename(m_4) m4; +%rename(t_4) t4; +%rename(mm4) *::m4; +%rename(tt4) *::t4; +%rename(mm5) *::m5; +%rename(tt5) *::t5; +%rename(opint) *::operator int; +%rename(opdouble) *::operator double; + +// No declaration +%rename(mm2a) GlobalWildStruct::m2; +%rename(mm2b) GlobalWildTemplateStruct::m2; +%rename(mm2c) Space::SpaceWildStruct::m2; +%rename(mm2d) Space::SpaceWildTemplateStruct::m2; +%rename(tt2b) GlobalWildTemplateStruct::t2; +%rename(tt2d) Space::SpaceWildTemplateStruct::t2; + +// With declaration +%rename(mm3a) GlobalWildStruct::m3; +%rename(mm3b) GlobalWildTemplateStruct::m3; +%rename(mm3c) Space::SpaceWildStruct::m3; +%rename(mm3d) Space::SpaceWildTemplateStruct::m3; +%rename(tt3b) GlobalWildTemplateStruct::t3; +%rename(tt3d) Space::SpaceWildTemplateStruct::t3; + +// Global override too +%rename(mm4a) GlobalWildStruct::m4; +%rename(mm4b) GlobalWildTemplateStruct::m4; +%rename(mm4c) Space::SpaceWildStruct::m4; +%rename(mm4d) Space::SpaceWildTemplateStruct::m4; +%rename(tt4b) GlobalWildTemplateStruct::t4; +%rename(tt4d) Space::SpaceWildTemplateStruct::t4; + +// %extend renames +%extend GlobalWildStruct { + %rename(mm5a) m5; +} +%extend GlobalWildTemplateStruct { + %rename(mm5b) m5; +} +%extend GlobalWildTemplateStruct { + %rename(tt5b) t5; +} +namespace Space { + %extend SpaceWildStruct { + %rename(mm5c) m5; + } + %extend SpaceWildTemplateStruct { + %rename(mm5d) m5; + } + %extend SpaceWildTemplateStruct { + %rename(tt5d) t5; + } +} + +// operators +%rename(opinta) GlobalWildStruct::operator int; +%rename(opintb) GlobalWildTemplateStruct::operator int; +%rename(opintc) Space::SpaceWildStruct::operator int; +%rename(opintd) Space::SpaceWildTemplateStruct::operator int; +%rename(opdoubleb) GlobalWildTemplateStruct::operator double; +%rename(opdoubled) Space::SpaceWildTemplateStruct::operator double; + +%inline %{ +struct GlobalWildStruct { + void m1() {} + void m2() {} + void m3() {} + void m4() {} + void m5() {} + operator int() { return 0; } +}; +template struct GlobalWildTemplateStruct { + void m1() {} + void m2() {} + void t2() {} + void m3() {} + void t3() {} + void m4() {} + void t4() {} + void m5() {} + void t5() {} + operator int() { return 0; } + operator double() { return 0.0; } +}; +namespace Space { + struct SpaceWildStruct { + void m1() {} + void m2() {} + void m3() {} + void m4() {} + void m5() {} + operator int() { return 0; } + }; + template struct SpaceWildTemplateStruct { + void m1() {} + void m2() {} + void t2() {} + void m3() {} + void t3() {} + void m4() {} + void t4() {} + void m5() {} + void t5() {} + operator int() { return 0; } + operator double() { return 0.0; } + }; +} + +// Wild card renames expected for these +struct NoChangeStruct { + void m1() {} + void m2() {} + void m3() {} + void m4() {} + void m5() {} + operator int() { return 0; } +}; +namespace Space { + struct SpaceNoChangeStruct { + void m1() {} + void m2() {} + void m3() {} + void m4() {} + void m5() {} + operator int() { return 0; } + }; +} +%} + +%template(GlobalWildTemplateStructInt) GlobalWildTemplateStruct; +%template(SpaceWildTemplateStructInt) Space::SpaceWildTemplateStruct; diff --git a/Examples/test-suite/ruby/Makefile.in b/Examples/test-suite/ruby/Makefile.in index ae4995882..d94ac7061 100644 --- a/Examples/test-suite/ruby/Makefile.in +++ b/Examples/test-suite/ruby/Makefile.in @@ -11,7 +11,6 @@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ CPP_TEST_CASES = \ - li_cdata \ li_cstring \ li_factory \ li_std_functors \ @@ -22,6 +21,7 @@ CPP_TEST_CASES = \ li_std_stack \ primitive_types \ ruby_keywords \ + ruby_minherit_shared_ptr \ ruby_naming \ ruby_track_objects \ ruby_track_objects_directors \ @@ -30,8 +30,8 @@ CPP_TEST_CASES = \ # stl_new C_TEST_CASES += \ - li_cdata \ - li_cstring + li_cstring \ + ruby_manual_proxy \ include $(srcdir)/../common.mk @@ -61,7 +61,7 @@ ruby_naming.cpptest: SWIGOPT += -autorename # a file is found which has _runme.rb appended after the testcase name. run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) -I$(srcdir):. $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) $(RUBYFLAGS) -I$(srcdir):. $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean @@ -69,4 +69,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" ruby_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/test-suite/ruby/cpp11_li_std_array_runme.rb b/Examples/test-suite/ruby/cpp11_li_std_array_runme.rb new file mode 100644 index 000000000..770f37c0f --- /dev/null +++ b/Examples/test-suite/ruby/cpp11_li_std_array_runme.rb @@ -0,0 +1,134 @@ +#!/usr/bin/env ruby +# +# Put description here +# +# +# +# +# + +require 'swig_assert' + +require 'cpp11_li_std_array' + +include Cpp11_li_std_array + + +def failed(a, b, msg) + raise RuntimeError, "#{msg} #{a} #{b}" +end + +def compare_sequences(a, b) + if a.size != b.size + failed(a, b, "different sizes") + end + for i in 0..a.size-1 + failed(a, b, "elements are different:") if a[i] != b[i] + end +end + +def compare_containers(rubyarray, swigarray) + compare_sequences(rubyarray, swigarray) +end + +def setslice_exception(swigarray, newval) + begin + swigarray[0..swigarray.size] = newval + raise RuntimeError, "swigarray[] = #{newval} missed set exception for swigarray: #{swigarray}" + rescue ArgumentError => e +# print "exception: #{e}" + end +end + + +# Check std::array has similar behaviour to a Ruby array +# except it is not resizable + +ps = [0, 1, 2, 3, 4, 5] + +ai = ArrayInt6.new(ps) + +compare_containers(ps, ai) + +# slices +compare_containers(ps[0..5], ai[0..5]) +compare_containers(ps[-6..-1], ai[-6..-1]) +compare_containers(ps[0..10], ai[0..10]) + +# Reverse (.reverse is not provided) +rev = [] +ai.reverse_each { |i| rev.push i } +compare_containers(ps.reverse, rev) + +# Modify content +for i in 0..ps.size-1 + ps[i] = ps[i] * 10 + ai[i] = ai[i] * 10 +end +compare_containers(ps, ai) + +# Empty +ai = ArrayInt6.new() +compare_containers([0, 0, 0, 0, 0, 0], ai) + +# Set slice +newvals = [10, 20, 30, 40, 50, 60] +ai[0, 6] = newvals +compare_containers(ai, newvals) + +ai[-6, 6] = newvals +compare_containers(ai, newvals) + +setslice_exception(ai, [1, 2, 3, 4, 5, 6, 7]) +setslice_exception(ai, [1, 2, 3, 4, 5]) +setslice_exception(ai, [1, 2, 3, 4]) +setslice_exception(ai, [1, 2, 3]) +setslice_exception(ai, [1, 2]) +setslice_exception(ai, [1]) +setslice_exception(ai, []) + +# Check return +compare_containers(arrayOutVal(), [-2, -1, 0, 0, 1, 2]) +compare_containers(arrayOutConstRef(), [-2, -1, 0, 0, 1, 2]) +compare_containers(arrayOutRef(), [-2, -1, 0, 0, 1, 2]) +compare_containers(arrayOutPtr(), [-2, -1, 0, 0, 1, 2]) + +# Check passing arguments +ai = arrayInVal([9, 8, 7, 6, 5, 4]) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +ai = arrayInConstRef([9, 8, 7, 6, 5, 4]) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +ai = ArrayInt6.new([9, 8, 7, 6, 5, 4]) +arrayInRef(ai) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +ai = ArrayInt6.new([9, 8, 7, 6, 5, 4]) +arrayInPtr(ai) +compare_containers(ai, [90, 80, 70, 60, 50, 40]) + +# indexing +ai = ArrayInt6.new([9, 8, 7, 6, 5, 4]) +swig_assert_equal(ai[0], 9, binding) +swig_assert_equal(ai[5], 4, binding) +swig_assert_equal(ai[6], nil, binding) +swig_assert_equal(ai[-7], nil, binding) + +# fill +ai.fill(111) +compare_containers(ai, [111, 111, 111, 111, 111, 111]) + +# various +ai = ArrayInt6.new([9, 8, 7, 6, 5, 4]) +swig_assert(ai.include? 9) +swig_assert(!ai.include?(99)) +swig_assert(ai.kind_of? ArrayInt6) +swig_assert(ai.find {|x| x == 6 } == 6) +swig_assert(ai.find {|x| x == 66 } == nil) +swig_assert(ai.respond_to?(:each)) +swig_assert(ai.respond_to?(:each_with_index)) + +ai = [0, 10, 20, 30, 40, 50] +ai.each_with_index { |e,i| swig_assert(e/10 == i) } + diff --git a/Examples/test-suite/ruby/director_smartptr_runme.rb b/Examples/test-suite/ruby/director_smartptr_runme.rb new file mode 100644 index 000000000..8b4bd3d6d --- /dev/null +++ b/Examples/test-suite/ruby/director_smartptr_runme.rb @@ -0,0 +1,54 @@ +#!/usr/bin/env ruby +# +# Put description here +# +# +# +# +# + +require 'director_smartptr' + +include Director_smartptr + +class Director_smartptr_MyBarFoo < Foo + + def ping() + return "director_smartptr_MyBarFoo.ping()" + end + + def pong() + return "director_smartptr_MyBarFoo.pong();" + ping() + end + + def upcall(fooBarPtr) + return "override;" + fooBarPtr.FooBarDo() + end + + def makeFoo() + return Foo.new() + end +end + +def check(got, expected) + if (got != expected) + raise RuntimeError, "Failed, got: #{got} expected: #{expected}" + end +end + +fooBar = Director_smartptr::FooBar.new() + +myBarFoo = Director_smartptr_MyBarFoo.new() +check(myBarFoo.ping(), "director_smartptr_MyBarFoo.ping()") +check(Foo.callPong(myBarFoo), "director_smartptr_MyBarFoo.pong();director_smartptr_MyBarFoo.ping()") +check(Foo.callUpcall(myBarFoo, fooBar), "override;Bar::Foo2::Foo2Bar()") + +myFoo = myBarFoo.makeFoo() +check(myFoo.pong(), "Foo::pong();Foo::ping()") +check(Foo.callPong(myFoo), "Foo::pong();Foo::ping()") +check(myFoo.upcall(FooBar.new()), "Bar::Foo2::Foo2Bar()") + +myFoo2 = Foo.new().makeFoo() +check(myFoo2.pong(), "Foo::pong();Foo::ping()") +check(Foo.callPong(myFoo2), "Foo::pong();Foo::ping()") +check(myFoo2.upcall(FooBar.new()), "Bar::Foo2::Foo2Bar()") diff --git a/Examples/test-suite/ruby/li_boost_shared_ptr_bits_runme.rb b/Examples/test-suite/ruby/li_boost_shared_ptr_bits_runme.rb new file mode 100644 index 000000000..bcd817e5a --- /dev/null +++ b/Examples/test-suite/ruby/li_boost_shared_ptr_bits_runme.rb @@ -0,0 +1,32 @@ +require 'li_boost_shared_ptr_bits' +require 'swig_gc' + +v = Li_boost_shared_ptr_bits::VectorIntHolder.new() +v.push(Li_boost_shared_ptr_bits::IntHolder.new(11)) +v.push(Li_boost_shared_ptr_bits::IntHolder.new(22)) +v.push(Li_boost_shared_ptr_bits::IntHolder.new(33)) + +sum = Li_boost_shared_ptr_bits::sum(v) +if (sum != 66) + raise RuntimeError, "sum is wrong" +end + +hidden = Li_boost_shared_ptr_bits::HiddenDestructor.create() +GC.track_class = Li_boost_shared_ptr_bits::HiddenPrivateDestructor +GC.stats if $VERBOSE +hidden = nil +GC.start + +hiddenPrivate = Li_boost_shared_ptr_bits::HiddenPrivateDestructor.create() +if (Li_boost_shared_ptr_bits::HiddenPrivateDestructor.DeleteCount != 0) + # GC doesn't always run +# raise RuntimeError, "Count should be zero" +end + +GC.stats if $VERBOSE +hiddenPrivate = nil +GC.start +if (Li_boost_shared_ptr_bits::HiddenPrivateDestructor.DeleteCount != 1) + # GC doesn't always run +# raise RuntimeError, "Count should be one" +end diff --git a/Examples/test-suite/ruby/li_boost_shared_ptr_runme.rb b/Examples/test-suite/ruby/li_boost_shared_ptr_runme.rb new file mode 100644 index 000000000..cc5c0cab0 --- /dev/null +++ b/Examples/test-suite/ruby/li_boost_shared_ptr_runme.rb @@ -0,0 +1,614 @@ +require 'li_boost_shared_ptr' +require 'swig_gc' + +#debug = $VERBOSE +debug = false + +# simple shared_ptr usage - created in C++ + + +class Li_boost_shared_ptr_runme + + def main(debug) + if (debug) + puts "Started" + end + + Li_boost_shared_ptr::debug_shared = debug + + # Change loop count to run for a long time to monitor memory + loopCount = 1 # 5000 + 1.upto(loopCount) do + self.runtest() + end + + # Expect 1 instance - the one global variable (GlobalValue) + GC.track_class = Li_boost_shared_ptr::Klass + invokeGC("Final GC") + +# Actual count is 3 due to memory leaks calling rb_raise in the call to Li_boost_shared_ptr::valuetest(nil) +# as setjmp/longjmp are used thereby failing to call destructors of Klass instances on the stack in _wrap_valuetest +# This is a generic problem in Ruby wrappers, not shared_ptr specific +# expectedCount = 1 + expectedCount = 3 + actualCount = Li_boost_shared_ptr::Klass.getTotal_count() + if (actualCount != expectedCount) +# raise RuntimeError, "GC failed to run (li_boost_shared_ptr). Expected count: #{expectedCount} Actual count: #{actualCount}" + puts "GC failed to run (li_boost_shared_ptr). Expected count: #{expectedCount} Actual count: #{actualCount}" + end + + wrapper_count = Li_boost_shared_ptr::shared_ptr_wrapper_count() + if (wrapper_count != Li_boost_shared_ptr.NOT_COUNTING) + # Expect 1 instance - the one global variable (GlobalSmartValue) + if (wrapper_count != 1) + raise RuntimeError, "shared_ptr wrapper count=#{wrapper_count}" + end + end + + if (debug) + puts "Finished" + end + end + + def invokeGC(debug_msg) + puts "invokeGC #{debug_msg} start" if $VERBOSE + GC.stats if $VERBOSE + GC.start + puts "invokeGC #{debug_msg} end" if $VERBOSE + end + + def runtest + # simple shared_ptr usage - created in C++ + k = Li_boost_shared_ptr::Klass.new("me oh my") + val = k.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(1, k) + + # simple shared_ptr usage - not created in C++ + k = Li_boost_shared_ptr::factorycreate() + val = k.getValue() + self.verifyValue("factorycreate", val) + self.verifyCount(1, k) + + # pass by shared_ptr + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::smartpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointertest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::smartpointerpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointertest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr reference + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::smartpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerreftest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer reference + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::smartpointerpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointerreftest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # const pass by shared_ptr + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::constsmartpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # const pass by shared_ptr pointer + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::constsmartpointerpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # const pass by shared_ptr reference + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::constsmartpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by value + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::valuetest(k) + val = kret.getValue() + self.verifyValue("me oh my valuetest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by pointer + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::pointertest(k) + val = kret.getValue() + self.verifyValue("me oh my pointertest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by reference + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::reftest(k) + val = kret.getValue() + self.verifyValue("me oh my reftest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by pointer reference + k = Li_boost_shared_ptr::Klass.new("me oh my") + kret = Li_boost_shared_ptr::pointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my pointerreftest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # null tests + k = nil + + if (Li_boost_shared_ptr::smartpointertest(k) != nil) + raise RuntimeError, "return was not null" + end + + if (Li_boost_shared_ptr::smartpointerpointertest(k) != nil) + raise RuntimeError, "return was not null" + end + + if (Li_boost_shared_ptr::smartpointerreftest(k) != nil) + raise RuntimeError, "return was not null" + end + + if (Li_boost_shared_ptr::smartpointerpointerreftest(k) != nil) + raise RuntimeError, "return was not null" + end + + if (Li_boost_shared_ptr::nullsmartpointerpointertest(nil) != "null pointer") + raise RuntimeError, "not null smartpointer pointer" + end + + begin + Li_boost_shared_ptr::valuetest(k) + raise RuntimeError, "Failed to catch null pointer" + rescue ArgumentError + end + + if (Li_boost_shared_ptr::pointertest(k) != nil) + raise RuntimeError, "return was not null" + end + + begin + Li_boost_shared_ptr::reftest(k) + raise RuntimeError, "Failed to catch null pointer" + rescue ArgumentError + end + + # $owner + k = Li_boost_shared_ptr::pointerownertest() + val = k.getValue() + self.verifyValue("pointerownertest", val) + self.verifyCount(1, k) + k = Li_boost_shared_ptr::smartpointerpointerownertest() + val = k.getValue() + self.verifyValue("smartpointerpointerownertest", val) + self.verifyCount(1, k) + + # //////////////////////////////// Derived class ////////////////////// + # derived pass by shared_ptr + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::derivedsmartptrtest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrtest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by shared_ptr pointer + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::derivedsmartptrpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by shared_ptr ref + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::derivedsmartptrreftest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by shared_ptr pointer ref + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::derivedsmartptrpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by pointer + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::derivedpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedpointertest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # derived pass by ref + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::derivedreftest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedreftest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # //////////////////////////////// Derived and base class mixed /////// + # pass by shared_ptr (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::smartpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointertest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::smartpointerpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointertest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr reference (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::smartpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer reference (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::smartpointerpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointerreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by value (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::valuetest(k) + val = kret.getValue() + self.verifyValue("me oh my valuetest", val) # note slicing + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by pointer (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::pointertest(k) + val = kret.getValue() + self.verifyValue("me oh my pointertest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by ref (mixed) + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + kret = Li_boost_shared_ptr::reftest(k) + val = kret.getValue() + self.verifyValue("me oh my reftest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # //////////////////////////////// Overloading tests ////////////////// + # Base class + k = Li_boost_shared_ptr::Klass.new("me oh my") + self.verifyValue(Li_boost_shared_ptr::overload_rawbyval(k), "rawbyval") + self.verifyValue(Li_boost_shared_ptr::overload_rawbyref(k), "rawbyref") + self.verifyValue(Li_boost_shared_ptr::overload_rawbyptr(k), "rawbyptr") + self.verifyValue( + Li_boost_shared_ptr::overload_rawbyptrref(k), "rawbyptrref") + + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyval(k), "smartbyval") + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyref(k), "smartbyref") + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyptr(k), "smartbyptr") + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyptrref(k), "smartbyptrref") + + # Derived class + k = Li_boost_shared_ptr::KlassDerived.new("me oh my") + self.verifyValue(Li_boost_shared_ptr::overload_rawbyval(k), "rawbyval") + self.verifyValue(Li_boost_shared_ptr::overload_rawbyref(k), "rawbyref") + self.verifyValue(Li_boost_shared_ptr::overload_rawbyptr(k), "rawbyptr") + self.verifyValue( + Li_boost_shared_ptr::overload_rawbyptrref(k), "rawbyptrref") + + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyval(k), "smartbyval") + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyref(k), "smartbyref") + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyptr(k), "smartbyptr") + self.verifyValue( + Li_boost_shared_ptr::overload_smartbyptrref(k), "smartbyptrref") + + # 3rd derived class + k = Li_boost_shared_ptr::Klass3rdDerived.new("me oh my") + val = k.getValue() + self.verifyValue("me oh my-3rdDerived", val) + self.verifyCount(1, k) + val = Li_boost_shared_ptr::test3rdupcast(k) + self.verifyValue("me oh my-3rdDerived", val) + self.verifyCount(1, k) + + # //////////////////////////////// Member variables /////////////////// + # smart pointer by value + m = Li_boost_shared_ptr::MemberVariables.new() + k = Li_boost_shared_ptr::Klass.new("smart member value") + m.SmartMemberValue = k + val = k.getValue() + self.verifyValue("smart member value", val) + self.verifyCount(2, k) + + kmember = m.SmartMemberValue + val = kmember.getValue() + self.verifyValue("smart member value", val) + self.verifyCount(3, kmember) + self.verifyCount(3, k) + + GC.track_class = Li_boost_shared_ptr::MemberVariables + m = nil + invokeGC("m = nil (A)") + + self.verifyCount(2, kmember) + self.verifyCount(2, k) + + # smart pointer by pointer + m = Li_boost_shared_ptr::MemberVariables.new() + k = Li_boost_shared_ptr::Klass.new("smart member pointer") + m.SmartMemberPointer = k + val = k.getValue() + self.verifyValue("smart member pointer", val) + self.verifyCount(1, k) + + kmember = m.SmartMemberPointer + val = kmember.getValue() + self.verifyValue("smart member pointer", val) + self.verifyCount(2, kmember) + self.verifyCount(2, k) + + m = nil + invokeGC("m = nil (B)") + + self.verifyCount(2, kmember) + self.verifyCount(2, k) + + # smart pointer by reference + m = Li_boost_shared_ptr::MemberVariables.new() + k = Li_boost_shared_ptr::Klass.new("smart member reference") + m.SmartMemberReference = k + val = k.getValue() + self.verifyValue("smart member reference", val) + self.verifyCount(2, k) + + kmember = m.SmartMemberReference + val = kmember.getValue() + self.verifyValue("smart member reference", val) + self.verifyCount(3, kmember) + self.verifyCount(3, k) + + # The C++ reference refers to SmartMemberValue... + kmemberVal = m.SmartMemberValue + val = kmember.getValue() + self.verifyValue("smart member reference", val) + self.verifyCount(4, kmemberVal) + self.verifyCount(4, kmember) + self.verifyCount(4, k) + + m = nil + invokeGC("m = nil (C)") + + + self.verifyCount(3, kmemberVal) + self.verifyCount(3, kmember) + self.verifyCount(3, k) + + # plain by value + m = Li_boost_shared_ptr::MemberVariables.new() + k = Li_boost_shared_ptr::Klass.new("plain member value") + m.MemberValue = k + val = k.getValue() + self.verifyValue("plain member value", val) + self.verifyCount(1, k) + + kmember = m.MemberValue + val = kmember.getValue() + self.verifyValue("plain member value", val) + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + m = nil + invokeGC("m = nil (D)") + + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + # plain by pointer + m = Li_boost_shared_ptr::MemberVariables.new() + k = Li_boost_shared_ptr::Klass.new("plain member pointer") + m.MemberPointer = k + val = k.getValue() + self.verifyValue("plain member pointer", val) + self.verifyCount(1, k) + + kmember = m.MemberPointer + val = kmember.getValue() + self.verifyValue("plain member pointer", val) + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + m = nil + invokeGC("m = nil (E)") + + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + # plain by reference + m = Li_boost_shared_ptr::MemberVariables.new() + k = Li_boost_shared_ptr::Klass.new("plain member reference") + m.MemberReference = k + val = k.getValue() + self.verifyValue("plain member reference", val) + self.verifyCount(1, k) + + kmember = m.MemberReference + val = kmember.getValue() + self.verifyValue("plain member reference", val) + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + m = nil + invokeGC("m = nil (F)") + + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + # null member variables + m = Li_boost_shared_ptr::MemberVariables.new() + + # shared_ptr by value + k = m.SmartMemberValue + if (k != nil) + raise RuntimeError, "expected null" + end + m.SmartMemberValue = nil + k = m.SmartMemberValue + if (k != nil) + raise RuntimeError, "expected null" + end + self.verifyCount(0, k) + + # plain by value + begin + m.MemberValue = nil + raise RuntimeError, "Failed to catch null pointer" + rescue ArgumentError + end + + # ////////////////////////////////// Global variables ///////////////// + # smart pointer + kglobal = Li_boost_shared_ptr.GlobalSmartValue + if (kglobal != nil) + raise RuntimeError, "expected null" + end + + k = Li_boost_shared_ptr::Klass.new("smart global value") + Li_boost_shared_ptr.GlobalSmartValue = k + self.verifyCount(2, k) + + kglobal = Li_boost_shared_ptr.GlobalSmartValue + val = kglobal.getValue() + self.verifyValue("smart global value", val) + self.verifyCount(3, kglobal) + self.verifyCount(3, k) + self.verifyValue( + "smart global value", Li_boost_shared_ptr.GlobalSmartValue.getValue()) + Li_boost_shared_ptr.GlobalSmartValue = nil + + # plain value + k = Li_boost_shared_ptr::Klass.new("global value") + Li_boost_shared_ptr.GlobalValue = k + self.verifyCount(1, k) + + kglobal = Li_boost_shared_ptr.GlobalValue + val = kglobal.getValue() + self.verifyValue("global value", val) + self.verifyCount(1, kglobal) + self.verifyCount(1, k) + self.verifyValue( + "global value", Li_boost_shared_ptr.GlobalValue.getValue()) + + begin + Li_boost_shared_ptr.GlobalValue = nil + raise RuntimeError, "Failed to catch null pointer" + rescue ArgumentError + end + + # plain pointer + kglobal = Li_boost_shared_ptr.GlobalPointer + if (kglobal != nil) + raise RuntimeError, "expected null" + end + + k = Li_boost_shared_ptr::Klass.new("global pointer") + Li_boost_shared_ptr.GlobalPointer = k + self.verifyCount(1, k) + + kglobal = Li_boost_shared_ptr.GlobalPointer + val = kglobal.getValue() + self.verifyValue("global pointer", val) + self.verifyCount(1, kglobal) + self.verifyCount(1, k) + Li_boost_shared_ptr.GlobalPointer = nil + + # plain reference + + k = Li_boost_shared_ptr::Klass.new("global reference") + Li_boost_shared_ptr.GlobalReference = k + self.verifyCount(1, k) + + kglobal = Li_boost_shared_ptr.GlobalReference + val = kglobal.getValue() + self.verifyValue("global reference", val) + self.verifyCount(1, kglobal) + self.verifyCount(1, k) + + begin + Li_boost_shared_ptr.GlobalReference = nil + raise RuntimeError, "Failed to catch null pointer" + rescue ArgumentError + end + + # ////////////////////////////////// Templates //////////////////////// + pid = Li_boost_shared_ptr::PairIntDouble.new(10, 20.2) + if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4) + raise RuntimeError, "Base values wrong" + end + if (pid.val1 != 10 or pid.val2 != 20.2) + raise RuntimeError, "Derived Values wrong" + end + end + + def verifyValue(expected, got) + if (expected != got) + raise RuntimeError, "verify value failed. Expected: #{expected} Got: #{got}" + end + end + + def verifyCount(expected, k) + got = Li_boost_shared_ptr::use_count(k) + if (expected != got) + puts "skipped verifyCount expect/got: #{expected}/#{got}" +# raise RuntimeError, "verify use_count failed. Expected: #{expected} Got: #{got}" + end + end +end + +runme = Li_boost_shared_ptr_runme.new() +runme.main(debug) diff --git a/Examples/test-suite/ruby/li_boost_shared_ptr_template_runme.rb b/Examples/test-suite/ruby/li_boost_shared_ptr_template_runme.rb new file mode 100644 index 000000000..7d446a474 --- /dev/null +++ b/Examples/test-suite/ruby/li_boost_shared_ptr_template_runme.rb @@ -0,0 +1,45 @@ +require 'li_boost_shared_ptr_template' + +begin + b = Li_boost_shared_ptr_template::BaseINTEGER.new() + d = Li_boost_shared_ptr_template::DerivedINTEGER.new() + if (b.bar() != 1) + raise RuntimeError("test 1") + end + if (d.bar() != 2) + raise RuntimeError("test 2") + end + if (Li_boost_shared_ptr_template.bar_getter(b) != 1) + raise RuntimeError("test 3") + end +# Needs fixing as it does for Python +# if (Li_boost_shared_ptr_template.bar_getter(d) != 2) +# raise RuntimeError("test 4") +# end +end + +begin + b = Li_boost_shared_ptr_template::BaseDefaultInt.new() + d = Li_boost_shared_ptr_template::DerivedDefaultInt.new() + d2 = Li_boost_shared_ptr_template::DerivedDefaultInt2.new() + if (b.bar2() != 3) + raise RuntimeError("test 5") + end + if (d.bar2() != 4) + raise RuntimeError("test 6") + end + if (d2.bar2() != 4) + raise RuntimeError("test 6") + end + if (Li_boost_shared_ptr_template.bar2_getter(b) != 3) + raise RuntimeError("test 7") + end +# Needs fixing as it does for Python +# if (Li_boost_shared_ptr_template.bar2_getter(d) != 4) +# raise RuntimeError("test 8") +# end +# if (Li_boost_shared_ptr_template.bar2_getter(d2) != 4) +# raise RuntimeError("test 8") +# end +end + diff --git a/Examples/test-suite/ruby/li_carrays_cpp_runme.rb b/Examples/test-suite/ruby/li_carrays_cpp_runme.rb new file mode 100644 index 000000000..692d21065 --- /dev/null +++ b/Examples/test-suite/ruby/li_carrays_cpp_runme.rb @@ -0,0 +1,36 @@ +#!/usr/bin/env ruby +# +# Put description here +# +# +# +# +# + +require 'swig_assert' + +require 'li_carrays_cpp' + +include Li_carrays_cpp + +# +# Testing for %array_functions(int,intArray) +# +ary = new_intArray(2) +intArray_setitem(ary, 0, 0) +intArray_setitem(ary, 1, 1) +intArray_getitem(ary, 0) +intArray_getitem(ary, 1) +delete_intArray(ary) + +# +# Testing for %array_class(double, doubleArray) +# +ary = DoubleArray.new(2) +ary[0] = 0.0 +ary[1] = 1.0 +ary[0] +ary[1] +ptr = ary.cast +ary2 = DoubleArray.frompointer(ptr) + diff --git a/Examples/test-suite/ruby/li_std_vector_runme.rb b/Examples/test-suite/ruby/li_std_vector_runme.rb index fe3d9e0ce..68feb8f1a 100644 --- a/Examples/test-suite/ruby/li_std_vector_runme.rb +++ b/Examples/test-suite/ruby/li_std_vector_runme.rb @@ -39,12 +39,12 @@ iv.each_with_index { |e,i| "iv.slice(1,2).to_s" => "12", "iv[0,-2]" => nil, "iv[0,3].to_s" => "012", - "iv[0,10].to_s" => "012", + "iv[0,10].to_s" => "0123", "iv[1..2].to_s" => '12', "iv[1..3].to_s" => '123', "iv[1..4].to_s" => '123', "iv[1..-2].to_s" => '12', - "iv[2..-3]" => nil, + "iv[2..-3].to_s" => '', }.each do |k,v| swig_assert( "#{k} == #{v.inspect}", binding ) end @@ -68,6 +68,141 @@ iv = IntVector.new([0,1,2,3,4,5,6]) iv.delete_if { |x| x == 0 || x == 3 || x == 6 } swig_assert_equal(iv.to_s, '1245', binding) +iv[1,2] = [-2, -4] +swig_assert_equal(iv.to_s, '1-2-45', binding) + +iv = IntVector.new([0,1,2,3]) +iv[0,1] = [-1, -2] +swig_assert_equal(iv.to_s, '-1-2123', binding) + +iv = IntVector.new([1,2,3,4]) +iv[1,3] = [6,7,8,9] +#__setitem__ needs fixing +#swig_assert_equal(iv.to_s, '16789', binding) + +iv = IntVector.new([1,2,3,4]) + +swig_assert_equal(iv[0], 1, binding) +swig_assert_equal(iv[3], 4, binding) +swig_assert_equal(iv[4], nil, binding) +swig_assert_equal(iv[-5], nil, binding) + +iv[-1] = 9 +iv[-4] = 6 +swig_assert_equal(iv.to_s, '6239', binding) + +begin + iv[-5] = 99 + raise "exception missed" +rescue IndexError +end + +iv[6] = 5 +swig_assert_equal(iv.to_s, '6239555', binding) + +def failed(a, b, msg) + a = 'nil' if a == nil + b = 'nil' if b == nil + raise RuntimeError, "#{msg}: #{a} ... #{b}" +end + +def compare_sequences(a, b) + if a != nil && b != nil + if a.size != b.size + failed(a, b, "different sizes") + end + for i in 0..a.size-1 + failed(a, b, "elements are different") if a[i] != b[i] + end + else + unless a == nil && b == nil + failed(a, b, "only one of the sequences is nil") + end + end +end + +def compare_expanded_sequences(a, b) + # a can contain nil elements which indicate additional elements + # b won't contain nil for additional elements + if a != nil && b != nil + if a.size != b.size + failed(a, b, "different sizes") + end + for i in 0..a.size-1 + failed(a, b, "elements are different") if a[i] != b[i] && a[i] != nil + end + else + unless a == nil && b == nil + failed(a, b, "only one of the sequences is nil") + end + end +end + +def check_slice(i, length) + aa = [1,2,3,4] + iv = IntVector.new(aa) + + aa_slice = aa[i, length] + iv_slice = iv[i, length] + compare_sequences(aa_slice, iv_slice) + + aa_slice = aa.slice(i, length) + iv_slice = iv.slice(i, length) + compare_sequences(aa_slice, iv_slice) +end + +def check_range(i, j) + aa = [1,2,3,4] + iv = IntVector.new(aa) + + aa_range = aa[i..j] + iv_range = iv[i..j] + compare_sequences(aa_range, iv_range) + + aa_range = aa[Range.new(i, j, true)] + iv_range = iv[Range.new(i, j, true)] + compare_sequences(aa_range, iv_range) +end + +def set_slice(i, length, expect_nil_expanded_elements) + aa = [1,2,3,4] + iv = IntVector.new(aa) + aa_new = [8, 9] + iv_new = IntVector.new(aa_new) + + aa[i, length] = aa_new + iv[i, length] = iv_new + if expect_nil_expanded_elements + compare_expanded_sequences(aa, iv) + else + compare_sequences(aa, iv) + end +end + +for i in -5..5 + for length in -5..5 + check_slice(i, length) + end +end + +for i in -5..5 + for j in -5..5 + check_range(i, j) + end +end + +for i in -4..4 + for length in 0..4 + set_slice(i, length, false) + end +end + +for i in [5, 6] + for length in 0..5 + set_slice(i, length, true) + end +end + dv = DoubleVector.new(10) diff --git a/Examples/test-suite/ruby/overload_extend2_runme.rb b/Examples/test-suite/ruby/overload_extend2_runme.rb new file mode 100644 index 000000000..81b456c10 --- /dev/null +++ b/Examples/test-suite/ruby/overload_extend2_runme.rb @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby +# +# Put description here +# +# +# +# +# + +require 'swig_assert' + +require 'overload_extend2' + +f = Overload_extend2::Foo.new + +raise RuntimeError if f.test(3) != 1 +raise RuntimeError if f.test("hello") != 2 +raise RuntimeError if f.test(3.5,2.5) != 3 diff --git a/Examples/test-suite/ruby/overload_extendc_runme.rb b/Examples/test-suite/ruby/overload_extend_c_runme.rb similarity index 77% rename from Examples/test-suite/ruby/overload_extendc_runme.rb rename to Examples/test-suite/ruby/overload_extend_c_runme.rb index a2682bf42..357afdb64 100644 --- a/Examples/test-suite/ruby/overload_extendc_runme.rb +++ b/Examples/test-suite/ruby/overload_extend_c_runme.rb @@ -9,10 +9,11 @@ require 'swig_assert' -require 'overload_extend' +require 'overload_extend_c' -f = Overload_extend::Foo.new +f = Overload_extend_c::Foo.new raise RuntimeError if f.test(3) != 1 raise RuntimeError if f.test("hello") != 2 raise RuntimeError if f.test(3.5,2.5) != 6 + diff --git a/Examples/test-suite/ruby/ruby_manual_proxy_runme.rb b/Examples/test-suite/ruby/ruby_manual_proxy_runme.rb new file mode 100644 index 000000000..c1cee2d13 --- /dev/null +++ b/Examples/test-suite/ruby/ruby_manual_proxy_runme.rb @@ -0,0 +1,49 @@ +#!/usr/bin/env ruby +# +# The Subversion bindings use this manually written proxy class approach +# to the Ruby bindings. Note that in C the struct svn_fs_t is an +# opaque pointer and the Ruby FileSystem proxy class is hand written around it. +# This testcase tests this and the C close function and subsequent error +# handling. + +require 'swig_assert' +require 'ruby_manual_proxy' + +module Svn + module Fs + module_function + def create(path) + f = Ruby_manual_proxy::svn_fs_create(path) + return f + end + + FileSystem = SWIG::TYPE_p_svn_fs_t + class FileSystem + class << self + def create(*args) + Fs.create(*args) + end + end + def path + Ruby_manual_proxy::svn_fs_path(self) + end + end + end +end + +f = Svn::Fs::FileSystem.create("/tmp/myfile") +path = f.path +f.close +begin + # regression in swig-3.0.8 meant ObjectPreviouslyDeleted error was thrown instead + path = f.path + raise RuntimeError.new("IOError (1) not thrown") +rescue IOError +end + +file = nil +begin + path = Ruby_manual_proxy::svn_fs_path(file) + raise RuntimeError.new("IOError (2) not thrown") +rescue IOError +end diff --git a/Examples/test-suite/ruby/ruby_minherit_shared_ptr_runme.rb b/Examples/test-suite/ruby/ruby_minherit_shared_ptr_runme.rb new file mode 100644 index 000000000..9381fee2b --- /dev/null +++ b/Examples/test-suite/ruby/ruby_minherit_shared_ptr_runme.rb @@ -0,0 +1,28 @@ +#!/usr/bin/env ruby +# +# Put description here +# +# +# +# +# + +require 'ruby_minherit_shared_ptr' + +md = Ruby_minherit_shared_ptr::MultiDerived.new(11, 22) + +if md.Base1Func != 11 then + raise RuntimeError +end +if md.Interface1Func != 22 then + raise RuntimeError +end +if Ruby_minherit_shared_ptr.BaseCheck(md) != 11 then + raise RuntimeError +end +if Ruby_minherit_shared_ptr.InterfaceCheck(md) != 22 then + raise RuntimeError +end +if Ruby_minherit_shared_ptr.DerivedCheck(md) != 33 then + raise RuntimeError +end diff --git a/Examples/test-suite/ruby/swig_assert.rb b/Examples/test-suite/ruby/swig_assert.rb index 200b08384..69a1a0207 100644 --- a/Examples/test-suite/ruby/swig_assert.rb +++ b/Examples/test-suite/ruby/swig_assert.rb @@ -22,6 +22,8 @@ end # msg - optional additional message to print # def swig_assert_equal( a, b, scope = nil, msg = nil ) + a = 'nil' if a == nil + b = 'nil' if b == nil begin check = "#{a} == #{b}" if scope.kind_of? Binding diff --git a/Examples/test-suite/ruby_manual_proxy.i b/Examples/test-suite/ruby_manual_proxy.i new file mode 100644 index 000000000..2cb154e6a --- /dev/null +++ b/Examples/test-suite/ruby_manual_proxy.i @@ -0,0 +1,66 @@ +%module ruby_manual_proxy + + +%typemap(in, numinputs=0) SWIGTYPE ** ($*1_ltype temp) "$1 = &temp;"; + +%typemap(argout) SWIGTYPE **OUTPARAM { + $result = SWIG_Ruby_AppendOutput($result, SWIG_NewPointerObj(*$1, $*1_descriptor, 0)); +} + +%apply SWIGTYPE **OUTPARAM { + svn_fs_t ** +}; + +%typemap(check) svn_fs_t * { + if (!$1) { + svn_swig_rb_raise_svn_fs_already_close(); + } +} + +%{ +typedef struct svn_fs_t { + char path[256]; +} svn_fs_t; + +void svn_fs_create(svn_fs_t **fs_p, const char *path) { + svn_fs_t *fs = (svn_fs_t *)malloc(sizeof(svn_fs_t)); + strncpy(fs->path, path, 256); + *fs_p = fs; +} +const char *svn_fs_path(svn_fs_t *fs) { + return fs->path; +} +%} + +typedef struct svn_fs_t svn_fs_t; +void svn_fs_create(svn_fs_t **fs_p, const char *path); +const char *svn_fs_path(svn_fs_t *fs); + +%{ +static void svn_swig_rb_raise_svn_fs_already_close(void) { + rb_raise(rb_eIOError, "already closed"); +} + +static VALUE svn_fs_swig_rb_close(VALUE self) { + if (!DATA_PTR(self)) { + svn_swig_rb_raise_svn_fs_already_close(); + } + + DATA_PTR(self) = NULL; + + return Qnil; +} + +static VALUE svn_fs_swig_rb_closed(VALUE self) { + return DATA_PTR(self) ? Qfalse : Qtrue; +} +%} + +%insert("init") %{ + { + VALUE cSvnfs; + cSvnfs = rb_const_get(_mSWIG, rb_intern("TYPE_p_svn_fs_t")); + rb_define_method(cSvnfs, "close", + VALUEFUNC(svn_fs_swig_rb_close), 0); + } +%} diff --git a/Examples/test-suite/ruby_minherit_shared_ptr.i b/Examples/test-suite/ruby_minherit_shared_ptr.i new file mode 100644 index 000000000..6a0e3f94c --- /dev/null +++ b/Examples/test-suite/ruby_minherit_shared_ptr.i @@ -0,0 +1,39 @@ +// Test ruby_minherit (multiple inheritance support) and shared_ptr +%module(ruby_minherit="1") ruby_minherit_shared_ptr + +%include +%shared_ptr(Interface1) +%shared_ptr(Base1) +%shared_ptr(MultiDerived) + +%inline %{ +#include +class Interface1 { +public: + virtual int Interface1Func() const = 0; +}; + +class Base1 { + int val; +public: + Base1(int a = 0) : val(a) {} + virtual int Base1Func() const { return val; } +}; + +class MultiDerived : public Base1, public Interface1 { + int multi; +public: + MultiDerived(int v1, int v2) : Base1(v1), multi(v2) {} + virtual int Interface1Func() const { return multi; } +}; + +int BaseCheck(const Base1& b) { + return b.Base1Func(); +} +int InterfaceCheck(const Interface1& i) { + return i.Interface1Func(); +} +int DerivedCheck(const MultiDerived& m) { + return m.Interface1Func() + m.Base1Func(); +} +%} diff --git a/Examples/test-suite/schemerunme/overload_extend_c.scm b/Examples/test-suite/schemerunme/overload_extend_c.scm new file mode 100644 index 000000000..0b03b285a --- /dev/null +++ b/Examples/test-suite/schemerunme/overload_extend_c.scm @@ -0,0 +1,12 @@ +(define f (new-Foo)) + +(if (not (= (Foo-test f 3) 1)) + (error "test integer bad")) + +(if (not (= (Foo-test f "hello") 2)) + (error "test string bad")) + +(if (not (= (Foo-test f 3.5 2.5) 6.0)) + (error "test reals bad")) + +(exit 0) diff --git a/Examples/test-suite/scilab/Makefile.in b/Examples/test-suite/scilab/Makefile.in index 4a9a4f007..483ed2439 100644 --- a/Examples/test-suite/scilab/Makefile.in +++ b/Examples/test-suite/scilab/Makefile.in @@ -13,7 +13,6 @@ top_builddir = ../@top_builddir@ C_TEST_CASES += \ scilab_consts \ - scilab_enums \ scilab_identifier_name \ CPP_TEST_CASES += \ @@ -21,6 +20,7 @@ CPP_TEST_CASES += \ primitive_types \ scilab_li_matrix \ scilab_multivalue \ + scilab_enums \ scilab_pointer_conversion_functions \ CPP_STD_TEST_CASES += \ @@ -62,7 +62,7 @@ setup = \ mkdir $(TEST_DIR); \ fi; \ if [ -f $(SRC_RUNME_SCRIPT) ]; then \ - echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ if [ ! -f $(TEST_DIR) ]; then \ cp $(SRC_RUNME_SCRIPT) $(TEST_DIR); \ fi; \ @@ -73,7 +73,7 @@ setup = \ cp $(srcdir)/swigtest.quit $(TEST_DIR); \ fi; \ else \ - echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ; \ + echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ fi; \ # Runs the testcase. A testcase is only run if diff --git a/Examples/test-suite/scilab/empty_c_runme.sci b/Examples/test-suite/scilab/empty_c_runme.sci new file mode 100644 index 000000000..48db2d52b --- /dev/null +++ b/Examples/test-suite/scilab/empty_c_runme.sci @@ -0,0 +1,3 @@ +exec("swigtest.start", -1); + +exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/funcptr_cpp_runme.sci b/Examples/test-suite/scilab/funcptr_cpp_runme.sci index cb4c3cd0d..2065fb1df 100644 --- a/Examples/test-suite/scilab/funcptr_cpp_runme.sci +++ b/Examples/test-suite/scilab/funcptr_cpp_runme.sci @@ -3,5 +3,6 @@ exec("swigtest.start", -1); checkequal(call1(ADD_BY_VALUE_get(), 10, 11), 21, "ADD_BY_VALUE"); checkequal(call2(ADD_BY_POINTER_get(), 12, 13), 25, "ADD_BY_POINTER"); checkequal(call3(ADD_BY_REFERENCE_get(), 14, 15), 29, "ADD_BY_REFERENCE"); +checkequal(call1(ADD_BY_VALUE_C_get(), 2, 3), 5, "ADD_BY_VALUE_C"); exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/li_carrays_cpp_runme.sci b/Examples/test-suite/scilab/li_carrays_cpp_runme.sci new file mode 100644 index 000000000..0ac157446 --- /dev/null +++ b/Examples/test-suite/scilab/li_carrays_cpp_runme.sci @@ -0,0 +1,11 @@ +exec("swigtest.start", -1); + +d = new_intArray(10); + +intArray_setitem(d, 0, 7); + +intArray_setitem(d, 5, intArray_getitem(d, 0) + 3); + +checkequal(intArray_getitem(d, 5) + intArray_getitem(d, 0), 17, "d(5) + d(0) <> 17"); + +exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/li_cpointer_cpp_runme.sci b/Examples/test-suite/scilab/li_cpointer_cpp_runme.sci new file mode 100644 index 000000000..0aa4339c8 --- /dev/null +++ b/Examples/test-suite/scilab/li_cpointer_cpp_runme.sci @@ -0,0 +1,8 @@ +exec("swigtest.start", -1); + +p = new_intp(); +intp_assign(p, 3); +checkequal(intp_value(p), 3, "intp_value(p)"); +delete_intp(p); + +exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/overload_extendc_runme.sci b/Examples/test-suite/scilab/overload_extend2_runme.sci similarity index 100% rename from Examples/test-suite/scilab/overload_extendc_runme.sci rename to Examples/test-suite/scilab/overload_extend2_runme.sci diff --git a/Examples/test-suite/scilab/overload_extend_c_runme.sci b/Examples/test-suite/scilab/overload_extend_c_runme.sci new file mode 100644 index 000000000..416477bcb --- /dev/null +++ b/Examples/test-suite/scilab/overload_extend_c_runme.sci @@ -0,0 +1,13 @@ +exec("swigtest.start", -1); + +//try +// x = new_Foo(); +//catch +// swigtesterror(); +//end +//if Foo_test(x) <> 0 then swigtesterror(); end +//if Foo_test(x, 1) <> 1 then swigtesterror(); end +//if Foo_test(x, 2, 3) <> 5 then swigtesterror(); end +//if Foo_test(x, "Hello, swig!") <> 2 then swigtesterror(); end + +exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/overload_polymorphic_runme.sci b/Examples/test-suite/scilab/overload_polymorphic_runme.sci new file mode 100644 index 000000000..cae65405c --- /dev/null +++ b/Examples/test-suite/scilab/overload_polymorphic_runme.sci @@ -0,0 +1,11 @@ +exec("swigtest.start", -1); + +derived = new_Derived(); + +checkequal(test(derived), 0, "test(derived)"); +checkequal(test2(derived), 1, "test2(derived)"); + +delete_Derived(derived); + +exec("swigtest.quit", -1); + diff --git a/Examples/test-suite/scilab/overload_simple_runme.sci b/Examples/test-suite/scilab/overload_simple_runme.sci index 23be43db9..ad353e847 100644 --- a/Examples/test-suite/scilab/overload_simple_runme.sci +++ b/Examples/test-suite/scilab/overload_simple_runme.sci @@ -1,16 +1,17 @@ exec("swigtest.start", -1); +f = new_Foo(); +b = new_Bar(); +v = malloc_void(32); + // Functions checkequal(foo(int32(3)), "foo:int", "foo(int)"); checkequal(foo(3), "foo:double", "foo(double)"); checkequal(foo("hello"), "foo:char *", "foo(char* )"); -f = new_Foo(); checkequal(foo(f), "foo:Foo *", "foo(Foo *)"); -//b = new_Bar(); -//checkequal(foo(b), "foo:Bar *", "foo(Bar *)"); -//v = malloc_void(32); -//checkequal(foo(v), "foo:void *", "foo(void *)"); +checkequal(foo(b), "foo:Bar *", "foo(Bar *)"); +checkequal(foo(v), "foo:void *", "foo(void *)"); // Class methods @@ -19,8 +20,8 @@ checkequal(Spam_foo(s, int32(3)), "foo:int", "Spam::foo(int)"); checkequal(Spam_foo(s, 3), "foo:double", "Spam::foo(double)"); checkequal(Spam_foo(s, "hello"), "foo:char *", "Spam::foo(char *)"); checkequal(Spam_foo(s, f), "foo:Foo *", "Spam::foo(Foo *)"); -//checkequal(Spam_foo(s, b), "foo:Bar *", "Spam::foo(Bar *)"); -//checkequal(Spam_foo(s, v), "foo:void *", "Spam::foo(void *)"); +checkequal(Spam_foo(s, b), "foo:Bar *", "Spam::foo(Bar *)"); +checkequal(Spam_foo(s, v), "foo:void *", "Spam::foo(void *)"); delete_Spam(s); // Static class methods @@ -29,8 +30,8 @@ checkequal(Spam_bar(int32(3)), "bar:int", "Spam::bar(int)"); checkequal(Spam_bar(3.1), "bar:double", "Spam::bar(double)"); checkequal(Spam_bar("hello"), "bar:char *", "Spam::bar(char *)"); checkequal(Spam_bar(f), "bar:Foo *", "Spam::bar(Foo *)"); -//checkequal(Spam_bar(b), "bar:Bar *", "Spam::bar(Bar *)"); -//checkequal(Spam_bar(b), "bar:void *", "Spam::bar(void *)"); +checkequal(Spam_bar(b), "bar:Bar *", "Spam::bar(Bar *)"); +checkequal(Spam_bar(v), "bar:void *", "Spam::bar(void *)"); // Constructors @@ -54,20 +55,21 @@ s = new_Spam(f); checkequal(Spam_type_get(s), "Foo *", "Spam::Spam(Foo *)"); delete_Spam(s); -//s = new_Spam(b); -//checkequal(Spam_type_get(s), "Bar *", "Spam::Spam(Bar *)"); -//delete_Spam(s); +s = new_Spam(b); +checkequal(Spam_type_get(s), "Bar *", "Spam::Spam(Bar *)"); +delete_Spam(s); -//s = new_Spam(v); -//checkequal(Spam_type_get(s), "void *", "Spam::Spam(void *)"); -//delete_Spam(s); +s = new_Spam(v); +checkequal(Spam_type_get(s), "void *", "Spam::Spam(void *)"); +delete_Spam(s); delete_Foo(f); -//delete_Bar(b); -//free_void(v); +delete_Bar(b); +free_void(v); a = new_ClassA(); b = ClassA_method1(a, 1); +delete_ClassA(a); exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/overload_subtype_runme.sci b/Examples/test-suite/scilab/overload_subtype_runme.sci new file mode 100644 index 000000000..e644f56b9 --- /dev/null +++ b/Examples/test-suite/scilab/overload_subtype_runme.sci @@ -0,0 +1,13 @@ +exec("swigtest.start", -1); + +f = new_Foo(); +b = new_Bar(); + +checkequal(spam(f), 1, "spam(f)"); +checkequal(spam(b), 2, "spam(b)"); + +delete_Foo(f); +delete_Bar(b); + +exec("swigtest.quit", -1); + diff --git a/Examples/test-suite/scilab/scilab_enums_runme.sci b/Examples/test-suite/scilab/scilab_enums_runme.sci index 3e9fb7ae0..2776bee1e 100644 --- a/Examples/test-suite/scilab/scilab_enums_runme.sci +++ b/Examples/test-suite/scilab/scilab_enums_runme.sci @@ -24,4 +24,13 @@ checkEnum(TYPEDEF_ENUM_1_2, 22); checkEnum(TYPEDEF_ENUM_2_1, 31); checkEnum(TYPEDEF_ENUM_2_2, 32); +checkEnum(ENUM_REF_1, 1); +checkEnum(ENUM_REF_2, 10); + +checkEnum(clsEnum_CLS_ENUM_1, 100); +checkEnum(clsEnum_CLS_ENUM_2, 101); + +checkEnum(clsEnum_CLS_ENUM_REF_1, 101); +checkEnum(clsEnum_CLS_ENUM_REF_2, 110); + exec("swigtest.quit", -1); diff --git a/Examples/test-suite/scilab/template_rename_runme.sci b/Examples/test-suite/scilab/template_rename_runme.sci index 9c9512930..7b6b0de84 100644 --- a/Examples/test-suite/scilab/template_rename_runme.sci +++ b/Examples/test-suite/scilab/template_rename_runme.sci @@ -6,7 +6,7 @@ checkequal(iFoo_spam_test(i, 5), 5, "iFoo_spam_test(i, 5) test fails"); checkequal(iFoo_groki_test(i, 6), 6, "iFoo_groki_test(i, 6) test fails"); delete_iFoo(i); -d = new_iFoo(); +d = new_dFoo(); checkequal(dFoo_blah_test(d, 4), 4, "dFoo_blah_test(d, 4) test fails"); checkequal(dFoo_spam(d, 5), 5, "dFoo_spam_test(d, 5) test fails"); checkequal(dFoo_grok_test(d, 6), 6, "dFoo_groki_test(d, 6) test fails"); diff --git a/Examples/test-suite/scilab/typedef_struct_cpp_runme.sci b/Examples/test-suite/scilab/typedef_struct_cpp_runme.sci new file mode 100644 index 000000000..e41c21629 --- /dev/null +++ b/Examples/test-suite/scilab/typedef_struct_cpp_runme.sci @@ -0,0 +1,29 @@ +exec("swigtest.start", -1); + +try + x = new_LineObj(); + LineObj_numpoints_set(x, 100); +catch + swigtesterror(); +end +if LineObj_numpoints_get(x) <> 100 then swigtesterror(); end + +if MS_NOOVERRIDE_get() <> -1111 then swigtesterror(); end + +try + y = make_a(); + A_t_a_set(y, 200); +catch + swigtesterror(); +end +if A_t_a_get(y) <> 200 then swigtesterror(); end + +try + A_t_b_set(y, 300); +catch + swigtesterror(); +end +if A_t_b_get(y) <> 300 then swigtesterror(); end + +exec("swigtest.quit", -1); + diff --git a/Examples/test-suite/scilab_enums.i b/Examples/test-suite/scilab_enums.i index 32d5a34de..9c2e393e0 100644 --- a/Examples/test-suite/scilab_enums.i +++ b/Examples/test-suite/scilab_enums.i @@ -35,4 +35,21 @@ typedef enum TYPEDEF_ENUM_2 { TYPEDEF_ENUM_2_2 = 32 } TYPEDEF_ENUM_2; +enum ENUM_REF { + ENUM_REF_1 = 1, + ENUM_REF_2 = ENUM_REF_1 + 9 +}; + +class clsEnum { +public: + enum CLS_ENUM { + CLS_ENUM_1 = 100, + CLS_ENUM_2 = 101 + }; + enum CLS_ENUM_REF { + CLS_ENUM_REF_1 = 101, + CLS_ENUM_REF_2 = CLS_ENUM_REF_1 + 9 + }; +}; + %} diff --git a/Examples/test-suite/smart_pointer_ignore.i b/Examples/test-suite/smart_pointer_ignore.i new file mode 100644 index 000000000..146a5e49e --- /dev/null +++ b/Examples/test-suite/smart_pointer_ignore.i @@ -0,0 +1,33 @@ +%module smart_pointer_ignore + + +%ignore Derived; + +%inline %{ +class Base { + public: + void baseMethod() {} +}; + +class Derived : public Base { + public: + void derivedMethod() {} +}; + +template +class Ptr { +public: + Ptr(T *t) : ptr(t) {} + T * operator->() const { return ptr; } +private: + T *ptr; +}; +%} + +%template(DerivedPtr) Ptr; + +%inline %{ +Ptr makeDerived() { + return Ptr(new Derived()); +} +%} diff --git a/Examples/test-suite/special_variable_attributes.i b/Examples/test-suite/special_variable_attributes.i new file mode 100644 index 000000000..973a09344 --- /dev/null +++ b/Examples/test-suite/special_variable_attributes.i @@ -0,0 +1,170 @@ +%module special_variable_attributes + +// Special variable expansion and special variable macros, aka embedded typemaps - expansion tests +// Tests these are expanded within typemap attributes. +// Also tests that these are expanded when used together, so that the special variables +// can be used as the type passed to the special variable macro. +// C# is used for testing as it is one of the few languages that uses a lot of typemap attributes. +// Attributes in both 'in' and 'out' typemaps are needed, that is, +// typemaps targeting both parameters and return values respectively). + +#ifdef SWIGCSHARP +// Check special variable expansion in typemap attributes. +// This changes return by reference into return by value. +// Takes advantage of the fact that 'int' is a valid type in both C and C#. +// This is not a realistic use, just a way to test the variable expansion in the 'out' attribute. +%typemap(ctype, out="$*1_ltype") int& getNumber1 "_not_used_" +%typemap(imtype, out="$*1_ltype") int& getNumber1 "_not_used_" +%typemap(cstype, out="$*1_ltype") int& getNumber1 "_not_used_" +%typemap(out) int& getNumber1 "$result = *$1;" +%typemap(csout, excode=SWIGEXCODE) int & getNumber1 { + int ret = $imcall;$excode + return ret; + } +#endif + +%inline %{ +int& getNumber1() { + static int num = 111; + return num; +} +%} + +#ifdef SWIGCSHARP +// Check special variable macro expansion in typemap attributes. +// This changes return by reference into return by value. +%typemap(ctype, out="$typemap(ctype, int)") int& getNumber2 "_not_used_" +%typemap(imtype, out="$typemap(imtype, int)") int& getNumber2 "_not_used_" +%typemap(cstype, out="$typemap(cstype, int)") int& getNumber2 "_not_used_" +%typemap(out) int& getNumber2 "$result = *$1;" +%typemap(csout, excode=SWIGEXCODE) int & getNumber2 { + int ret = $imcall;$excode + return ret; + } +#endif + +%inline %{ +int& getNumber2() { + static int num = 222; + return num; +} +%} + + +#ifdef SWIGCSHARP +// Check special variable macro expansion and special variable expansion in typemap attributes. +// This changes return by reference into return by value. +%typemap(ctype, out="$typemap(ctype, $*1_ltype)") int& getNumber3 "_not_used_" +%typemap(imtype, out="$typemap(imtype, $*1_ltype)") int& getNumber3 "_not_used_" +%typemap(cstype, out="$typemap(cstype, $*1_ltype)") int& getNumber3 "_not_used_" +%typemap(out) int& getNumber3 "$result = *$1;" +%typemap(csout, excode=SWIGEXCODE) int & getNumber3 { + int ret = $imcall;$excode + return ret; + } +#endif + +%inline %{ +int& getNumber3() { + static int num = 333; + return num; +} +%} + +#ifdef SWIGCSHARP +// Check special variable macro expansion in typemap attributes. +%typemap(csin, + pre=" $typemap(cstype, int) $csinput_scaled = 11;" + ) int num1 +%{$csinput * $csinput_scaled %} +#endif + +%inline %{ +int bounceNumber1(int num1) { + return num1; +} +%} + +#ifdef SWIGCSHARP +// Check special variable expansion in typemap attributes. +%typemap(csin, + pre=" $1_type $csinput_scaled = 22;" + ) int num2 +%{$csinput * $csinput_scaled %} +#endif + +%inline %{ +int bounceNumber2(int num2) { + return num2; +} +%} + +#ifdef SWIGCSHARP +// Check special variable and special variable macro expansion in typemap attributes. +%typemap(csin, + pre=" $typemap(cstype, $1_type) $csinput_scaled = 33;" + ) int num3 +%{$csinput * $csinput_scaled %} +#endif + +%inline %{ +int bounceNumber3(int num3) { + return num3; +} +%} + +///////////////////////////////// +//// Multi-argument typemaps //// +///////////////////////////////// + +// Test expansion of special variables +#ifdef SWIGCSHARP +%typemap(ctype) (int intvar, char charvar) "double" +%typemap(imtype) (int intvar, char charvar) "double" +%typemap(cstype) (int intvar, char charvar) "double" +%typemap(in) (int intvar, char charvar) +%{ + // split double value a.b into two numbers, a and b*100 + $1 = (int)$input; + $2 = (char)(($input - $1 + 0.005) * 100); +%} +%typemap(csin, + pre=" $1_type $csinput_$1_type = 50;\n" // $1_type should expand to int + " $2_type $csinput_$2_type = 'A';" // $2_type should expand to char + ) (int intvar, char charvar) +%{$csinput + ($csinput_int - 50 + $csinput_char - 'A') + ($csinput_$1_type - 50 + $csinput_$2_type - 'A')%} +#endif + +%inline %{ +int multi1(int intvar, char charvar) { + return intvar + charvar; +} +%} + +#ifdef SWIGCSHARP +%typemap(csin, + pre=" $typemap(cstype, int) $csinput_$typemap(cstype, int) = 50;\n" // also should expand to int + " $typemap(cstype, char) $csinput_$typemap(cstype, char) = 'A';" // also should expand to char + ) (int intvar, char charvar) +%{55 + $csinput + ($csinput_int - 50 + $csinput_char - 'A') + ($csinput_$typemap(cstype, int) - 50 + $csinput_$typemap(cstype, char) - 'A')%} +#endif + +%inline %{ +int multi2(int intvar, char charvar) { + return intvar + charvar; +} +%} + +#ifdef SWIGCSHARP +%typemap(csin, + pre=" $typemap(cstype, $1_type) $csinput_$typemap(cstype, $1_type) = 50;\n" // also should expand to int + " $typemap(cstype, $2_type) $csinput_$typemap(cstype, $2_type) = 'A';" // also should expand to char + ) (int intvar, char charvar) +%{77 + $csinput + ($csinput_int - 50 + $csinput_char - 'A') + ($csinput_$typemap(cstype, $1_type) - 50 + $csinput_$typemap(cstype, $2_type) - 'A')%} +#endif + +%inline %{ +int multi3(int intvar, char charvar) { + return intvar + charvar; +} +%} diff --git a/Examples/test-suite/string_constants.i b/Examples/test-suite/string_constants.i new file mode 100644 index 000000000..60f8c1859 --- /dev/null +++ b/Examples/test-suite/string_constants.i @@ -0,0 +1,44 @@ +%module string_constants +// Test unusual string constants + +%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK); + +#if defined(SWIGCSHARP) +%csconst(1); +%csconstvalue("\"AEIOU\\n\"") SS1; +%csconstvalue("\"AEIOU\\n\"") SS2; +#endif +#if defined(SWIGJAVA) +%javaconst(1); +#endif +%inline %{ +#define SS1 "ÆÎOU\n" +#define AA1 "A\rB\nC" +#define EE1 "\124\125\126" +#define XX1 "\x57\x58\x59" +#define ZS1 "\0" +#define ES1 "" +%} +%constant SS2="ÆÎOU\n"; +%constant AA2="A\rB\nC"; +%constant EE2="\124\125\126"; +%constant XX2="\x57\x58\x59"; +%constant ZS2="\0"; +%constant ES2=""; + +%inline %{ +static const char *SS3 = "ÆÎOU\n"; +static const char *AA3 = "A\rB\nC"; +static const char *EE3 = "\124\125\126"; +static const char *XX3 = "\x57\x58\x59"; +static const char *ZS3 = "\0"; +static const char *ES3 = ""; +struct things { + const char * defarguments1(const char *SS4 = "ÆÎOU\n") { return SS4; } + const char * defarguments2(const char *AA4 = "A\rB\nC") { return AA4; } + const char * defarguments3(const char *EE4 = "\124\125\126") { return EE4; } + const char * defarguments4(const char *XX4 = "\x57\x58\x59") { return XX4; } + const char * defarguments5(const char *ZS4 = "\0") { return ZS4; } + const char * defarguments6(const char *ES4 = "") { return ES4; } +}; +%} diff --git a/Examples/test-suite/swig_exception.i b/Examples/test-suite/swig_exception.i new file mode 100644 index 000000000..3cf8b406c --- /dev/null +++ b/Examples/test-suite/swig_exception.i @@ -0,0 +1,91 @@ +/* File : swig_exception.i + * Test SWIG_exception(). + */ +%module swig_exception + +%include exception.i + +%exception { + try { + $action + } catch (std::exception& e) { + SWIG_exception(SWIG_SystemError, e.what()); + } +} + +%inline %{ +class Value { + int a_; + int b_; +public: + Value(int a, int b) : a_(a), b_(b) {} +}; + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; + void move(double dx, double dy); + virtual double area() = 0; + virtual double perimeter() = 0; + virtual Value throwException(); + static int nshapes; +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); +}; +%} + +%{ +#define PI 3.14159265358979323846 + +#include + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +Value Shape::throwException() { + throw std::logic_error("OK"); +} + +int Shape::nshapes = 0; + +double Circle::area() { + return PI*radius*radius; +} + +double Circle::perimeter() { + return 2*PI*radius; +} + +double Square::area() { + return width*width; +} + +double Square::perimeter() { + return 4*width; +} +%} diff --git a/Examples/test-suite/tcl/Makefile.in b/Examples/test-suite/tcl/Makefile.in index 82c59dee4..322e71914 100644 --- a/Examples/test-suite/tcl/Makefile.in +++ b/Examples/test-suite/tcl/Makefile.in @@ -55,4 +55,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" tcl_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/test-suite/template_default_arg.i b/Examples/test-suite/template_default_arg.i index faa0f686b..8747fb988 100644 --- a/Examples/test-suite/template_default_arg.i +++ b/Examples/test-suite/template_default_arg.i @@ -38,7 +38,7 @@ X(const T& t = T()) {} X(double a, const T& t = T(0)) {} T meth(double a, const T& t = T(0)) { return t; } - const T& meth(const T& t = T(0)) { return t; } + const T& meth(const T& t = T(0)) { static T tt; tt = t; return tt; } }; template class Y : private X { diff --git a/Examples/test-suite/template_default_arg_overloaded.i b/Examples/test-suite/template_default_arg_overloaded.i new file mode 100644 index 000000000..ef8320692 --- /dev/null +++ b/Examples/test-suite/template_default_arg_overloaded.i @@ -0,0 +1,67 @@ +%module template_default_arg_overloaded + +// Github issue #529 + +%include + +%inline %{ +#include + +namespace lsst { +namespace daf { +namespace bass { + +class PropertyList { +public: + PropertyList(void) {}; + + virtual ~PropertyList(void) {}; + + template int set(std::string const& name1, T const& value1, bool inPlace1=true) { return 1; } + + int set(std::string const& name2, PropertyList const& value2, bool inPlace2=true) { return 2; } + + template int set(std::string const& name3, T const& value3, std::string const& comment3, bool inPlace3=true) { return 3; } +}; + +}}} // namespace lsst::daf::bass + +// As above but in global namespace +class PropertyListGlobal { +public: + PropertyListGlobal(void) {}; + + virtual ~PropertyListGlobal(void) {}; + + template int set(std::string const& name1, T const& value1, bool inPlace1=true) { return 1; } + + int set(std::string const& name2, PropertyListGlobal const& value2, bool inPlace2=true) { return 2; } + + template int set(std::string const& name3, T const& value3, std::string const& comment3, bool inPlace3=true) { return 3; } +}; + +%} + +%template(setInt) lsst::daf::bass::PropertyList::set; +%template(setIntGlobal) PropertyListGlobal::set; + + +// Global functions +%inline %{ +template int goopGlobal(T i1, bool b1 = true) { return 1; } +int goopGlobal(short s2 = 0) { return 2; } +template int goopGlobal(const char *s3, bool b3 = true) { return 3; } +%} + +// Global functions in a namespace +%inline %{ +namespace lsst { +template int goop(T i1, bool b1 = true) { return 1; } +int goop(short s2 = 0) { return 2; } +template int goop(const char *s3, bool b3 = true) { return 3; } +} +%} + +%template(GoopIntGlobal) goopGlobal; +%template(GoopInt) lsst::goop; + diff --git a/Examples/test-suite/template_default_arg_overloaded_extend.i b/Examples/test-suite/template_default_arg_overloaded_extend.i new file mode 100644 index 000000000..67d66c2fa --- /dev/null +++ b/Examples/test-suite/template_default_arg_overloaded_extend.i @@ -0,0 +1,44 @@ +%module template_default_arg_overloaded_extend + +%inline %{ +namespace gaia2 { + +struct Filter {}; +struct SearchPoint {}; +struct DataSet {}; + +template +class BaseSearchSpace {}; + +template +class BaseResultSet { +public: + const char *over(int i = 0) { + return "over(int)"; + } +}; +} +%} + +// Specialized template extend +%extend gaia2::BaseResultSet { + int go_get_method(int n, gaia2::SearchPoint, int offset = -1) { + return offset; + } + const char *over(gaia2::SearchPoint, int x = 0) { + return "over(giai2::SearchPoint, int)"; + } +} + +// Generic extend for all template instantiations +%extend gaia2::BaseResultSet { + int go_get_template(int n, SearchPointType sss, int offset = -2) { + return offset; + } + const char *over(bool b, SearchPointType, int x = 0) { + return "over(bool, SearchPointType, int)"; + } +} + +%template(ResultSet) gaia2::BaseResultSet; + diff --git a/Examples/test-suite/template_typedef_inherit.i b/Examples/test-suite/template_typedef_inherit.i index 861905b43..ccc96f49f 100644 --- a/Examples/test-suite/template_typedef_inherit.i +++ b/Examples/test-suite/template_typedef_inherit.i @@ -10,7 +10,10 @@ typedef std::string String; namespace Type { - template class TypedInterfaceObject {}; + template class TypedInterfaceObject { + public: + virtual ~TypedInterfaceObject() {} + }; template class TypedCollectionInterfaceObject : public TypedInterfaceObject { public: @@ -27,6 +30,7 @@ namespace Type { /** Method add() appends an element to the collection */ inline virtual void add(const T & elt) {} + virtual ~PersistentCollection() {} }; } %} diff --git a/Examples/test-suite/traits.i b/Examples/test-suite/traits.i deleted file mode 100644 index 0d25a60d9..000000000 --- a/Examples/test-suite/traits.i +++ /dev/null @@ -1,6 +0,0 @@ -%module traits - -%include typemaps/traits.swg - - -%fragment("Traits"); diff --git a/Examples/test-suite/typedef_struct.i b/Examples/test-suite/typedef_struct.i index 97456d9a6..185e81105 100644 --- a/Examples/test-suite/typedef_struct.i +++ b/Examples/test-suite/typedef_struct.i @@ -1,6 +1,13 @@ %module typedef_struct %inline %{ + +#if __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +/* for anonymous enums */ +/* dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] */ +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif + typedef struct { int numpoints; } LineObj; diff --git a/Examples/test-suite/typedef_struct_cpp.i b/Examples/test-suite/typedef_struct_cpp.i new file mode 100644 index 000000000..7c6e3fff9 --- /dev/null +++ b/Examples/test-suite/typedef_struct_cpp.i @@ -0,0 +1,3 @@ +%module typedef_struct_cpp + +%include "typedef_struct.i" diff --git a/Examples/test-suite/typemap_documentation.i b/Examples/test-suite/typemap_documentation.i new file mode 100644 index 000000000..b7c1ddd22 --- /dev/null +++ b/Examples/test-suite/typemap_documentation.i @@ -0,0 +1,50 @@ +%module typemap_documentation + +// A place for checking that documented typemaps are working. +// The UTL languages are the only ones that are consistent enough to support these generic typemap functions. +// These are in the Typemaps.html chapter. + +%inline %{ +class Foo { +public: + int x; +}; + +class Bar { +public: + int y; +}; +%} + +#if defined(SWIGUTL) +%typemap(in) Foo * { + if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) { + SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo"); + } +} +#endif + +%inline %{ +int GrabVal(Foo *f) { + return f->x; +} +%} + + +#if defined(SWIGUTL) +%typemap(in) Foo * { + if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) { + Bar *temp; + if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar *), 0))) { + SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo or Bar"); + } + $1 = (Foo *)temp; + } +} +#endif + +%inline %{ +int GrabValFooBar(Foo *f) { + return f->x; +} +%} diff --git a/Examples/test-suite/typemap_manyargs.i b/Examples/test-suite/typemap_manyargs.i index d26e97714..426fcca1b 100644 --- a/Examples/test-suite/typemap_manyargs.i +++ b/Examples/test-suite/typemap_manyargs.i @@ -13,6 +13,7 @@ $9 = &temp9; $10 = &temp10; // the code generated for this was arg20 = &temp10; and arg20 does not exist. int $10_ptr = 0; // Was arg20_ptr + (void)$10_ptr; } %inline %{ diff --git a/Examples/test-suite/typemap_subst.i b/Examples/test-suite/typemap_subst.i index 91ac62020..946384840 100644 --- a/Examples/test-suite/typemap_subst.i +++ b/Examples/test-suite/typemap_subst.i @@ -27,12 +27,14 @@ (void)c; (void)d; (void)e; + (void)f; } { /* Test locals */ basetemp.member = 0; startemp = &basetemp; temp = &startemp; amptemp = &temp; + (void)amptemp; } { /* Test descriptors */ void *desc = $descriptor; diff --git a/Examples/test-suite/typemap_various.i b/Examples/test-suite/typemap_various.i index c2f70ce55..3436bac1c 100644 --- a/Examples/test-suite/typemap_various.i +++ b/Examples/test-suite/typemap_various.i @@ -25,23 +25,33 @@ void foo1(Foo f, const Foo& ff) {} void foo2(Foo f, const Foo& ff) {} %} -#ifdef SWIGUTL -%typemap(ret) int Bar1::foo() { /* hello1 */ }; -%typemap(ret) int Bar2::foo() { /* hello2 */ }; -%typemap(ret) int foo() {/* hello3 */ }; -#endif +// Check "ret" typemap is implemented +%{ + template struct NeededForTest {}; +%} +%fragment("NeededForTest", "header") %{ + template<> struct NeededForTest { NeededForTest(short) {} }; +%} + +%typemap(ret) short "_ret_typemap_for_short_no_compile" +%typemap(ret, fragment="NeededForTest") short Bar1::foofunction() { /* ret typemap for short */ NeededForTest needed($1); }; +%typemap(ret, fragment="NeededForTest") short globalfoofunction() { /* ret typemap for short */ NeededForTest needed($1); }; %inline %{ struct Bar1 { - int foo() { return 1;} - }; - - struct Bar2 { - int foo() { return 1;} + short foofunction() { return 1;} }; + short globalfoofunction() { return 1;} %} - +%{ +void CheckRetTypemapUsed() { + // If the "ret" typemap is not used, the NeededForTest template specialization will not have been + // generated and so the following code will result in a compile failure + NeededForTest needed(111); + (void)needed; +} +%} %newobject FFoo::Bar(bool) const ; %typemap(newfree) char* Bar(bool) { @@ -62,7 +72,7 @@ void foo2(Foo f, const Foo& ff) {} #endif // Test obscure bug where named typemaps where not being applied when symbol name contained a number -%typemap(out) double "_typemap_for_double_no_compile_" +%typemap(out) double "_out_typemap_for_double_no_compile_" %typemap(out) double ABCD::meth {$1 = 0.0; TYPEMAP_OUT_INIT} %typemap(out) double ABCD::m1 {$1 = 0.0; TYPEMAP_OUT_INIT} %typemap(out) double ABCD::_x2 {$1 = 0.0; TYPEMAP_OUT_INIT} diff --git a/Examples/test-suite/uffi/Makefile.in b/Examples/test-suite/uffi/Makefile.in index 275778c87..5d6dc110c 100644 --- a/Examples/test-suite/uffi/Makefile.in +++ b/Examples/test-suite/uffi/Makefile.in @@ -48,4 +48,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" uffi_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR='$(SRCDIR)' uffi_clean diff --git a/Examples/test-suite/unicode_strings.i b/Examples/test-suite/unicode_strings.i index 56063c8a4..9be3748e6 100644 --- a/Examples/test-suite/unicode_strings.i +++ b/Examples/test-suite/unicode_strings.i @@ -2,6 +2,10 @@ %include +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} + %inline %{ const char* non_utf8_c_str(void) { @@ -12,4 +16,8 @@ std::string non_utf8_std_string(void) { return std::string("h\xe9llo w\xc3\xb6rld"); } +char *charstring(char *s) { + return s; +} + %} diff --git a/Examples/test-suite/using_protected.i b/Examples/test-suite/using_protected.i index 402a7c8da..331d99585 100644 --- a/Examples/test-suite/using_protected.i +++ b/Examples/test-suite/using_protected.i @@ -6,6 +6,7 @@ protected: int x; int blah(int xx) { return xx; } virtual int vmethod(int xx) { return xx; } + virtual ~Foo() {} }; class FooBar : public Foo { diff --git a/Examples/test-suite/variable_replacement.i b/Examples/test-suite/variable_replacement.i new file mode 100644 index 000000000..d44ac1b96 --- /dev/null +++ b/Examples/test-suite/variable_replacement.i @@ -0,0 +1,16 @@ +%module variable_replacement + +%inline %{ + +class A { +public: + int a(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12) + { + return 0; + } +}; + +class B : public A { +}; + +%} diff --git a/Examples/test-suite/virtual_vs_nonvirtual_base.i b/Examples/test-suite/virtual_vs_nonvirtual_base.i index 009461835..25dfd7cf6 100644 --- a/Examples/test-suite/virtual_vs_nonvirtual_base.i +++ b/Examples/test-suite/virtual_vs_nonvirtual_base.i @@ -13,6 +13,7 @@ class SimpleNonVirtual { public: int dummy() { return 0; } + virtual ~SimpleNonVirtual() {} }; class SimpleReturnClass diff --git a/Examples/xml/Makefile.in b/Examples/xml/Makefile.in index 27c86e3e9..44894b8ea 100644 --- a/Examples/xml/Makefile.in +++ b/Examples/xml/Makefile.in @@ -1,6 +1,13 @@ # Examples/xml/Makefile +srcdir = @srcdir@ top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +SWIGEXE = $(top_builddir)/swig +SWIG_LIB_DIR = $(top_srcdir)/Lib +SWIG_LIB_SET = @SWIG_LIB_SET@ +SWIGINVOKE = $(SWIG_LIB_SET) $(SWIGTOOL) $(SWIGEXE) cleanup = tail +2 \ | sed -e 's/ident="ID[0-9A-F]*"//g' \ @@ -19,14 +26,12 @@ all-dot-i-files = \ example_xml.i \ gnarly.i -chk-swiglib = $(top_srcdir)/Lib - check: for f in $(all-dot-i-files) ; do \ base=`basename $$f .i` ; \ xml=$$base.xml ; \ - SWIG_LIB=$(chk-swiglib) $(top_srcdir)/swig -xml $$xml $$f ; \ - cat $$xml | $(cleanup) | diff -c $$base.expected-xml - ; \ + $(SWIGINVOKE) -xml $$xml ${srcdir}/$$f ; \ + cat $$xml | $(cleanup) | diff -c ${srcdir}/$$base.expected-xml - ; \ done clean: @@ -38,7 +43,7 @@ distclean: clean # from here on, non-developers beware! %.expected-xml : %.i - SWIG_LIB=$(top_srcdir)/Lib $(top_srcdir)/swig -xml tmp-file $^ + $(SWIGINVOKE) -xml tmp-file $^ cat tmp-file | $(cleanup) > $@ rm -f tmp-file diff --git a/Lib/allkw.swg b/Lib/allkw.swg index 563190e19..b9413191f 100644 --- a/Lib/allkw.swg +++ b/Lib/allkw.swg @@ -24,6 +24,7 @@ %include %include %include +%include %include %include %include diff --git a/Lib/carrays.i b/Lib/carrays.i index 201c17cac..3a9c3cfee 100644 --- a/Lib/carrays.i +++ b/Lib/carrays.i @@ -81,7 +81,7 @@ typedef struct { #ifdef __cplusplus NAME(int nelements) { - return new TYPE[nelements]; + return new TYPE[nelements](); } ~NAME() { delete [] self; diff --git a/Lib/cdata.i b/Lib/cdata.i index b9b8e1887..730ecccfb 100644 --- a/Lib/cdata.i +++ b/Lib/cdata.i @@ -29,13 +29,20 @@ typedef struct SWIGCDATA { } %typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); -#elif SWIGPHP +#elif SWIGPHP5 %typemap(out) SWIGCDATA { ZVAL_STRINGL($result, $1.data, $1.len, 1); } %typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); +#elif SWIGPHP7 + +%typemap(out) SWIGCDATA { + ZVAL_STRINGL($result, $1.data, $1.len); +} +%typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH); + #elif SWIGJAVA %apply (char *STRING, int LENGTH) { (const void *indata, int inlen) } diff --git a/Lib/csharp/boost_intrusive_ptr.i b/Lib/csharp/boost_intrusive_ptr.i index 1cc5efda7..d0a048d16 100644 --- a/Lib/csharp/boost_intrusive_ptr.i +++ b/Lib/csharp/boost_intrusive_ptr.i @@ -1,511 +1,510 @@ -// Users can provide their own SWIG_INTRUSIVE_PTR_TYPEMAPS or SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP macros before including this file to change the -// visibility of the constructor and getCPtr method if desired to public if using multiple modules. -#ifndef SWIG_INTRUSIVE_PTR_TYPEMAPS -#define SWIG_INTRUSIVE_PTR_TYPEMAPS(CONST, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS_IMPLEMENTATION(internal, internal, CONST, TYPE) -#endif -#ifndef SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP -#define SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP(CONST, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP_IMPLEMENTATION(internal, internal, CONST, TYPE) -#endif - -%include - -// Language specific macro implementing all the customisations for handling the smart pointer -%define SWIG_INTRUSIVE_PTR_TYPEMAPS_IMPLEMENTATION(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, CONST, TYPE...) - -// %naturalvar is as documented for member variables -%naturalvar TYPE; -%naturalvar SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >; - -// destructor wrapper customisation -%feature("unref") TYPE "(void)arg1; delete smartarg1;" - -// Typemap customisations... - -%typemap(in, canthrow=1) CONST TYPE ($&1_type argp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ - // plain value - argp = (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0; - if (!argp) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Attempt to dereference null $1_type", 0); - return $null; - } - $1 = *argp; -%} -%typemap(out, fragment="SWIG_intrusive_deleter") CONST TYPE %{ - //plain value(out) - $1_ltype* resultp = new $1_ltype(($1_ltype &)$1); - intrusive_ptr_add_ref(resultp); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(resultp, SWIG_intrusive_deleter< CONST TYPE >()); -%} - -%typemap(in, canthrow=1) CONST TYPE * (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ - // plain pointer - smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input; - $1 = (TYPE *)(smartarg ? smartarg->get() : 0); -%} -%typemap(out, fragment="SWIG_intrusive_deleter,SWIG_null_deleter") CONST TYPE * %{ - //plain pointer(out) - #if ($owner) - if ($1) { - intrusive_ptr_add_ref($1); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1, SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } - #else - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0; - #endif -%} - -%typemap(in, canthrow=1) CONST TYPE & (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ - // plain reference - $1 = ($1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); - if(!$1) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type reference is null", 0); - return $null; - } -%} -%typemap(out, fragment="SWIG_intrusive_deleter,SWIG_null_deleter") CONST TYPE & %{ - //plain reference(out) - #if ($owner) - if ($1) { - intrusive_ptr_add_ref($1); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1, SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } - #else - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0; - #endif -%} - -%typemap(in) TYPE *CONST& ($*1_ltype temp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ - // plain pointer by reference - temp = ($*1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); - $1 = &temp; -%} -%typemap(out, fragment="SWIG_intrusive_deleter,SWIG_null_deleter") TYPE *CONST& %{ - // plain pointer by reference(out) - #if ($owner) - if (*$1) { - intrusive_ptr_add_ref(*$1); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1, SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } - #else - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_0); - #endif -%} - -%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ - // intrusive_ptr by value - smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; - if (smartarg) { - $1 = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); - } -%} -%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > %{ - if ($1) { - intrusive_ptr_add_ref($1.get()); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1.get(), SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } -%} - -%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast ($&1_type smartarg) %{ - // shared_ptr by value - smartarg = *($&1_ltype*)&$input; - if (smartarg) $1 = *smartarg; -%} -%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > ANY_TYPE_SWIGSharedPtrUpcast %{ - *($&1_ltype*)&$result = $1 ? new $1_ltype($1) : 0; -%} - -%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & ($*1_ltype tempnull, $*1_ltype temp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ - // intrusive_ptr by reference - if ( $input ) { - smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; - temp = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); - $1 = &temp; - } else { - $1 = &tempnull; - } -%} -%typemap(memberin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & %{ - delete &($1); - if ($self) { - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * temp = new SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(*$input); - $1 = *temp; - } -%} -%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & %{ - if (*$1) { - intrusive_ptr_add_ref($1->get()); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1->get(), SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } -%} - -%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * ($*1_ltype tempnull, $*1_ltype temp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ - // intrusive_ptr by pointer - if ( $input ) { - smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; - temp = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); - $1 = &temp; - } else { - $1 = &tempnull; - } -%} -%typemap(memberin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * %{ - delete $1; - if ($self) $1 = new SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(*$input); -%} -%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * %{ - if ($1 && *$1) { - intrusive_ptr_add_ref($1->get()); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1->get(), SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } - if ($owner) delete $1; -%} - -%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& (SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > temp, $*1_ltype tempp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ - // intrusive_ptr by pointer reference - smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; - if ($input) { - temp = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); - } - tempp = &temp; - $1 = &tempp; -%} -%typemap(memberin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& %{ - if ($self) $1 = *$input; -%} -%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& %{ - if (*$1 && **$1) { - intrusive_ptr_add_ref((*$1)->get()); - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >((*$1)->get(), SWIG_intrusive_deleter< CONST TYPE >()); - } else { - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; - } -%} - -// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug -%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ -#error "typemaps for $1_type not available" -%} -%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ -#error "typemaps for $1_type not available" -%} - - -%typemap (ctype) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, - SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "void *" -%typemap (imtype, out="global::System.IntPtr") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, - SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "global::System.Runtime.InteropServices.HandleRef" -%typemap (cstype) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, - SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "$typemap(cstype, TYPE)" -%typemap(csin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, - SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, - SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "$typemap(cstype, TYPE).getCPtr($csinput)" - -%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } -%typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > %{ - get { - $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode - return ret; - } %} -%typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >& %{ - get { - $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode - return ret; - } %} -%typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >* %{ - get { - $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode - return ret; - } %} - - -%typemap(csout, excode=SWIGEXCODE) CONST TYPE { - $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) CONST TYPE & { - $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) CONST TYPE * { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } -%typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { - global::System.IntPtr cPtr = $imcall; - $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode - return ret; - } - -// Base proxy classes -%typemap(csbody) TYPE %{ - private global::System.Runtime.InteropServices.HandleRef swigCPtr; - private bool swigCMemOwnBase; - - PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { - swigCMemOwnBase = cMemoryOwn; - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); - } - - CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; - } -%} - -// Derived proxy classes -%typemap(csbody_derived) TYPE %{ - private global::System.Runtime.InteropServices.HandleRef swigCPtr; - private bool swigCMemOwnDerived; - - PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { - swigCMemOwnDerived = cMemoryOwn; - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); - } - - CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; - } -%} - -%typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { - lock(this) { - if (swigCPtr.Handle != global::System.IntPtr.Zero) { - if (swigCMemOwnBase) { - swigCMemOwnBase = false; - $imcall; - } - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); - } - global::System.GC.SuppressFinalize(this); - } - } - -%typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { - lock(this) { - if (swigCPtr.Handle != global::System.IntPtr.Zero) { - if (swigCMemOwnDerived) { - swigCMemOwnDerived = false; - $imcall; - } - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); - } - global::System.GC.SuppressFinalize(this); - base.Dispose(); - } - } - -// CONST version needed ???? also for C# -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" - - -%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; -%template() SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >; -%enddef - - -///////////////////////////////////////////////////////////////////// - - -%include - -%define SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP_IMPLEMENTATION(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, CONST, TYPE...) - -%naturalvar TYPE; -%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; - -// destructor mods -%feature("unref") TYPE "(void)arg1; delete smartarg1;" - - -// plain value -%typemap(in, canthrow=1) CONST TYPE ($&1_type argp = 0) %{ - argp = (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0; - if (!argp) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Attempt to dereference null $1_type", 0); - return $null; - } - $1 = *argp; %} -%typemap(out) CONST TYPE -%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)); %} - -// plain pointer -%typemap(in) CONST TYPE * (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ - smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input; - $1 = (TYPE *)(smartarg ? smartarg->get() : 0); %} -%typemap(out, fragment="SWIG_null_deleter") CONST TYPE * %{ - *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0; -%} - -// plain reference -%typemap(in, canthrow=1) CONST TYPE & %{ - $1 = ($1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); - if (!$1) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type reference is null", 0); - return $null; - } %} -%typemap(out, fragment="SWIG_null_deleter") CONST TYPE & -%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner); %} - -// plain pointer by reference -%typemap(in) TYPE *CONST& ($*1_ltype temp = 0) -%{ temp = ($*1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); - $1 = &temp; %} -%typemap(out, fragment="SWIG_null_deleter") TYPE *CONST& -%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner); %} - -%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast ($&1_type smartarg) %{ - // shared_ptr by value - smartarg = *($&1_ltype*)&$input; - if (smartarg) $1 = *smartarg; -%} -%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > ANY_TYPE_SWIGSharedPtrUpcast %{ - *($&1_ltype*)&$result = $1 ? new $1_ltype($1) : 0; -%} - -// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug -%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ -#error "typemaps for $1_type not available" -%} -%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ -#error "typemaps for $1_type not available" -%} - - -%typemap (ctype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "void *" -%typemap (imtype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "void *" -%typemap (cstype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "$typemap(cstype, TYPE)" -%typemap (csin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "$typemap(cstype, TYPE).getCPtr($csinput)" -%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { - global::System.IntPtr cPtr = $imcall; - return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); - } - -%typemap(csout, excode=SWIGEXCODE) CONST TYPE { - return new $typemap(cstype, TYPE)($imcall, true); - } -%typemap(csout, excode=SWIGEXCODE) CONST TYPE & { - return new $typemap(cstype, TYPE)($imcall, true); - } -%typemap(csout, excode=SWIGEXCODE) CONST TYPE * { - global::System.IntPtr cPtr = $imcall; - return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); - } -%typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { - global::System.IntPtr cPtr = $imcall; - return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); - } - -// Base proxy classes -%typemap(csbody) TYPE %{ - private global::System.Runtime.InteropServices.HandleRef swigCPtr; - private bool swigCMemOwnBase; - - PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { - swigCMemOwnBase = cMemoryOwn; - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); - } - - CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; - } -%} - -// Derived proxy classes -%typemap(csbody_derived) TYPE %{ - private global::System.Runtime.InteropServices.HandleRef swigCPtr; - private bool swigCMemOwnDerived; - - PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { - swigCMemOwnDerived = cMemoryOwn; - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); - } - - CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; - } -%} - -%typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { - lock(this) { - if (swigCPtr.Handle != global::System.IntPtr.Zero) { - if (swigCMemOwnBase) { - swigCMemOwnBase = false; - $imcall; - } - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); - } - global::System.GC.SuppressFinalize(this); - } - } - -%typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { - lock(this) { - if (swigCPtr.Handle != global::System.IntPtr.Zero) { - if (swigCMemOwnDerived) { - swigCMemOwnDerived = false; - $imcall; - } - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); - } - global::System.GC.SuppressFinalize(this); - base.Dispose(); - } - } - - -// CONST version needed ???? also for C# -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" -%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" - - -%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; -%enddef - +// Users can provide their own SWIG_INTRUSIVE_PTR_TYPEMAPS or SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP macros before including this file to change the +// visibility of the constructor and getCPtr method if desired to public if using multiple modules. +#ifndef SWIG_INTRUSIVE_PTR_TYPEMAPS +#define SWIG_INTRUSIVE_PTR_TYPEMAPS(CONST, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS_IMPLEMENTATION(internal, internal, CONST, TYPE) +#endif +#ifndef SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP +#define SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP(CONST, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP_IMPLEMENTATION(internal, internal, CONST, TYPE) +#endif + +%include + +// Language specific macro implementing all the customisations for handling the smart pointer +%define SWIG_INTRUSIVE_PTR_TYPEMAPS_IMPLEMENTATION(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, CONST, TYPE...) + +// %naturalvar is as documented for member variables +%naturalvar TYPE; +%naturalvar SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >; + +// destructor wrapper customisation +%feature("unref") TYPE "(void)arg1; delete smartarg1;" + +// Typemap customisations... + +%typemap(in, canthrow=1) CONST TYPE ($&1_type argp = 0) %{ + // plain value + argp = (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0; + if (!argp) { + SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Attempt to dereference null $1_type", 0); + return $null; + } + $1 = *argp; +%} +%typemap(out, fragment="SWIG_intrusive_deleter") CONST TYPE %{ + //plain value(out) + $1_ltype* resultp = new $1_ltype(($1_ltype &)$1); + intrusive_ptr_add_ref(resultp); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(resultp, SWIG_intrusive_deleter< CONST TYPE >()); +%} + +%typemap(in, canthrow=1) CONST TYPE * (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ + // plain pointer + smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input; + $1 = (TYPE *)(smartarg ? smartarg->get() : 0); +%} +%typemap(out, fragment="SWIG_intrusive_deleter,SWIG_null_deleter") CONST TYPE * %{ + //plain pointer(out) + #if ($owner) + if ($1) { + intrusive_ptr_add_ref($1); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1, SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } + #else + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0; + #endif +%} + +%typemap(in, canthrow=1) CONST TYPE & %{ + // plain reference + $1 = ($1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); + if(!$1) { + SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type reference is null", 0); + return $null; + } +%} +%typemap(out, fragment="SWIG_intrusive_deleter,SWIG_null_deleter") CONST TYPE & %{ + //plain reference(out) + #if ($owner) + if ($1) { + intrusive_ptr_add_ref($1); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1, SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } + #else + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0; + #endif +%} + +%typemap(in) TYPE *CONST& ($*1_ltype temp = 0) %{ + // plain pointer by reference + temp = ($*1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); + $1 = &temp; +%} +%typemap(out, fragment="SWIG_intrusive_deleter,SWIG_null_deleter") TYPE *CONST& %{ + // plain pointer by reference(out) + #if ($owner) + if (*$1) { + intrusive_ptr_add_ref(*$1); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1, SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } + #else + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_0); + #endif +%} + +%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ + // intrusive_ptr by value + smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; + if (smartarg) { + $1 = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); + } +%} +%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > %{ + if ($1) { + intrusive_ptr_add_ref($1.get()); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1.get(), SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } +%} + +%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast ($&1_type smartarg) %{ + // shared_ptr by value + smartarg = *($&1_ltype*)&$input; + if (smartarg) $1 = *smartarg; +%} +%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > ANY_TYPE_SWIGSharedPtrUpcast %{ + *($&1_ltype*)&$result = $1 ? new $1_ltype($1) : 0; +%} + +%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & ($*1_ltype tempnull, $*1_ltype temp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ + // intrusive_ptr by reference + if ( $input ) { + smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; + temp = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); + $1 = &temp; + } else { + $1 = &tempnull; + } +%} +%typemap(memberin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & %{ + delete &($1); + if ($self) { + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * temp = new SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(*$input); + $1 = *temp; + } +%} +%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & %{ + if (*$1) { + intrusive_ptr_add_ref($1->get()); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1->get(), SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } +%} + +%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * ($*1_ltype tempnull, $*1_ltype temp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ + // intrusive_ptr by pointer + if ( $input ) { + smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; + temp = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); + $1 = &temp; + } else { + $1 = &tempnull; + } +%} +%typemap(memberin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * %{ + delete $1; + if ($self) $1 = new SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(*$input); +%} +%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * %{ + if ($1 && *$1) { + intrusive_ptr_add_ref($1->get()); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1->get(), SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } + if ($owner) delete $1; +%} + +%typemap(in) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& (SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > temp, $*1_ltype tempp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * smartarg) %{ + // intrusive_ptr by pointer reference + smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >**)&$input; + if ($input) { + temp = SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >(smartarg->get(), true); + } + tempp = &temp; + $1 = &tempp; +%} +%typemap(memberin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& %{ + if ($self) $1 = *$input; +%} +%typemap(out, fragment="SWIG_intrusive_deleter") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& %{ + if (*$1 && **$1) { + intrusive_ptr_add_ref((*$1)->get()); + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >((*$1)->get(), SWIG_intrusive_deleter< CONST TYPE >()); + } else { + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = 0; + } +%} + +// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug +%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ +#error "typemaps for $1_type not available" +%} +%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ +#error "typemaps for $1_type not available" +%} + + +%typemap (ctype) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "void *" +%typemap (imtype, out="global::System.IntPtr") SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "global::System.Runtime.InteropServices.HandleRef" +%typemap (cstype) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "$typemap(cstype, TYPE)" +%typemap(csin) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > &, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *, + SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& "$typemap(cstype, TYPE).getCPtr($csinput)" + +%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > & { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > * { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > *& { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE > %{ + get { + $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode + return ret; + } %} +%typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >& %{ + get { + $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode + return ret; + } %} +%typemap(csvarout, excode=SWIGEXCODE2) SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >* %{ + get { + $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode + return ret; + } %} + + +%typemap(csout, excode=SWIGEXCODE) CONST TYPE { + $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) CONST TYPE & { + $typemap(cstype, TYPE) ret = new $typemap(cstype, TYPE)($imcall, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) CONST TYPE * { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } +%typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { + global::System.IntPtr cPtr = $imcall; + $typemap(cstype, TYPE) ret = (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true);$excode + return ret; + } + +// Base proxy classes +%typemap(csbody) TYPE %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + private bool swigCMemOwnBase; + + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { + swigCMemOwnBase = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; + } +%} + +// Derived proxy classes +%typemap(csbody_derived) TYPE %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + private bool swigCMemOwnDerived; + + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { + swigCMemOwnDerived = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; + } +%} + +%typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { + lock(this) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { + if (swigCMemOwnBase) { + swigCMemOwnBase = false; + $imcall; + } + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + global::System.GC.SuppressFinalize(this); + } + } + +%typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { + lock(this) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { + if (swigCMemOwnDerived) { + swigCMemOwnDerived = false; + $imcall; + } + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + global::System.GC.SuppressFinalize(this); + base.Dispose(); + } + } + +// CONST version needed ???? also for C# +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" + + +%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; +%template() SWIG_INTRUSIVE_PTR_QNAMESPACE::intrusive_ptr< CONST TYPE >; +%enddef + + +///////////////////////////////////////////////////////////////////// + + +%include + +%define SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP_IMPLEMENTATION(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, CONST, TYPE...) + +%naturalvar TYPE; +%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; + +// destructor mods +%feature("unref") TYPE "(void)arg1; delete smartarg1;" + + +// plain value +%typemap(in, canthrow=1) CONST TYPE ($&1_type argp = 0) %{ + argp = (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0; + if (!argp) { + SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Attempt to dereference null $1_type", 0); + return $null; + } + $1 = *argp; %} +%typemap(out) CONST TYPE +%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)); %} + +// plain pointer +%typemap(in) CONST TYPE * (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{ + smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input; + $1 = (TYPE *)(smartarg ? smartarg->get() : 0); %} +%typemap(out, fragment="SWIG_null_deleter") CONST TYPE * %{ + *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0; +%} + +// plain reference +%typemap(in, canthrow=1) CONST TYPE & %{ + $1 = ($1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); + if (!$1) { + SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type reference is null", 0); + return $null; + } %} +%typemap(out, fragment="SWIG_null_deleter") CONST TYPE & +%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner); %} + +// plain pointer by reference +%typemap(in) TYPE *CONST& ($*1_ltype temp = 0) +%{ temp = ($*1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0); + $1 = &temp; %} +%typemap(out, fragment="SWIG_null_deleter") TYPE *CONST& +%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner); %} + +%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast ($&1_type smartarg) %{ + // shared_ptr by value + smartarg = *($&1_ltype*)&$input; + if (smartarg) $1 = *smartarg; +%} +%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > ANY_TYPE_SWIGSharedPtrUpcast %{ + *($&1_ltype*)&$result = $1 ? new $1_ltype($1) : 0; +%} + +// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug +%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ +#error "typemaps for $1_type not available" +%} +%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ +#error "typemaps for $1_type not available" +%} + + +%typemap (ctype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "void *" +%typemap (imtype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "void *" +%typemap (cstype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "$typemap(cstype, TYPE)" +%typemap (csin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > "$typemap(cstype, TYPE).getCPtr($csinput)" +%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { + global::System.IntPtr cPtr = $imcall; + return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); + } + +%typemap(csout, excode=SWIGEXCODE) CONST TYPE { + return new $typemap(cstype, TYPE)($imcall, true); + } +%typemap(csout, excode=SWIGEXCODE) CONST TYPE & { + return new $typemap(cstype, TYPE)($imcall, true); + } +%typemap(csout, excode=SWIGEXCODE) CONST TYPE * { + global::System.IntPtr cPtr = $imcall; + return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); + } +%typemap(csout, excode=SWIGEXCODE) TYPE *CONST& { + global::System.IntPtr cPtr = $imcall; + return (cPtr == global::System.IntPtr.Zero) ? null : new $typemap(cstype, TYPE)(cPtr, true); + } + +// Base proxy classes +%typemap(csbody) TYPE %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + private bool swigCMemOwnBase; + + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) { + swigCMemOwnBase = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; + } +%} + +// Derived proxy classes +%typemap(csbody_derived) TYPE %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + private bool swigCMemOwnDerived; + + PTRCTOR_VISIBILITY $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclazznameSWIGSmartPtrUpcast(cPtr), true) { + swigCMemOwnDerived = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + CPTR_VISIBILITY static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; + } +%} + +%typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE { + lock(this) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { + if (swigCMemOwnBase) { + swigCMemOwnBase = false; + $imcall; + } + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + global::System.GC.SuppressFinalize(this); + } + } + +%typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE { + lock(this) { + if (swigCPtr.Handle != global::System.IntPtr.Zero) { + if (swigCMemOwnDerived) { + swigCMemOwnDerived = false; + $imcall; + } + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + global::System.GC.SuppressFinalize(this); + base.Dispose(); + } + } + + +// CONST version needed ???? also for C# +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" +%typemap(imtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "global::System.Runtime.InteropServices.HandleRef" + + +%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; +%enddef diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index f7b7927ba..a703899d8 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -409,8 +409,8 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { #endif %typemap(directorin) SWIGTYPE -%{ $input = (void *)&$1; %} -%typemap(csdirectorin) SWIGTYPE "new $&csclassname($iminput, false)" +%{ $input = (void *)new $1_ltype((const $1_ltype &)$1); %} +%typemap(csdirectorin) SWIGTYPE "new $&csclassname($iminput, true)" %typemap(csdirectorout) SWIGTYPE "$&csclassname.getCPtr($cscall).Handle" /* Generic pointers and references */ @@ -860,7 +860,8 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { global::System.IntPtr ret = $imcall;$excode return ret; } - +%typemap(csdirectorin) void *VOID_INT_PTR "$iminput" +%typemap(csdirectorout) void *VOID_INT_PTR "$cscall" /* Typemaps used for the generation of proxy and type wrapper class code */ %typemap(csbase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" diff --git a/Lib/csharp/csharpkw.swg b/Lib/csharp/csharpkw.swg index 43ca5993b..824f61874 100644 --- a/Lib/csharp/csharpkw.swg +++ b/Lib/csharp/csharpkw.swg @@ -2,9 +2,9 @@ #define CSHARP_CSHARPKW_SWG_ /* Warnings for C# keywords */ -#define CSHARPKW(x) %keywordwarn("'" `x` "' is a C# keyword, renaming to '_" `x` "'",rename="_%s") `x` +#define CSHARPKW(x) %keywordwarn("'" `x` "' is a C# keyword, renaming to '" `x` "_'",rename="%s_") `x` -#define CSHARPCLASSKW(x) %keywordwarn("'" `x` "' is a special method name used in the C# wrapper classes, class renamed to '_" `x` "'",%$isclass,rename="_%s") `x` +#define CSHARPCLASSKW(x) %keywordwarn("'" `x` "' is a special method name used in the C# wrapper classes, class renamed to '" `x` "_'",%$isclass,rename="%s_") `x` /* from diff --git a/Lib/csharp/std_array.i b/Lib/csharp/std_array.i new file mode 100644 index 000000000..c1fee124d --- /dev/null +++ b/Lib/csharp/std_array.i @@ -0,0 +1,227 @@ +/* ----------------------------------------------------------------------------- + * std_array.i + * + * SWIG typemaps for std::array + * C# implementation + * The C# wrapper is made to look and feel like a C# System.Collections.Generic.IReadOnlyList<> collection. + * ----------------------------------------------------------------------------- */ + +%{ +#include +#include +#include +%} + +%include + + +%define SWIG_STD_ARRAY_INTERNAL(T, N) +%typemap(csinterfaces) std::array< T, N > "global::System.IDisposable, global::System.Collections.IEnumerable\n , global::System.Collections.Generic.IEnumerable<$typemap(cstype, T)>\n"; +%typemap(cscode) std::array< T, N > %{ + public $csclassname(global::System.Collections.ICollection c) : this() { + if (c == null) + throw new global::System.ArgumentNullException("c"); + int end = global::System.Math.Min(this.Count, c.Count); + int i = 0; + foreach ($typemap(cstype, T) elem in c) { + if (i >= end) + break; + this[i++] = elem; + } + } + + public int Count { + get { + return (int)size(); + } + } + + public $typemap(cstype, T) this[int index] { + get { + return getitem(index); + } + set { + setitem(index, value); + } + } + + public bool IsEmpty { + get { + return empty(); + } + } + + public void CopyTo($typemap(cstype, T)[] array) + { + CopyTo(0, array, 0, this.Count); + } + + public void CopyTo($typemap(cstype, T)[] array, int arrayIndex) + { + CopyTo(0, array, arrayIndex, this.Count); + } + + public void CopyTo(int index, $typemap(cstype, T)[] array, int arrayIndex, int count) + { + if (array == null) + throw new global::System.ArgumentNullException("array"); + if (index < 0) + throw new global::System.ArgumentOutOfRangeException("index", "Value is less than zero"); + if (arrayIndex < 0) + throw new global::System.ArgumentOutOfRangeException("arrayIndex", "Value is less than zero"); + if (count < 0) + throw new global::System.ArgumentOutOfRangeException("count", "Value is less than zero"); + if (array.Rank > 1) + throw new global::System.ArgumentException("Multi dimensional array.", "array"); + if (index+count > this.Count || arrayIndex+count > array.Length) + throw new global::System.ArgumentException("Number of elements to copy is too large."); + for (int i=0; i global::System.Collections.Generic.IEnumerable<$typemap(cstype, T)>.GetEnumerator() { + return new $csclassnameEnumerator(this); + } + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() { + return new $csclassnameEnumerator(this); + } + + public $csclassnameEnumerator GetEnumerator() { + return new $csclassnameEnumerator(this); + } + + // Type-safe enumerator + /// Note that the IEnumerator documentation requires an InvalidOperationException to be thrown + /// whenever the collection is modified. This has been done for changes in the size of the + /// collection but not when one of the elements of the collection is modified as it is a bit + /// tricky to detect unmanaged code that modifies the collection under our feet. + public sealed class $csclassnameEnumerator : global::System.Collections.IEnumerator + , global::System.Collections.Generic.IEnumerator<$typemap(cstype, T)> + { + private $csclassname collectionRef; + private int currentIndex; + private object currentObject; + private int currentSize; + + public $csclassnameEnumerator($csclassname collection) { + collectionRef = collection; + currentIndex = -1; + currentObject = null; + currentSize = collectionRef.Count; + } + + // Type-safe iterator Current + public $typemap(cstype, T) Current { + get { + if (currentIndex == -1) + throw new global::System.InvalidOperationException("Enumeration not started."); + if (currentIndex > currentSize - 1) + throw new global::System.InvalidOperationException("Enumeration finished."); + if (currentObject == null) + throw new global::System.InvalidOperationException("Collection modified."); + return ($typemap(cstype, T))currentObject; + } + } + + // Type-unsafe IEnumerator.Current + object global::System.Collections.IEnumerator.Current { + get { + return Current; + } + } + + public bool MoveNext() { + int size = collectionRef.Count; + bool moveOkay = (currentIndex+1 < size) && (size == currentSize); + if (moveOkay) { + currentIndex++; + currentObject = collectionRef[currentIndex]; + } else { + currentObject = null; + } + return moveOkay; + } + + public void Reset() { + currentIndex = -1; + currentObject = null; + if (collectionRef.Count != currentSize) { + throw new global::System.InvalidOperationException("Collection modified."); + } + } + + public void Dispose() { + currentIndex = -1; + currentObject = null; + } + } +%} + + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + + array(); + array(const array &other); + + size_type size() const; + bool empty() const; + + %rename(Fill) fill; + void fill(const value_type& val); + + %rename(Swap) swap; + void swap(array& other); + + %extend { + T getitemcopy(int index) throw (std::out_of_range) { + if (index>=0 && index<(int)$self->size()) + return (*$self)[index]; + else + throw std::out_of_range("index"); + } + const_reference getitem(int index) throw (std::out_of_range) { + if (index>=0 && index<(int)$self->size()) + return (*$self)[index]; + else + throw std::out_of_range("index"); + } + void setitem(int index, const_reference val) throw (std::out_of_range) { + if (index>=0 && index<(int)$self->size()) + (*$self)[index] = val; + else + throw std::out_of_range("index"); + } + void Reverse() { + std::reverse($self->begin(), $self->end()); + } + void Reverse(int index, int count) throw (std::out_of_range, std::invalid_argument) { + if (index < 0) + throw std::out_of_range("index"); + if (count < 0) + throw std::out_of_range("count"); + if (index >= (int)$self->size()+1 || index+count > (int)$self->size()) + throw std::invalid_argument("invalid range"); + std::reverse($self->begin()+index, $self->begin()+index+count); + } + } +%enddef + + +%csmethodmodifiers std::array::empty "private" +%csmethodmodifiers std::array::getitemcopy "private" +%csmethodmodifiers std::array::getitem "private" +%csmethodmodifiers std::array::setitem "private" +%csmethodmodifiers std::array::size "private" + +namespace std { + template class array { + SWIG_STD_ARRAY_INTERNAL(T, N) + }; +} diff --git a/Lib/csharp/std_except.i b/Lib/csharp/std_except.i index 27eb84bc2..c983bd0f6 100644 --- a/Lib/csharp/std_except.i +++ b/Lib/csharp/std_except.i @@ -7,6 +7,7 @@ * ----------------------------------------------------------------------------- */ %{ +#include #include %} @@ -16,6 +17,7 @@ namespace std struct exception {}; } +%typemap(throws, canthrow=1) std::bad_cast "SWIG_CSharpSetPendingException(SWIG_CSharpInvalidCastException, $1.what());\n return $null;" %typemap(throws, canthrow=1) std::bad_exception "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;" %typemap(throws, canthrow=1) std::domain_error "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;" %typemap(throws, canthrow=1) std::exception "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;" diff --git a/Lib/csharp/std_vector.i b/Lib/csharp/std_vector.i index 467a2ade8..fad729dff 100644 --- a/Lib/csharp/std_vector.i +++ b/Lib/csharp/std_vector.i @@ -398,4 +398,5 @@ SWIG_STD_VECTOR_ENHANCED(unsigned long long) SWIG_STD_VECTOR_ENHANCED(float) SWIG_STD_VECTOR_ENHANCED(double) SWIG_STD_VECTOR_ENHANCED(std::string) // also requires a %include +SWIG_STD_VECTOR_ENHANCED(std::wstring) // also requires a %include diff --git a/Lib/csharp/swiginterface.i b/Lib/csharp/swiginterface.i new file mode 100644 index 000000000..e5bfd23a4 --- /dev/null +++ b/Lib/csharp/swiginterface.i @@ -0,0 +1,63 @@ +/* ----------------------------------------------------------------------------- + * swiginterface.i + * + * SWIG interface feature and typemaps implementation providing: + * %interface + * %interface_impl + * %interface_custom + * ----------------------------------------------------------------------------- */ + +%define INTERFACE_TYPEMAPS(CTYPE...) +%typemap(cstype) CTYPE "$&csinterfacename" +%typemap(cstype) CTYPE *, CTYPE [], CTYPE & "$csinterfacename" +%typemap(cstype) CTYPE *const& "$*csinterfacename" +%typemap(csin) CTYPE, CTYPE & "$csinput.GetInterfaceCPtr()" +%typemap(csin) CTYPE *, CTYPE *const&, CTYPE [] "$csinput == null ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : $csinput.GetInterfaceCPtr()" +%typemap(csout, excode=SWIGEXCODE) CTYPE { + $&csclassname ret = new $&csclassname($imcall, true);$excode + return ($&csinterfacename)ret; + } +%typemap(csout, excode=SWIGEXCODE) CTYPE & { + $csclassname ret = new $csclassname($imcall, $owner);$excode + return ($csinterfacename)ret; + } +%typemap(csout, excode=SWIGEXCODE) CTYPE *, CTYPE [] { + global::System.IntPtr cPtr = $imcall; + $csclassname ret = (cPtr == global::System.IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode + return ($csinterfacename)ret; + } +%typemap(csout, excode=SWIGEXCODE) CTYPE *const& { + global::System.IntPtr cPtr = $imcall; + $*csclassname ret = (cPtr == global::System.IntPtr.Zero) ? null : new $*csclassname(cPtr, $owner);$excode + return ($*csinterfacename)ret; + } +%typemap(csdirectorin) CTYPE "($&csinterfacename)new $&csclassname($iminput, true)" +%typemap(csdirectorin) CTYPE & "($csinterfacename)new $csclassname($iminput, false)" +%typemap(csdirectorin) CTYPE *, CTYPE [] "($iminput == global::System.IntPtr.Zero) ? null : ($csinterfacename)new $csclassname($iminput, false)" +%typemap(csdirectorin) CTYPE *const& "($iminput == global::System.IntPtr.Zero) ? null : ($*csinterfacename)new $*csclassname($iminput, false)" +%typemap(csdirectorout) CTYPE, CTYPE *, CTYPE *const&, CTYPE [], CTYPE & "$cscall.GetInterfaceCPtr()" +%typemap(csinterfacecode, declaration=" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n global::System.Runtime.InteropServices.HandleRef GetInterfaceCPtr();\n", cptrmethod="$interfacename_GetInterfaceCPtr") CTYPE %{ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + global::System.Runtime.InteropServices.HandleRef $interfacename.GetInterfaceCPtr() { + return new global::System.Runtime.InteropServices.HandleRef(this, $imclassname.$csclazzname$interfacename_GetInterfaceCPtr(swigCPtr.Handle)); + } +%} +%enddef + +%define %interface(CTYPE...) +%feature("interface", name="%sSwigInterface") CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef + +%define %interface_impl(CTYPE...) +%rename("%sSwigImpl") CTYPE; +%feature("interface", name="%(rstrip:[SwigImpl])s") CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef + +%define %interface_custom(PROXY, INTERFACE, CTYPE...) +%rename(PROXY) CTYPE; +%feature("interface", name=INTERFACE) CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef + diff --git a/Lib/d/carrays.i b/Lib/d/carrays.i index 37b59c871..f2803ea46 100644 --- a/Lib/d/carrays.i +++ b/Lib/d/carrays.i @@ -21,7 +21,7 @@ %{ static TYPE *new_##NAME(int nelements) { %} #ifdef __cplusplus -%{ return new TYPE[nelements]; %} +%{ return new TYPE[nelements](); %} #else %{ return (TYPE *) calloc(nelements,sizeof(TYPE)); %} #endif @@ -78,7 +78,7 @@ typedef struct {} NAME; %extend NAME { #ifdef __cplusplus NAME(int nelements) { - return new TYPE[nelements]; + return new TYPE[nelements](); } ~NAME() { delete [] self; diff --git a/Lib/d/dswigtype.swg b/Lib/d/dswigtype.swg index 41336dc91..f91d6dfe6 100644 --- a/Lib/d/dswigtype.swg +++ b/Lib/d/dswigtype.swg @@ -57,7 +57,7 @@ #endif %typemap(directorin) SWIGTYPE - "$input = (void *)&$1;" + "$input = (void *)new $1_ltype((const $1_ltype &)$1);" %typemap(directorout) SWIGTYPE %{ if (!$input) { SWIG_DSetPendingException(SWIG_DIllegalArgumentException, "Unexpected null return for type $1_type"); @@ -65,7 +65,7 @@ } $result = *($&1_ltype)$input; %} -%typemap(ddirectorin) SWIGTYPE "new $&dclassname($winput, false)" +%typemap(ddirectorin) SWIGTYPE "new $&dclassname($winput, true)" %typemap(ddirectorout) SWIGTYPE "$&dclassname.swigGetCPtr($dcall)" %typemap(din) SWIGTYPE "$&dclassname.swigGetCPtr($dinput)" diff --git a/Lib/d/std_except.i b/Lib/d/std_except.i index 2b557e5fc..fbfd6c337 100644 --- a/Lib/d/std_except.i +++ b/Lib/d/std_except.i @@ -7,6 +7,7 @@ * ----------------------------------------------------------------------------- */ %{ +#include #include %} @@ -16,6 +17,7 @@ namespace std struct exception {}; } +%typemap(throws, canthrow=1) std::bad_cast "SWIG_DSetPendingException(SWIG_DException, $1.what());\n return $null;" %typemap(throws, canthrow=1) std::bad_exception "SWIG_DSetPendingException(SWIG_DException, $1.what());\n return $null;" %typemap(throws, canthrow=1) std::domain_error "SWIG_DSetPendingException(SWIG_DException, $1.what());\n return $null;" %typemap(throws, canthrow=1) std::exception "SWIG_DSetPendingException(SWIG_DException, $1.what());\n return $null;" diff --git a/Lib/exception.i b/Lib/exception.i index 437eee6f0..da0d56cdd 100644 --- a/Lib/exception.i +++ b/Lib/exception.i @@ -12,10 +12,17 @@ %insert("runtime") "swigerrors.swg" -#ifdef SWIGPHP +#ifdef SWIGPHP5 %{ #include "zend_exceptions.h" -#define SWIG_exception(code, msg) zend_throw_exception(NULL, (char*)msg, code TSRMLS_CC) +#define SWIG_exception(code, msg) do { zend_throw_exception(NULL, (char*)msg, code TSRMLS_CC); goto thrown; } while (0) +%} +#endif + +#ifdef SWIGPHP7 +%{ +#include "zend_exceptions.h" +#define SWIG_exception(code, msg) do { zend_throw_exception(NULL, (char*)msg, code); goto thrown; } while (0) %} #endif @@ -258,6 +265,7 @@ SWIGINTERN void SWIG_DThrowException(int code, const char *msg) { } */ %{ +#include #include %} %define SWIG_CATCH_STDEXCEPT @@ -274,6 +282,8 @@ SWIGINTERN void SWIG_DThrowException(int code, const char *msg) { SWIG_exception(SWIG_IndexError, e.what() ); } catch (std::runtime_error& e) { SWIG_exception(SWIG_RuntimeError, e.what() ); + } catch (std::bad_cast& e) { + SWIG_exception(SWIG_TypeError, e.what() ); } catch (std::exception& e) { SWIG_exception(SWIG_SystemError, e.what() ); } diff --git a/Lib/go/go.swg b/Lib/go/go.swg index 35f914c5b..53b653f7c 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -426,10 +426,7 @@ /* Strings. */ %typemap(gotype) - char *, char *&, char[ANY], char[], - signed char *, signed char *&, signed char[ANY], signed char[], - unsigned char *, unsigned char *&, unsigned char[ANY], unsigned char[] -"string" + char *, char *&, char[ANY], char[] "string" /* Needed to avoid confusion with the way the go module handles references. */ @@ -437,46 +434,59 @@ %typemap(gotype) signed char& "*int8" %typemap(in) - char *, char[ANY], char[], - signed char *, signed char[ANY], signed char[], - unsigned char *, unsigned char[ANY], unsigned char[] -%{ $1 = ($1_ltype)$input.p; %} + char *, char[ANY], char[] +%{ + $1 = ($1_ltype)malloc($input.n + 1); + memcpy($1, $input.p, $input.n); + $1[$input.n] = '\0'; +%} -%typemap(in) char *&, signed char *&, unsigned char *& -%{ $1 = ($1_ltype)$input.p; %} +%typemap(in) char *& (char *temp) +%{ + temp = (char *)malloc($input.n + 1); + memcpy(temp, $input.p, $input.n); + temp[$input.n] = '\0'; + $1 = ($1_ltype)&temp; +%} + +%typemap(freearg) + char *, char *&, char[ANY], char[] +%{ free($1); %} %typemap(out,fragment="AllocateString") - char *, char *&, char[ANY], char[], - signed char *, signed char *&, signed char[ANY], signed char[], - unsigned char *, unsigned char *&, unsigned char[ANY], unsigned char[] + char *, char *&, char[ANY], char[] %{ $result = Swig_AllocateString((char*)$1, $1 ? strlen((char*)$1) : 0); %} %typemap(goout,fragment="CopyString") - char *, char *&, char[ANY], char[], - signed char *, signed char *&, signed char[ANY], signed char[], - unsigned char *, unsigned char *&, unsigned char[ANY], unsigned char[] + char *, char *&, char[ANY], char[] %{ $result = swigCopyString($1) %} %typemap(directorin,fragment="AllocateString") - char *, char *&, char[ANY], char[], - signed char *, signed char *&, signed char[ANY], signed char[], - unsigned char *, unsigned char *&, unsigned char[ANY], unsigned char[] + char *, char *&, char[ANY], char[] %{ $input = Swig_AllocateString((char*)$1, $1 ? strlen((char*)$1) : 0); %} %typemap(godirectorin,fragment="CopyString") - char *, char *&, char[ANY], char[], - signed char *, signed char *&, signed char[ANY], signed char[], - unsigned char *, unsigned char *&, unsigned char[ANY], unsigned char[] + char *, char *&, char[ANY], char[] %{ $result = swigCopyString($input) %} -%typemap(directorout) - char *, char *&, char[ANY], char[], - signed char *, signed char *&, signed char[ANY], signed char[], - unsigned char *, unsigned char *&, unsigned char[ANY], unsigned char[] +%typemap(godirectorout) + char *, char *&, char[ANY], char[] +%{ + { + p := Swig_malloc(len($input) + 1) + s := (*[1<<30]byte)(unsafe.Pointer(p))[:len($input) + 1] + copy(s, $input) + s[len($input)] = 0 + $result = *(*string)(unsafe.Pointer(&s)) + } +%} + +%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) + char *, char *&, char[ANY], char[] %{ $result = ($1_ltype)$input.p; %} /* String & length */ @@ -574,7 +584,7 @@ %typemap(goout) SWIGTYPE "" %typemap(directorin) SWIGTYPE -%{ $input = ($&1_ltype)&$1; %} +%{ $input = new $1_ltype((const $1_ltype &)$1); %} %typemap(godirectorin) SWIGTYPE "" diff --git a/Lib/go/goruntime.swg b/Lib/go/goruntime.swg index 031a7f6f0..dc6193d04 100644 --- a/Lib/go/goruntime.swg +++ b/Lib/go/goruntime.swg @@ -8,6 +8,10 @@ static void Swig_free(void* p) { free(p); } + +static void* Swig_malloc(int c) { + return malloc(c); +} %} %insert(runtime) %{ @@ -60,6 +64,24 @@ typedef size_t uintgo; #endif #endif +#ifndef SWIGGO_GCCGO +// Set the host compiler struct attribute that will be +// used to match gc's struct layout. For example, on 386 Windows, +// gcc wants to 8-align int64s, but gc does not. +// Use __gcc_struct__ to work around http://gcc.gnu.org/PR52991 on x86, +// and https://golang.org/issue/5603. +// See: https://github.com/golang/go/blob/fcbf04f9b93b4cd8addd05c2ed784118eb50a46c/src/cmd/cgo/out.go#L663 +%insert(runtime) %{ +# if !defined(__clang__) && (defined(__i386__) || defined(__x86_64__)) +# define SWIGSTRUCTPACKED __attribute__((__packed__, __gcc_struct__)) +# else +# define SWIGSTRUCTPACKED __attribute__((__packed__)) +# endif +%} +#else +# define SWIGSTRUCTPACKED +#endif + %insert(runtime) %{ typedef struct { char *p; intgo n; } _gostring_; @@ -116,7 +138,7 @@ static char *_swig_topofstack() { static void _swig_gopanic(const char *p) { struct { const char *p; - } a; + } SWIGSTRUCTPACKED a; a.p = p; crosscall2(_cgo_panic, &a, (int) sizeof a); } @@ -133,7 +155,7 @@ static void *_swig_goallocate(size_t len) { struct { size_t len; void *ret; - } a; + } SWIGSTRUCTPACKED a; a.len = len; crosscall2(_cgo_allocate, &a, (int) sizeof a); return a.ret; diff --git a/Lib/go/std_except.i b/Lib/go/std_except.i index 789a335f7..4f021a126 100644 --- a/Lib/go/std_except.i +++ b/Lib/go/std_except.i @@ -7,6 +7,7 @@ * ----------------------------------------------------------------------------- */ %{ +#include #include %} @@ -16,6 +17,7 @@ namespace std struct exception {}; } +%typemap(throws) std::bad_cast %{_swig_gopanic($1.what());%} %typemap(throws) std::bad_exception %{_swig_gopanic($1.what());%} %typemap(throws) std::domain_error %{_swig_gopanic($1.what());%} %typemap(throws) std::exception %{_swig_gopanic($1.what());%} diff --git a/Lib/go/std_string.i b/Lib/go/std_string.i index 068c688cb..099ae84d4 100644 --- a/Lib/go/std_string.i +++ b/Lib/go/std_string.i @@ -24,8 +24,21 @@ class string; %typemap(in) string %{ $1.assign($input.p, $input.n); %} +%typemap(godirectorout) string +%{ + { + p := Swig_malloc(len($input)) + s := (*[1<<30]byte)(unsafe.Pointer(p))[:len($input)] + copy(s, $input) + $result = *(*string)(unsafe.Pointer(&s)) + } +%} + %typemap(directorout) string -%{ $result.assign($input.p, $input.n); %} +%{ + $result.assign($input.p, $input.n); + free($input.p); +%} %typemap(out,fragment="AllocateString") string %{ $result = Swig_AllocateString($1.data(), $1.length()); %} @@ -45,10 +58,21 @@ class string; $1 = &$1_str; %} +%typemap(godirectorout) const string & +%{ + { + p := Swig_malloc(len($input)) + s := (*[1<<30]byte)(unsafe.Pointer(p))[:len($input)] + copy(s, $input) + $result = *(*string)(unsafe.Pointer(&s)) + } +%} + %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const string & %{ static $*1_ltype $1_str; $1_str.assign($input.p, $input.n); + free($input.p); $result = &$1_str; %} diff --git a/Lib/guile/std_except.i b/Lib/guile/std_except.i index 61bf481a3..6c30a319f 100644 --- a/Lib/guile/std_except.i +++ b/Lib/guile/std_except.i @@ -1,6 +1,7 @@ // TODO: STL exception handling // Note that the generic std_except.i file did not work %{ +#include #include %} diff --git a/Lib/guile/std_map.i b/Lib/guile/std_map.i index 1e1014f54..489acc187 100644 --- a/Lib/guile/std_map.i +++ b/Lib/guile/std_map.i @@ -41,11 +41,11 @@ namespace std { template class map { - %typemap(in) map (std::map* m) { + %typemap(in) map { if (scm_is_null($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); } else if (scm_is_pair($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); SCM alist = $input; while (!scm_is_null(alist)) { K* k; @@ -72,15 +72,13 @@ namespace std { SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0)); } } - %typemap(in) const map& (std::map temp, - std::map* m), - const map* (std::map temp, - std::map* m) { + %typemap(in) const map& (std::map temp), + const map* (std::map temp) { if (scm_is_null($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; } else if (scm_is_pair($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; SCM alist = $input; while (!scm_is_null(alist)) { @@ -109,8 +107,7 @@ namespace std { } %typemap(out) map { SCM alist = SCM_EOL; - for (std::map::reverse_iterator i=$i.rbegin(); - i!=$i.rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=$i.rbegin(); i!=$i.rend(); ++i) { K* key = new K(i->first); T* val = new T(i->second); SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1); @@ -156,7 +153,7 @@ namespace std { } } else { /* wrapped map? */ - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -201,7 +198,7 @@ namespace std { } } else { /* wrapped map? */ - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -222,14 +219,14 @@ namespace std { typedef K key_type; typedef T mapped_type; map(); - map(const map &); + map(const map< K, T> &); unsigned int size() const; bool empty() const; void clear(); %extend { const T& __getitem__(const K& key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) return i->second; else @@ -239,20 +236,19 @@ namespace std { (*self)[key] = x; } void __delitem__(const K& key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) self->erase(i); else throw std::out_of_range("key not found"); } bool has_key(const K& key) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); return i != self->end(); } SCM keys() { SCM result = SCM_EOL; - for (std::map::reverse_iterator i=self->rbegin(); - i!=self->rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=self->rbegin(); i!=self->rend(); ++i) { K* key = new K(i->first); SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1); result = scm_cons(k,result); @@ -268,11 +264,11 @@ namespace std { %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO) template class map { - %typemap(in) map (std::map* m) { + %typemap(in) map { if (scm_is_null($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); } else if (scm_is_pair($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); SCM alist = $input; while (!scm_is_null(alist)) { T* x; @@ -300,15 +296,13 @@ namespace std { SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0)); } } - %typemap(in) const map& (std::map temp, - std::map* m), - const map* (std::map temp, - std::map* m) { + %typemap(in) const map& (std::map temp), + const map* (std::map temp) { if (scm_is_null($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; } else if (scm_is_pair($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; SCM alist = $input; while (!scm_is_null(alist)) { @@ -338,8 +332,7 @@ namespace std { } %typemap(out) map { SCM alist = SCM_EOL; - for (std::map::reverse_iterator i=$1.rbegin(); - i!=$1.rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=$1.rbegin(); i!=$1.rend(); ++i) { T* val = new T(i->second); SCM k = CONVERT_TO(i->first); SCM x = SWIG_NewPointerObj(val,$descriptor(T *), 1); @@ -382,7 +375,7 @@ namespace std { } } else { // wrapped map? - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -425,7 +418,7 @@ namespace std { } } else { // wrapped map? - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -442,14 +435,14 @@ namespace std { %rename("has-key?") has_key; public: map(); - map(const map &); + map(const map< K, T > &); unsigned int size() const; bool empty() const; void clear(); %extend { T& __getitem__(K key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) return i->second; else @@ -459,20 +452,19 @@ namespace std { (*self)[key] = x; } void __delitem__(K key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) self->erase(i); else throw std::out_of_range("key not found"); } bool has_key(K key) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); return i != self->end(); } SCM keys() { SCM result = SCM_EOL; - for (std::map::reverse_iterator i=self->rbegin(); - i!=self->rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=self->rbegin(); i!=self->rend(); ++i) { SCM k = CONVERT_TO(i->first); result = scm_cons(k,result); } @@ -484,11 +476,11 @@ namespace std { %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO) template class map { - %typemap(in) map (std::map* m) { + %typemap(in) map { if (scm_is_null($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); } else if (scm_is_pair($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); SCM alist = $input; while (!scm_is_null(alist)) { K* k; @@ -515,15 +507,13 @@ namespace std { SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0)); } } - %typemap(in) const map& (std::map temp, - std::map* m), - const map* (std::map temp, - std::map* m) { + %typemap(in) const map& (std::map temp), + const map* (std::map temp) { if (scm_is_null($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; } else if (scm_is_pair($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; SCM alist = $input; while (!scm_is_null(alist)) { @@ -552,8 +542,7 @@ namespace std { } %typemap(out) map { SCM alist = SCM_EOL; - for (std::map::reverse_iterator i=$1.rbegin(); - i!=$1.rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=$1.rbegin(); i!=$1.rend(); ++i) { K* key = new K(i->first); SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1); SCM x = CONVERT_TO(i->second); @@ -572,7 +561,6 @@ namespace std { K* k; SCM head = SCM_CAR($input); if (scm_is_pair(head)) { - SCM key = SCM_CAR(head); SCM val = SCM_CDR(head); if (SWIG_ConvertPtr(val,(void **) &k, $descriptor(K *), 0) != 0) { @@ -595,7 +583,7 @@ namespace std { } } else { // wrapped map? - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -614,7 +602,6 @@ namespace std { K* k; SCM head = SCM_CAR($input); if (scm_is_pair(head)) { - SCM key = SCM_CAR(head); SCM val = SCM_CDR(head); if (SWIG_ConvertPtr(val,(void **) &k, $descriptor(K *), 0) != 0) { @@ -637,7 +624,7 @@ namespace std { } } else { // wrapped map? - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -654,14 +641,14 @@ namespace std { %rename("has-key?") has_key; public: map(); - map(const map &); + map(const map< K, T > &); unsigned int size() const; bool empty() const; void clear(); %extend { T __getitem__(const K& key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) return i->second; else @@ -671,20 +658,19 @@ namespace std { (*self)[key] = x; } void __delitem__(const K& key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) self->erase(i); else throw std::out_of_range("key not found"); } bool has_key(const K& key) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); return i != self->end(); } SCM keys() { SCM result = SCM_EOL; - for (std::map::reverse_iterator i=self->rbegin(); - i!=self->rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=self->rbegin(); i!=self->rend(); ++i) { K* key = new K(i->first); SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1); result = scm_cons(k,result); @@ -698,11 +684,11 @@ namespace std { %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO, T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO) template<> class map { - %typemap(in) map (std::map* m) { + %typemap(in) map { if (scm_is_null($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); } else if (scm_is_pair($input)) { - $1 = std::map(); + $1 = std::map< K, T >(); SCM alist = $input; while (!scm_is_null(alist)) { SCM entry, key, val; @@ -731,15 +717,13 @@ namespace std { SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0)); } } - %typemap(in) const map& (std::map temp, - std::map* m), - const map* (std::map temp, - std::map* m) { + %typemap(in) const map& (std::map temp), + const map* (std::map temp) { if (scm_is_null($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; } else if (scm_is_pair($input)) { - temp = std::map(); + temp = std::map< K, T >(); $1 = &temp; SCM alist = $input; while (!scm_is_null(alist)) { @@ -769,8 +753,7 @@ namespace std { } %typemap(out) map { SCM alist = SCM_EOL; - for (std::map::reverse_iterator i=$1.rbegin(); - i!=$1.rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=$1.rbegin(); i!=$1.rend(); ++i) { SCM k = CONVERT_K_TO(i->first); SCM x = CONVERT_T_TO(i->second); SCM entry = scm_cons(k,x); @@ -809,7 +792,7 @@ namespace std { } } else { // wrapped map? - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -849,7 +832,7 @@ namespace std { } } else { // wrapped map? - std::map* m; + std::map< K, T >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -866,14 +849,14 @@ namespace std { %rename("has-key?") has_key; public: map(); - map(const map &); + map(const map< K, T> &); unsigned int size() const; bool empty() const; void clear(); %extend { T __getitem__(K key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) return i->second; else @@ -883,20 +866,19 @@ namespace std { (*self)[key] = x; } void __delitem__(K key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) self->erase(i); else throw std::out_of_range("key not found"); } bool has_key(K key) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); return i != self->end(); } SCM keys() { SCM result = SCM_EOL; - for (std::map::reverse_iterator i=self->rbegin(); - i!=self->rend(); ++i) { + for (std::map< K, T >::reverse_iterator i=self->rbegin(); i!=self->rend(); ++i) { SCM k = CONVERT_K_TO(i->first); result = scm_cons(k,result); } diff --git a/Lib/guile/std_pair.i b/Lib/guile/std_pair.i index 512d0d555..92dec5fae 100644 --- a/Lib/guile/std_pair.i +++ b/Lib/guile/std_pair.i @@ -79,7 +79,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -105,7 +105,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -183,7 +183,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -207,7 +207,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -283,7 +283,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -307,7 +307,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; @@ -377,7 +377,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $&1_descriptor, 0) == 0) $1 = 1; @@ -398,7 +398,7 @@ namespace std { } } else { /* wrapped pair? */ - std::pair* m; + std::pair< T, U >* m; if (SWIG_ConvertPtr($input,(void **) &m, $1_descriptor, 0) == 0) $1 = 1; diff --git a/Lib/guile/std_vector.i b/Lib/guile/std_vector.i index 1c55239c1..d7a7140c6 100644 --- a/Lib/guile/std_vector.i +++ b/Lib/guile/std_vector.i @@ -44,17 +44,17 @@ namespace std { %typemap(in) vector { if (scm_is_vector($input)) { unsigned long size = scm_c_vector_length($input); - $1 = std::vector(size); + $1 = std::vector< T >(size); for (unsigned long i=0; i(); + $1 = std::vector< T >(); } else if (scm_is_pair($input)) { SCM head, tail; - $1 = std::vector(); + $1 = std::vector< T >(); tail = $input; while (!scm_is_null(tail)) { head = SCM_CAR(tail); @@ -72,7 +72,7 @@ namespace std { const vector* (std::vector temp) { if (scm_is_vector($input)) { unsigned long size = scm_c_vector_length($input); - temp = std::vector(size); + temp = std::vector< T >(size); $1 = &temp; for (unsigned long i=0; i(); + temp = std::vector< T >(); $1 = &temp; } else if (scm_is_pair($input)) { - temp = std::vector(); + temp = std::vector< T >(); $1 = &temp; SCM head, tail; tail = $input; @@ -138,7 +138,7 @@ namespace std { $1 = 0; } else { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor, 0) != -1) $1 = 1; @@ -178,7 +178,7 @@ namespace std { $1 = 0; } else { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_descriptor, 0) != -1) $1 = 1; @@ -232,7 +232,7 @@ namespace std { %typemap(in) vector { if (scm_is_vector($input)) { unsigned long size = scm_c_vector_length($input); - $1 = std::vector(size); + $1 = std::vector< T >(size); for (unsigned long i=0; i(size); + $1 = std::vector< T >(size); for (unsigned long i=0; i* (std::vector temp) { if (scm_is_vector($input)) { unsigned long size = scm_c_vector_length($input); - temp = std::vector(size); + temp = std::vector< T >(size); $1 = &temp; for (unsigned long i=0; i(); + temp = std::vector< T >(); $1 = &temp; } else if (scm_is_pair($input)) { SCM v = scm_vector($input); unsigned long size = scm_c_vector_length(v); - temp = std::vector(size); + temp = std::vector< T >(size); $1 = &temp; for (unsigned long i=0; i* v; + std::vector< T >* v; $1 = (SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor, 0) != -1) ? 1 : 0; } @@ -345,7 +345,7 @@ namespace std { $1 = CHECK(head) ? 1 : 0; } else { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; $1 = (SWIG_ConvertPtr($input,(void **) &v, $1_descriptor, 0) != -1) ? 1 : 0; } diff --git a/Lib/java/arrays_java.i b/Lib/java/arrays_java.i index 4b780aef9..402f088d5 100644 --- a/Lib/java/arrays_java.i +++ b/Lib/java/arrays_java.i @@ -52,7 +52,7 @@ static int SWIG_JavaArrayIn##JFUNCNAME (JNIEnv *jenv, JNITYPE **jarr, CTYPE **ca #ifdef __cplusplus %{ *carr = new CTYPE[sz]; %} #else -%{ *carr = (CTYPE*) calloc(sz, sizeof(CTYPE)); %} +%{ *carr = (CTYPE*) malloc(sz * sizeof(CTYPE)); %} #endif %{ if (!*carr) { SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed"); @@ -259,7 +259,7 @@ JAVA_ARRAYS_TYPEMAPS(double, double, jdouble, Double, "[D") /* double[ANY] * #ifdef __cplusplus $1 = new $*1_ltype[sz]; #else - $1 = ($1_ltype) calloc(sz, sizeof($*1_ltype)); + $1 = ($1_ltype) malloc(sz * sizeof($*1_ltype)); #endif if (!$1) { SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed"); @@ -289,7 +289,7 @@ JAVA_ARRAYS_TYPEMAPS(double, double, jdouble, Double, "[D") /* double[ANY] * #ifdef __cplusplus $1 = new $*1_ltype[sz]; #else - $1 = ($1_ltype) calloc(sz, sizeof($*1_ltype)); + $1 = ($1_ltype) malloc(sz * sizeof($*1_ltype)); #endif if (!$1) { SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed"); diff --git a/Lib/java/boost_intrusive_ptr.i b/Lib/java/boost_intrusive_ptr.i index f9525894f..a484a3b6c 100644 --- a/Lib/java/boost_intrusive_ptr.i +++ b/Lib/java/boost_intrusive_ptr.i @@ -263,8 +263,8 @@ // Base proxy classes %typemap(javabody) TYPE %{ - private long swigCPtr; - private boolean swigCMemOwnBase; + private transient long swigCPtr; + private transient boolean swigCMemOwnBase; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwnBase = cMemoryOwn; @@ -278,8 +278,8 @@ // Derived proxy classes %typemap(javabody_derived) TYPE %{ - private long swigCPtr; - private boolean swigCMemOwnDerived; + private transient long swigCPtr; + private transient boolean swigCMemOwnDerived; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { super($imclassname.$javaclazznameSWIGSmartPtrUpcast(cPtr), true); @@ -413,8 +413,8 @@ // Base proxy classes %typemap(javabody) TYPE %{ - private long swigCPtr; - private boolean swigCMemOwnBase; + private transient long swigCPtr; + private transient boolean swigCMemOwnBase; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwnBase = cMemoryOwn; @@ -428,8 +428,8 @@ // Derived proxy classes %typemap(javabody_derived) TYPE %{ - private long swigCPtr; - private boolean swigCMemOwnDerived; + private transient long swigCPtr; + private transient boolean swigCMemOwnDerived; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { super($imclassname.$javaclazznameSWIGSmartPtrUpcast(cPtr), true); diff --git a/Lib/java/boost_shared_ptr.i b/Lib/java/boost_shared_ptr.i index e75236993..5ed16aa32 100644 --- a/Lib/java/boost_shared_ptr.i +++ b/Lib/java/boost_shared_ptr.i @@ -145,8 +145,8 @@ // Base proxy classes %typemap(javabody) TYPE %{ - private long swigCPtr; - private boolean swigCMemOwn; + private transient long swigCPtr; + private transient boolean swigCMemOwn; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; @@ -160,8 +160,8 @@ // Derived proxy classes %typemap(javabody_derived) TYPE %{ - private long swigCPtr; - private boolean swigCMemOwnDerived; + private transient long swigCPtr; + private transient boolean swigCMemOwnDerived; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { super($imclassname.$javaclazznameSWIGSmartPtrUpcast(cPtr), true); diff --git a/Lib/java/java.swg b/Lib/java/java.swg index 22a4884ef..f1227d0ad 100644 --- a/Lib/java/java.swg +++ b/Lib/java/java.swg @@ -310,8 +310,11 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { bae = JCALL2(GetByteArrayElements, jenv, ba, 0); sz = JCALL1(GetArrayLength, jenv, ba); $1 = 0; - for(i=0; i 0) { + $1 = ($1_type)(signed char)bae[0]; + for(i=1; i 0) { + $result = ($1_type)(signed char)bae[0]; + for(i=1; i 0) { + temp = ($*1_ltype)(signed char)bae[0]; + for(i=1; i 0) { + temp = ($*1_ltype)(signed char)bae[0]; + for(i=1; i + +namespace std { + + template class array { + public: + typedef T& reference; + typedef const T& const_reference; + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T value_type; + typedef T* pointer; + typedef const T* const_pointer; + array(); + array(const array& other); + size_type size() const; + %rename(isEmpty) empty; + bool empty() const; + void fill(const T& u); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i #include %} @@ -16,6 +17,7 @@ namespace std struct exception {}; } +%typemap(throws) std::bad_cast "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;" %typemap(throws) std::bad_exception "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;" %typemap(throws) std::domain_error "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;" %typemap(throws) std::exception "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;" diff --git a/Lib/java/std_wstring.i b/Lib/java/std_wstring.i index 12d8fc14f..dd0b2f5ff 100644 --- a/Lib/java/std_wstring.i +++ b/Lib/java/std_wstring.i @@ -59,15 +59,16 @@ class wstring; jenv->ReleaseStringChars($input, $1_pstr); %} -%typemap(directorin,descriptor="Ljava/lang/String;") wstring { +%typemap(directorin,descriptor="Ljava/lang/String;") wstring %{ jsize $1_len = $1.length(); - jchar *conv_buf = new jchar[$1_len]; + jchar *$1_conv_buf = new jchar[$1_len]; for (jsize i = 0; i < $1_len; ++i) { - conv_buf[i] = (jchar)$1[i]; + $1_conv_buf[i] = (jchar)$1[i]; } - $input = jenv->NewString(conv_buf, $1_len); - delete [] conv_buf; -} + $input = jenv->NewString($1_conv_buf, $1_len); + Swig::LocalRefGuard $1_refguard(jenv, $input); + delete [] $1_conv_buf; +%} %typemap(out) wstring %{jsize $1_len = $1.length(); @@ -136,15 +137,16 @@ class wstring; $result = &$1_str; jenv->ReleaseStringChars($input, $1_pstr); %} -%typemap(directorin,descriptor="Ljava/lang/String;") const wstring & { +%typemap(directorin,descriptor="Ljava/lang/String;") const wstring & %{ jsize $1_len = $1.length(); - jchar *conv_buf = new jchar[$1_len]; + jchar *$1_conv_buf = new jchar[$1_len]; for (jsize i = 0; i < $1_len; ++i) { - conv_buf[i] = (jchar)($1)[i]; + $1_conv_buf[i] = (jchar)($1)[i]; } - $input = jenv->NewString(conv_buf, $1_len); - delete [] conv_buf; -} + $input = jenv->NewString($1_conv_buf, $1_len); + Swig::LocalRefGuard $1_refguard(jenv, $input); + delete [] $1_conv_buf; +%} %typemap(out) const wstring & %{jsize $1_len = $1->length(); diff --git a/Lib/java/swiginterface.i b/Lib/java/swiginterface.i new file mode 100644 index 000000000..334464157 --- /dev/null +++ b/Lib/java/swiginterface.i @@ -0,0 +1,74 @@ +/* ----------------------------------------------------------------------------- + * swiginterface.i + * + * SWIG interface feature and typemaps implementation providing: + * %interface + * %interface_impl + * %interface_custom + * ----------------------------------------------------------------------------- */ + +%define INTERFACE_TYPEMAPS(CTYPE...) +%typemap(jtype) CTYPE, CTYPE *, CTYPE *const&, CTYPE [], CTYPE & "long" +%typemap(jstype) CTYPE "$&javainterfacename" +%typemap(jstype) CTYPE *, CTYPE [], CTYPE & "$javainterfacename" +%typemap(jstype) CTYPE *const& "$*javainterfacename" +%typemap(javain) CTYPE "$javainput.$&interfacename_GetInterfaceCPtr()" +%typemap(javain) CTYPE & "$javainput.$interfacename_GetInterfaceCPtr()" +%typemap(javain) CTYPE *, CTYPE [] "($javainput == null) ? 0 : $javainput.$interfacename_GetInterfaceCPtr()" +%typemap(javain) CTYPE *const& "($javainput == null) ? 0 : $javainput.$*interfacename_GetInterfaceCPtr()" +%typemap(javaout) CTYPE { + return ($&javainterfacename)new $&javaclassname($jnicall, true); + } +%typemap(javaout) CTYPE & { + return ($javainterfacename)new $javaclassname($jnicall, $owner); + } +%typemap(javaout) CTYPE *, CTYPE [] { + long cPtr = $jnicall; + return (cPtr == 0) ? null : ($javainterfacename)new $javaclassname(cPtr, $owner); + } +%typemap(javaout) CTYPE *const& { + long cPtr = $jnicall; + return (cPtr == 0) ? null : ($javainterfacename)new $javaclassname(cPtr, $owner); + } + +%typemap(javadirectorin) CTYPE "($&javainterfacename)new $&javaclassname($jniinput, true)" +%typemap(javadirectorin) CTYPE & "($javainterfacename)new $javaclassname($jniinput, false)" +%typemap(javadirectorin) CTYPE *, CTYPE [] "($jniinput == 0) ? null : ($javainterfacename)new $javaclassname($jniinput, false)" +%typemap(javadirectorin) CTYPE *const& "($jniinput == 0) ? null : ($*javainterfacename)new $*javaclassname($jniinput, false)" +%typemap(javadirectorout) CTYPE "$javacall.$&interfacename_GetInterfaceCPtr()" +%typemap(javadirectorout) CTYPE *, CTYPE [], CTYPE & "$javacall.$interfacename_GetInterfaceCPtr()" +%typemap(javadirectorout) CTYPE *const& "$javacall.$*interfacename_GetInterfaceCPtr()" +%typemap(directorin,descriptor="L$packagepath/$&javainterfacename;") CTYPE +%{ $input = 0; + *(($&1_ltype*)&$input) = new $1_ltype((const $1_ltype &)$1); %} +%typemap(directorin,descriptor="L$packagepath/$javainterfacename;") CTYPE *, CTYPE [] +%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} +%typemap(directorin,descriptor="L$packagepath/$javainterfacename;") CTYPE & +%{ *($&1_ltype)&$input = ($1_ltype) &$1; %} +%typemap(directorin,descriptor="L$packagepath/$*javainterfacename;") CTYPE *const& +%{ *($&1_ltype)&$input = ($1_ltype) &$1; %} + +%typemap(javainterfacecode, declaration=" long $interfacename_GetInterfaceCPtr();\n", cptrmethod="$interfacename_GetInterfaceCPtr") CTYPE %{ + public long $interfacename_GetInterfaceCPtr() { + return $imclassname.$javaclazzname$interfacename_GetInterfaceCPtr(swigCPtr); + } +%} +%enddef + +%define %interface(CTYPE...) +%feature("interface", name="%sSwigInterface") CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef + +%define %interface_impl(CTYPE...) +%rename("%sSwigImpl") CTYPE; +%feature("interface", name="%(rstrip:[SwigImpl])s") CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef + +%define %interface_custom(PROXY, INTERFACE, CTYPE...) +%rename(PROXY) CTYPE; +%feature("interface", name=INTERFACE) CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef + diff --git a/Lib/java/typemaps.i b/Lib/java/typemaps.i index e71790bcc..041cb24e0 100644 --- a/Lib/java/typemaps.i +++ b/Lib/java/typemaps.i @@ -109,8 +109,11 @@ INPUT_TYPEMAP(double, jdouble, double, "D"); bae = JCALL2(GetByteArrayElements, jenv, ba, 0); sz = JCALL1(GetArrayLength, jenv, ba); temp = 0; - for(i=0; i 0) { + temp = ($*1_ltype)(signed char)bae[0]; + for(i=1; i 0) { + temp = ($*1_ltype)(signed char)bae[0]; + for(i=1; i LONG_MAX) ? JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); } +%#endif } %fragment(SWIG_AsVal_frag(unsigned long long),"header", fragment=SWIG_AsVal_frag(unsigned long), fragment="SWIG_CanCastAsInteger", - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(JSValueRef obj, unsigned long long *val) { @@ -158,6 +165,7 @@ SWIG_AsVal_dec(unsigned long long)(JSValueRef obj, unsigned long long *val) return SWIG_OK; } +%#endif } /* double */ diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 676a45833..30ee032ed 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -4,7 +4,7 @@ * ---------------------------------------------------------------------------*/ #define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) -#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_exception(code, msg) do { SWIG_JSC_exception(context, exception, code, msg); SWIG_fail; } while (0) #define SWIG_fail goto fail SWIGRUNTIME void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 12db9b4ab..fb7d55c2a 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -36,6 +36,7 @@ static SwigV8ReturnValue $jswrapper(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); +fail: SWIGV8_RETURN(SWIGV8_UNDEFINED()); } %} @@ -102,7 +103,7 @@ fail: %{ if(args.Length() == $jsargcount) { errorHandler.err.Clear(); -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = $jswrapper(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); @@ -124,13 +125,13 @@ fail: %fragment ("js_dtor", "templates") %{ -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void $jswrapper(v8::Isolate *isolate, v8::Persistent object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void $jswrapper(v8::Isolate *isolate, v8::Persistent *object, SWIGV8_Proxy *proxy) { #else static void $jswrapper(const v8::WeakCallbackData &data) { @@ -148,11 +149,11 @@ static void $jswrapper(const v8::WeakCallbackData &dat object.Clear(); -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); -#elif (SWIG_V8_VERSION < 0x032100) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #else object->Dispose(); @@ -168,13 +169,13 @@ static void $jswrapper(const v8::WeakCallbackData &dat * ----------------------------------------------------------------------------- */ %fragment ("js_dtoroverride", "templates") %{ -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void $jswrapper(v8::Persistent object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void $jswrapper(v8::Isolate *isolate, v8::Persistent object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #else static void $jswrapper(const v8::WeakCallbackData &data) { @@ -188,13 +189,13 @@ static void $jswrapper(const v8::WeakCallbackData &dat } delete proxy; -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); -#elif (SWIG_V8_VERSION < 0x032100) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #else object.Clear(); @@ -326,7 +327,7 @@ fail: if(args.Length() == $jsargcount) { errorHandler.err.Clear(); -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = $jswrapper(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); @@ -376,7 +377,7 @@ fail: %{ if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) { -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); #else $jsmangledname_class->Inherit( diff --git a/Lib/javascript/v8/javascriptcomplex.swg b/Lib/javascript/v8/javascriptcomplex.swg index 683b972bc..1c0107beb 100644 --- a/Lib/javascript/v8/javascriptcomplex.swg +++ b/Lib/javascript/v8/javascriptcomplex.swg @@ -4,7 +4,7 @@ the complex Constructor method, and the Real and Imag complex accessor methods. - See the std_complex.i and ccomplex.i for concret examples. + See the std_complex.i and ccomplex.i for concrete examples. */ /* the common from converter */ diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 969225401..091467df4 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -1,7 +1,7 @@ %insert(runtime) %{ // Note: since 3.19 there are new CallBack types, since 03.21.9 the old ones have been removed -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) typedef v8::InvocationCallback SwigV8FunctionCallback; typedef v8::AccessorGetter SwigV8AccessorGetterCallback; typedef v8::AccessorSetter SwigV8AccessorSetterCallback; @@ -83,6 +83,7 @@ SWIGRUNTIME void JS_veto_set_variable(v8::Local property, v8::Local< } else { SWIG_exception(SWIG_ERROR, msg); } +fail: ; } %} // v8_helper_functions diff --git a/Lib/javascript/v8/javascriptprimtypes.swg b/Lib/javascript/v8/javascriptprimtypes.swg index fe826b863..c0055c48e 100644 --- a/Lib/javascript/v8/javascriptprimtypes.swg +++ b/Lib/javascript/v8/javascriptprimtypes.swg @@ -112,18 +112,21 @@ int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) %fragment(SWIG_From_frag(long long),"header", fragment=SWIG_From_frag(long), - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE v8::Handle SWIG_From_dec(long long)(long long value) { return SWIGV8_NUMBER_NEW(value); } +%#endif } %fragment(SWIG_AsVal_frag(long long),"header", fragment=SWIG_AsVal_frag(long), fragment="SWIG_CanCastAsInteger", - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) { @@ -134,6 +137,7 @@ int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) return SWIG_OK; } +%#endif } /* unsigned long long */ @@ -141,19 +145,22 @@ int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) %fragment(SWIG_From_frag(unsigned long long),"header", fragment=SWIG_From_frag(long long), - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value) { return (value > LONG_MAX) ? SWIGV8_INTEGER_NEW_UNS(value) : SWIGV8_INTEGER_NEW(%numeric_cast(value,long)); } +%#endif } %fragment(SWIG_AsVal_frag(unsigned long long),"header", fragment=SWIG_AsVal_frag(unsigned long), fragment="SWIG_CanCastAsInteger", - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(v8::Handle obj, unsigned long long *val) { @@ -171,6 +178,7 @@ int SWIG_AsVal_dec(unsigned long long)(v8::Handle obj, unsigned long return SWIG_OK; } +%#endif } /* double */ diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index dc4d37a48..5ac52a51d 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -7,13 +7,13 @@ #define SWIGV8_SETWEAK_VERSION 0x032224 -#if (SWIG_V8_VERSION < 0x031803) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031803) #define SWIGV8_STRING_NEW2(cstr, len) v8::String::New(cstr, len) #else #define SWIGV8_STRING_NEW2(cstr, len) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), cstr, v8::String::kNormalString, len) #endif -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) typedef v8::Handle SwigV8ReturnValue; typedef v8::Arguments SwigV8Arguments; typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; @@ -27,11 +27,11 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return #endif -#if (SWIG_V8_VERSION < 0x032117) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032117) #define SWIGV8_HANDLESCOPE() v8::HandleScope scope #define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope #define SWIGV8_ESCAPE(val) return scope.Close(val) -#elif (SWIG_V8_VERSION < 0x032224) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032224) #define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_ESCAPE(val) return scope.Close(val) @@ -41,7 +41,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_ESCAPE(val) return scope.Escape(val) #endif -#if (SWIG_V8_VERSION < 0x032224) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032224) #define SWIGV8_ADJUST_MEMORY(size) v8::V8::AdjustAmountOfExternalAllocatedMemory(size) #define SWIGV8_CURRENT_CONTEXT() v8::Context::GetCurrent() #define SWIGV8_THROW_EXCEPTION(err) v8::ThrowException(err) @@ -55,7 +55,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_SYMBOL_NEW(sym) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), sym) #endif -#if (SWIG_V8_VERSION < 0x032318) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) #define SWIGV8_ARRAY_NEW() v8::Array::New() #define SWIGV8_BOOLEAN_NEW(bool) v8::Boolean::New(bool) #define SWIGV8_EXTERNAL_NEW(val) v8::External::New(val) @@ -83,9 +83,9 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_NULL() v8::Null(v8::Isolate::GetCurrent()) #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ = v8::Persistent::New(class); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ = v8::Persistent::New(v8::Isolate::GetCurrent(), class); #else #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ.Reset(v8::Isolate::GetCurrent(), class); @@ -97,7 +97,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; * ---------------------------------------------------------------------------*/ #define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) -#define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) +#define SWIG_exception(code, msg) do { SWIGV8_ErrorHandler.error(code, msg); SWIG_fail; } while (0) #define SWIG_fail goto fail #define SWIGV8_OVERLOAD false @@ -156,13 +156,13 @@ public: }; ~SWIGV8_Proxy() { -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) handle.ClearWeak(); handle.Dispose(); -#elif (SWIG_V8_VERSION < 0x032100) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) handle.ClearWeak(v8::Isolate::GetCurrent()); handle.Dispose(v8::Isolate::GetCurrent()); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) handle.ClearWeak(); handle.Dispose(); #else @@ -170,7 +170,7 @@ public: handle.Reset(); #endif -#if (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) handle.Clear(); #endif @@ -187,11 +187,11 @@ class SWIGV8_ClientData { public: v8::Persistent class_templ; -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Value> object, void *parameter); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); #else void (*dtor) (const v8::WeakCallbackData &data); @@ -205,7 +205,7 @@ SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void * if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#if (SWIG_V8_VERSION < 0x031511) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) v8::Handle cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); #else @@ -233,13 +233,13 @@ SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void * } -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { #else SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackData &data) { @@ -257,7 +257,7 @@ SWIGRUNTIME int SWIG_V8_GetInstancePtr(v8::Handle valRef, void **ptr) if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#if (SWIG_V8_VERSION < 0x031511) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) v8::Handle cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); #else @@ -279,34 +279,34 @@ SWIGRUNTIME void SWIGV8_SetPrivateData(v8::Handle obj, void *ptr, sw cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; -#if (SWIG_V8_VERSION < 0x031511) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) obj->SetPointerInInternalField(0, cdata); #else obj->SetAlignedPointerInInternalField(0, cdata); #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle = v8::Persistent::New(obj); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) cdata->handle = v8::Persistent::New(v8::Isolate::GetCurrent(), obj); #else cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } else { cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); } -#elif (SWIG_V8_VERSION < 0x031918) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031918) if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } else { cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); } -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } else { @@ -320,9 +320,9 @@ SWIGRUNTIME void SWIGV8_SetPrivateData(v8::Handle obj, void *ptr, sw } #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle.MarkIndependent(); -#elif (SWIG_V8_VERSION < 0x032100) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); #else cdata->handle.MarkIndependent(); @@ -351,15 +351,15 @@ SWIGRUNTIME v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_inf v8::Handle class_templ; if (ptr == NULL) { -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) SWIGV8_ESCAPE(SWIGV8_NULL()); #else v8::Local result = SWIGV8_NULL(); SWIGV8_ESCAPE(result); -#endif +#endif } -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) if(info->clientdata != 0) { class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; } else { @@ -483,7 +483,7 @@ swig_type_info *SwigV8Packed_UnpackData(v8::Handle valRef, void *ptr, v8::Handle objRef = valRef->ToObject(); -#if (SWIG_V8_VERSION < 0x031511) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) v8::Handle cdataRef = objRef->GetInternalField(0); sobj = static_cast(v8::External::Unwrap(cdataRef)); #else @@ -511,13 +511,13 @@ int SWIGV8_ConvertPacked(v8::Handle valRef, void *ptr, size_t sz, swi return SWIG_OK; } -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) { SwigV8PackedData *cdata = static_cast(parameter); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent object, void *parameter) { SwigV8PackedData *cdata = static_cast(parameter); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent *object, SwigV8PackedData *cdata) { #else SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackData &data) { @@ -527,15 +527,15 @@ SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackDataDispose(isolate); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #else object.Clear(); @@ -552,35 +552,35 @@ v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_inf obj->SetHiddenValue(SWIGV8_STRING_NEW("__swig__packed_data__"), SWIGV8_BOOLEAN_NEW(true)); -#if (SWIG_V8_VERSION < 0x031511) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) obj->SetPointerInInternalField(0, cdata); #else obj->SetAlignedPointerInInternalField(0, cdata); #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle = v8::Persistent::New(obj); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) cdata->handle = v8::Persistent::New(v8::Isolate::GetCurrent(), obj); #else cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); -#elif (SWIG_V8_VERSION < 0x031918) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031918) cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, _wrap_SwigV8PackedData_delete); -#elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); #else cdata->handle.SetWeak(cdata, _wrap_SwigV8PackedData_delete); // v8::V8::SetWeak(&cdata->handle, cdata, _wrap_SwigV8PackedData_delete); #endif -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle.MarkIndependent(); -#elif (SWIG_V8_VERSION < 0x032100) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); #else cdata->handle.MarkIndependent(); @@ -600,7 +600,7 @@ v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_inf SWIGRUNTIME -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) v8::Handle SWIGV8_AppendOutput(v8::Handle result, v8::Handle obj) { #else v8::Handle SWIGV8_AppendOutput(v8::Local result, v8::Handle obj) { @@ -610,11 +610,11 @@ v8::Handle SWIGV8_AppendOutput(v8::Local result, v8::Handl if (result->IsUndefined()) { result = SWIGV8_ARRAY_NEW(); } -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) v8::Handle arr = v8::Handle::Cast(result); #else v8::Local arr = v8::Local::Cast(result); -#endif +#endif arr->Set(arr->Length(), obj); SWIGV8_ESCAPE(arr); diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index ea11b0837..0e4059326 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -5,11 +5,22 @@ // V8 Version Macro // ---------------- -// v8 does not (until now) provide a version macro - which is still discussed and may come soon. -// Until then, we set a default version which can be overridden via command line using V8_VERSION: -// swig -javascript -v8 -DV8_VERSION=0x031110 +// +// v8 added version macros V8_MAJOR_VERSION, V8_MINOR_VERSION, V8_BUILD_NUMBER +// and V8_PATCH_LEVEL in version 4.3.0. SWIG generated code uses these if +// they are defined - to support earlier versions you can specify the V8 version +// in use via the command line when you run SWIG: +// +// swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i +// // Or code in the interface file using SWIG_V8_VERSION: +// // %begin %{#define SWIG_V8_VERSION 0x031110%} +// +// 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. %define %swig_v8_define_version(version) %insert("runtime") %{ diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 721fac22b..660dbbf86 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -806,6 +806,44 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED return result; } +/* The class.get method helper, performs the lookup of class attributes. + * It returns an error code. Number of function return values is passed inside 'ret'. + * first_arg is not used in this function because function always has 2 arguments. + */ +SWIGINTERN int SWIG_Lua_class_do_get_item(lua_State *L, swig_type_info *type, int SWIGUNUSED first_arg, int *ret) +{ +/* there should be 2 params passed in + (1) userdata (not the meta table) + (2) string name of the attribute +*/ + int bases_search_result; + int substack_start = lua_gettop(L)-2; + assert(first_arg == substack_start+1); + lua_checkstack(L,5); + assert(lua_isuserdata(L,-2)); /* just in case */ + lua_getmetatable(L,-2); /* get the meta table */ + assert(lua_istable(L,-1)); /* just in case */ + /* NEW: looks for the __getitem() fn + this is a user provided get fn */ + SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */ + if (lua_iscfunction(L,-1)) /* if its there */ + { /* found it so call the fn & return its value */ + lua_pushvalue(L,substack_start+1); /* the userdata */ + lua_pushvalue(L,substack_start+2); /* the parameter */ + lua_call(L,2,1); /* 2 value in (userdata),1 out (result) */ + lua_remove(L,-2); /* stack tidy, remove metatable */ + if(ret) *ret = 1; + return SWIG_OK; + } + lua_pop(L,1); + /* Remove the metatable */ + lua_pop(L,1); + /* Search in base classes */ + bases_search_result = SWIG_Lua_iterate_bases(L,type,substack_start+1,SWIG_Lua_class_do_get_item,ret); + return bases_search_result; /* sorry not known */ +} + + /* The class.get method helper, performs the lookup of class attributes. * It returns an error code. Number of function return values is passed inside 'ret'. * first_arg is not used in this function because function always has 2 arguments. @@ -853,19 +891,6 @@ SWIGINTERN int SWIG_Lua_class_do_get(lua_State *L, swig_type_info *type, int SW return SWIG_OK; } lua_pop(L,1); /* remove whatever was there */ - /* NEW: looks for the __getitem() fn - this is a user provided get fn */ - SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */ - if (lua_iscfunction(L,-1)) /* if its there */ - { /* found it so call the fn & return its value */ - lua_pushvalue(L,substack_start+1); /* the userdata */ - lua_pushvalue(L,substack_start+2); /* the parameter */ - lua_call(L,2,1); /* 2 value in (userdata),1 out (result) */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - if(ret) *ret = 1; - return SWIG_OK; - } - lua_pop(L,1); /* Remove the metatable */ lua_pop(L,1); /* Search in base classes */ @@ -892,6 +917,10 @@ SWIGINTERN int SWIG_Lua_class_get(lua_State *L) if(result == SWIG_OK) return ret; + result = SWIG_Lua_class_do_get_item(L,type,1,&ret); + if(result == SWIG_OK) + return ret; + return 0; } diff --git a/Lib/lua/std_except.i b/Lib/lua/std_except.i index 160828723..34ab6a1ad 100644 --- a/Lib/lua/std_except.i +++ b/Lib/lua/std_except.i @@ -8,6 +8,7 @@ * ----------------------------------------------------------------------------- */ %{ +#include #include %} %include @@ -27,6 +28,7 @@ namespace std // normally objects which are thrown are returned to the interpreter as errors // (which potentially may have problems if they are not copied) // therefore all classes based upon std::exception are converted to their strings & returned as errors +%typemap(throws) std::bad_cast "SWIG_exception(SWIG_TypeError, $1.what());" %typemap(throws) std::bad_exception "SWIG_exception(SWIG_RuntimeError, $1.what());" %typemap(throws) std::domain_error "SWIG_exception(SWIG_ValueError, $1.what());" %typemap(throws) std::exception "SWIG_exception(SWIG_SystemError, $1.what());" diff --git a/Lib/octave/boost_shared_ptr.i b/Lib/octave/boost_shared_ptr.i index 052d48bb0..e91862057 100644 --- a/Lib/octave/boost_shared_ptr.i +++ b/Lib/octave/boost_shared_ptr.i @@ -41,7 +41,7 @@ %variable_fail(res, "$type", "$name"); } if (!argp) { - %argument_nullref("$type", $symname, $argnum); + %variable_nullref("$type", "$name"); } else { $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get()); if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); @@ -126,7 +126,9 @@ %variable_fail(res, "$type", "$name"); } SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared; - if (!argp) { %argument_nullref("$type", $symname, $argnum); } + if (!argp) { + %variable_nullref("$type", "$name"); + } if (newmem & SWIG_CAST_NEW_MEMORY) { tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); diff --git a/Lib/octave/octcontainer.swg b/Lib/octave/octcontainer.swg index 0211b33c6..af58f3aaa 100644 --- a/Lib/octave/octcontainer.swg +++ b/Lib/octave/octcontainer.swg @@ -562,8 +562,8 @@ namespace swig { static int asptr(const octave_value& obj, sequence **seq) { if (!obj.is_defined() || Swig::swig_value_deref(obj)) { sequence *p; - if (SWIG_ConvertPtr(obj,(void**)&p, - swig::type_info(),0) == SWIG_OK) { + swig_type_info *descriptor = swig::type_info(); + if (descriptor && SWIG_IsOK(SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0))) { if (seq) *seq = p; return SWIG_OLDOBJ; } diff --git a/Lib/octave/octprimtypes.swg b/Lib/octave/octprimtypes.swg index 6f43f21b0..663d1fe10 100644 --- a/Lib/octave/octprimtypes.swg +++ b/Lib/octave/octprimtypes.swg @@ -97,15 +97,20 @@ SWIG_AsVal_dec(bool)(const octave_value& ov, bool *val) // long long -%fragment(SWIG_From_frag(long long),"header") { +%fragment(SWIG_From_frag(long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE octave_value SWIG_From_dec(long long) (long long value) { return octave_int64(value); } +%#endif } -%fragment(SWIG_AsVal_frag(long long),"header") { +%fragment(SWIG_AsVal_frag(long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(long long)(const octave_value& ov, long long* val) { if (!ov.is_scalar_type()) @@ -127,16 +132,22 @@ SWIG_AsVal_dec(bool)(const octave_value& ov, bool *val) } return SWIG_OK; } +%#endif } -%fragment(SWIG_From_frag(unsigned long long),"header") { +%fragment(SWIG_From_frag(unsigned long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE octave_value SWIG_From_dec(unsigned long long) (unsigned long long value) { return octave_uint64(value); } +%#endif } -%fragment(SWIG_AsVal_frag(unsigned long long),"header") { +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(const octave_value& ov, unsigned long long* val) { if (!ov.is_scalar_type()) @@ -171,6 +182,7 @@ SWIG_AsVal_dec(bool)(const octave_value& ov, bool *val) } return SWIG_OK; } +%#endif } // double diff --git a/Lib/octave/octrun.swg b/Lib/octave/octrun.swg index ddfd48939..c1c0dcd67 100644 --- a/Lib/octave/octrun.swg +++ b/Lib/octave/octrun.swg @@ -363,41 +363,44 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return octave_value_list(); } - bool dispatch_unary_op(const std::string &symbol, octave_value &ret) { - member_value_pair *m = find_member(symbol, false); + bool dispatch_unary_op(const std::string &symbol, octave_value &ret) const { + octave_swig_type *nc_this = const_cast < octave_swig_type *>(this); + member_value_pair *m = nc_this->find_member(symbol, false); if (!m || m->first->is_static() || m->first->is_global()) return false; octave_value_list args; - args.append(as_value()); - octave_value_list argout(member_invoke(m, args, 1)); + args.append(nc_this->as_value()); + octave_value_list argout(nc_this->member_invoke(m, args, 1)); if (argout.length() < 1) return false; ret = argout(0); return true; } - bool dispatch_binary_op(const std::string &symbol, const octave_base_value &rhs, octave_value &ret) { - member_value_pair *m = find_member(symbol, false); + bool dispatch_binary_op(const std::string &symbol, const octave_base_value &rhs, octave_value &ret) const { + octave_swig_type *nc_this = const_cast < octave_swig_type *>(this); + member_value_pair *m = nc_this->find_member(symbol, false); if (!m || m->first->is_static() || m->first->is_global()) return false; octave_value_list args; - args.append(as_value()); + args.append(nc_this->as_value()); args.append(make_value_hack(rhs)); - octave_value_list argout(member_invoke(m, args, 1)); + octave_value_list argout(nc_this->member_invoke(m, args, 1)); if (argout.length() < 1) return false; ret = argout(0); return true; } - bool dispatch_index_op(const std::string &symbol, const octave_value_list &rhs, octave_value_list &ret) { - member_value_pair *m = find_member(symbol, false); + bool dispatch_index_op(const std::string &symbol, const octave_value_list &rhs, octave_value_list &ret) const { + octave_swig_type *nc_this = const_cast < octave_swig_type *>(this); + member_value_pair *m = nc_this->find_member(symbol, false); if (!m || m->first->is_static() || m->first->is_global()) return false; octave_value_list args; - args.append(as_value()); + args.append(nc_this->as_value()); args.append(rhs); - octave_value_list argout(member_invoke(m, args, 1)); + octave_value_list argout(nc_this->member_invoke(m, args, 1)); if (argout.length() >= 1) ret = argout(0); return true; @@ -459,22 +462,9 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } dim_vector dims(void) const { - octave_swig_type *nc_this = const_cast < octave_swig_type *>(this); - - // Find the __dims__ method of this object - member_value_pair *m = nc_this->find_member("__dims__", false); - - if (!m) return dim_vector(1,1); - - // Call the __dims__ method of this object - octave_value_list inarg; - inarg.append(nc_this->as_value()); - octave_value_list outarg = nc_this->member_invoke(m, inarg, 1); - - // __dims__ should return (at least) one output argument - if (outarg.length() < 1) return dim_vector(1,1); - - octave_value & out = outarg(0); + octave_value out; + if (!dispatch_unary_op("__dims__", out)) + return dim_vector(1,1); // Return value should be cell or matrix of integers if (out.is_cell()) { @@ -814,20 +804,38 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } virtual std::string string_value(bool force = false) const { - octave_swig_type *nc_this = const_cast < octave_swig_type *>(this); - member_value_pair *m = nc_this->find_member("__str__", false); - if (!m) { - error("__str__ method not defined"); - return std::string(); + octave_value ret; + if (!dispatch_unary_op("__str__", ret)) { + error("__str__ method not defined"); + return std::string(); } - octave_value_list outarg = nc_this->member_invoke(m, octave_value_list(nc_this->as_value()), 1); - if (outarg.length() < 1 || !outarg(0).is_string()) { + if (!ret.is_string()) { error("__str__ method did not return a string"); return std::string(); } - return outarg(0).string_value(); + return ret.string_value(); } + virtual double scalar_value(bool frc_str_conv = false) const { + octave_value ret; + if (!dispatch_unary_op("__float__", ret)) { + error("__float__ method not defined"); + } + return ret.scalar_value(); + } + +#if SWIG_OCTAVE_PREREQ(3,8,0) + virtual octave_value map(octave_base_value::unary_mapper_t umap) const { + const std::string opname = std::string("__") + octave_base_value::get_umap_name(umap) + std::string("__"); + octave_value ret; + if (!dispatch_unary_op(opname, ret)) { + error((opname + std::string(" method not found")).c_str()); + return octave_value(); + } + return ret; + } +#endif + #if SWIG_OCTAVE_PREREQ(3,3,52) virtual octave_map map_value() const { return octave_map(); @@ -982,10 +990,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } #if SWIG_OCTAVE_PREREQ(4,0,0) - void print(std::ostream &os, bool pr_as_read_syntax = false) { + void print(std::ostream &os, bool pr_as_read_syntax = false) #else - void print(std::ostream &os, bool pr_as_read_syntax = false) const { + void print(std::ostream &os, bool pr_as_read_syntax = false) const #endif + { if (is_string()) { os << string_value(); return; @@ -1080,6 +1089,14 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); virtual std::string string_value(bool force = false) const { return ptr->string_value(force); } + virtual double scalar_value(bool frc_str_conv = false) const + { return ptr->scalar_value(frc_str_conv); } + +#if SWIG_OCTAVE_PREREQ(3,8,0) + virtual octave_value map(octave_base_value::unary_mapper_t umap) const + { return ptr->map(umap); } +#endif + #if SWIG_OCTAVE_PREREQ(3,3,52) virtual octave_map map_value() const { return ptr->map_value(); } @@ -1137,7 +1154,17 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); #endif { return ptr->print(os, pr_as_read_syntax); } + virtual type_conv_info numeric_conversion_function(void) const { + return octave_base_value::type_conv_info (default_numeric_conversion_function, + octave_scalar::static_type_id ()); + } + private: + static octave_base_value *default_numeric_conversion_function (const octave_base_value& a) { + const octave_swig_ref& v = dynamic_cast(a); + return new octave_scalar(v.scalar_value()); + } + #if !SWIG_OCTAVE_PREREQ(4,0,0) DECLARE_OCTAVE_ALLOCATOR; #endif @@ -1178,10 +1205,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } #if SWIG_OCTAVE_PREREQ(4,0,0) - void print(std::ostream &os, bool pr_as_read_syntax = false) { + void print(std::ostream &os, bool pr_as_read_syntax = false) #else - void print(std::ostream &os, bool pr_as_read_syntax = false) const { + void print(std::ostream &os, bool pr_as_read_syntax = false) const #endif + { indent(os); os << "swig packed type: name = " << (type ? type->name : std::string()) << ", len = " << buf.size(); newline(os); } diff --git a/Lib/octave/octruntime.swg b/Lib/octave/octruntime.swg index fbf2007f6..1efc96f8f 100644 --- a/Lib/octave/octruntime.swg +++ b/Lib/octave/octruntime.swg @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -182,6 +183,23 @@ DEFUN_DLD( swig_this, args, nargout, swig_this_usage ) { return octave_value(octave_uint64((unsigned long long) ost->swig_this())); } +static const char *const swig_octave_prereq_usage = "-*- texinfo -*- \n\ +@deftypefn {Loadable Function} {} swig_octave_prereq(@var{major}, @var{minor}, @var{patch})\n\ +Return true if the version of Octave is at least @var{major}.@var{minor}.@var{patch}.\n\ +@end deftypefn"; + +DEFUN_DLD( swig_octave_prereq, args, nargout, swig_octave_prereq_usage ) { + if (args.length() != 3) { + error("swig_octave_prereq: must be called with 3 arguments"); + return octave_value_list(); + } + const int major = args(0).int_value(); + const int minor = args(1).int_value(); + const int patch = args(2).int_value(); + const bool prereq = SWIG_OCTAVE_PREREQ(major, minor, patch); + return octave_value(prereq); +} + static const char *const SWIG_name_usage = "-*- texinfo -*- \n\ @deftypefn {Loadable Module} {} " SWIG_name_d "\n\ Loads the SWIG-generated module `" SWIG_name_d "'.\n\ @@ -235,6 +253,9 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { octave_function *me = octave_call_stack::current(); + if (!SWIG_Octave_InstallFunction(me, "subclass")) { + return octave_value_list(); + } if (!SWIG_Octave_InstallFunction(me, "swig_type")) { return octave_value_list(); } @@ -244,7 +265,7 @@ DEFUN_DLD( SWIG_name, args, nargout, SWIG_name_usage ) { if (!SWIG_Octave_InstallFunction(me, "swig_this")) { return octave_value_list(); } - if (!SWIG_Octave_InstallFunction(me, "subclass")) { + if (!SWIG_Octave_InstallFunction(me, "swig_octave_prereq")) { return octave_value_list(); } diff --git a/Lib/octave/octstdcommon.swg b/Lib/octave/octstdcommon.swg index 96923f40a..799d369a7 100644 --- a/Lib/octave/octstdcommon.swg +++ b/Lib/octave/octstdcommon.swg @@ -42,7 +42,8 @@ namespace swig { struct traits_asptr { static int asptr(const octave_value& obj, Type **val) { Type *p; - int res = SWIG_ConvertPtr(obj, (void**)&p, type_info(), 0); + swig_type_info *descriptor = type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = p; } diff --git a/Lib/octave/std_common.i b/Lib/octave/std_common.i index 9aebf7f45..c8f17ba7f 100644 --- a/Lib/octave/std_common.i +++ b/Lib/octave/std_common.i @@ -11,17 +11,17 @@ fragment=SWIG_From_frag(Type), fragment="StdTraits") { namespace swig { - template <> struct traits { + template <> struct traits< Type > { typedef value_category category; static const char* type_name() { return #Type; } - }; - template <> struct traits_asval { + }; + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(octave_value obj, value_type *val) { + static int asval(octave_value obj, value_type *val) { return SWIG_AsVal(Type)(obj, val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static octave_value from(const value_type& val) { return SWIG_From(Type)(val); @@ -44,13 +44,13 @@ namespace swig { fragment=SWIG_From_frag(int), fragment="StdTraits") { namespace swig { - template <> struct traits_asval { + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(octave_value obj, value_type *val) { + static int asval(octave_value obj, value_type *val) { return SWIG_AsVal(int)(obj, (int *)val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static octave_value from(const value_type& val) { return SWIG_From(int)((int)val); diff --git a/Lib/octave/std_map.i b/Lib/octave/std_map.i index 7b85a548e..fd15661c3 100644 --- a/Lib/octave/std_map.i +++ b/Lib/octave/std_map.i @@ -98,7 +98,8 @@ res = traits_asptr_stdseq, std::pair >::asptr(items, val); } else { map_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; diff --git a/Lib/octave/std_pair.i b/Lib/octave/std_pair.i index ab028d144..a06498bf2 100644 --- a/Lib/octave/std_pair.i +++ b/Lib/octave/std_pair.i @@ -47,7 +47,8 @@ return get_pair(c(0),c(1),val); } else { value_type *p; - int res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = *p; return res; @@ -100,7 +101,8 @@ return get_pair(c(0),c(1),val); } else { value_type *p; - int res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; return res; diff --git a/Lib/perl5/perlinit.swg b/Lib/perl5/perlinit.swg index cdb73d53a..b49040d26 100644 --- a/Lib/perl5/perlinit.swg +++ b/Lib/perl5/perlinit.swg @@ -28,6 +28,7 @@ extern "C" XS(SWIG_init) { dXSARGS; int i; + (void)items; SWIG_InitializeModule(0); diff --git a/Lib/perl5/perlprimtypes.swg b/Lib/perl5/perlprimtypes.swg index d7ac6f94e..4cb675671 100644 --- a/Lib/perl5/perlprimtypes.swg +++ b/Lib/perl5/perlprimtypes.swg @@ -37,7 +37,7 @@ SWIGINTERNINLINE SV * SWIG_From_dec(long)(long value) { SV *sv; - if (value >= IV_MIN && value <= IV_MAX) + if (IVSIZE >= sizeof(value) || (value >= IV_MIN && value <= IV_MAX)) sv = newSViv(value); else sv = newSVpvf("%ld", value); @@ -46,20 +46,22 @@ SWIG_From_dec(long)(long value) } %fragment(SWIG_AsVal_frag(long),"header", + fragment="", + fragment="", fragment="SWIG_CanCastAsInteger") { SWIGINTERN int SWIG_AsVal_dec(long)(SV *obj, long* val) { if (SvUOK(obj)) { UV v = SvUV(obj); - if (v <= LONG_MAX) { + if (UVSIZE < sizeof(*val) || v <= LONG_MAX) { if (val) *val = v; return SWIG_OK; } return SWIG_OverflowError; } else if (SvIOK(obj)) { IV v = SvIV(obj); - if (v >= LONG_MIN && v <= LONG_MAX) { + if (IVSIZE <= sizeof(*val) || (v >= LONG_MIN && v <= LONG_MAX)) { if(val) *val = v; return SWIG_OK; } @@ -102,7 +104,7 @@ SWIGINTERNINLINE SV * SWIG_From_dec(unsigned long)(unsigned long value) { SV *sv; - if (value <= UV_MAX) + if (UVSIZE >= sizeof(value) || value <= UV_MAX) sv = newSVuv(value); else sv = newSVpvf("%lu", value); @@ -111,20 +113,22 @@ SWIG_From_dec(unsigned long)(unsigned long value) } %fragment(SWIG_AsVal_frag(unsigned long),"header", + fragment="", + fragment="", fragment="SWIG_CanCastAsInteger") { SWIGINTERN int SWIG_AsVal_dec(unsigned long)(SV *obj, unsigned long *val) { if (SvUOK(obj)) { UV v = SvUV(obj); - if (v <= ULONG_MAX) { + if (UVSIZE <= sizeof(*val) || v <= ULONG_MAX) { if (val) *val = v; return SWIG_OK; } return SWIG_OverflowError; } else if (SvIOK(obj)) { IV v = SvIV(obj); - if (v >= 0 && v <= ULONG_MAX) { + if (v >= 0 && (IVSIZE <= sizeof(*val) || v <= ULONG_MAX)) { if (val) *val = v; return SWIG_OK; } @@ -163,14 +167,14 @@ SWIG_AsVal_dec(unsigned long)(SV *obj, unsigned long *val) /* long long */ %fragment(SWIG_From_frag(long long),"header", - fragment=SWIG_From_frag(long), - fragment="", + fragment="SWIG_LongLongAvailable", fragment="") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE SV * SWIG_From_dec(long long)(long long value) { SV *sv; - if (value >= IV_MIN && value <= IV_MAX) + if (IVSIZE >= sizeof(value) || (value >= IV_MIN && value <= IV_MAX)) sv = newSViv((IV)(value)); else { //sv = newSVpvf("%lld", value); doesn't work in non 64bit Perl @@ -180,26 +184,28 @@ SWIG_From_dec(long long)(long long value) } return sv_2mortal(sv); } +%#endif } %fragment(SWIG_AsVal_frag(long long),"header", - fragment="", + fragment="SWIG_LongLongAvailable", fragment="", fragment="SWIG_CanCastAsInteger") { - +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(long long)(SV *obj, long long *val) { if (SvUOK(obj)) { UV v = SvUV(obj); - if (v < LLONG_MAX) { + /* pretty sure this could allow v == LLONG MAX */ + if (UVSIZE < sizeof(*val) || v < LLONG_MAX) { if (val) *val = v; return SWIG_OK; } return SWIG_OverflowError; } else if (SvIOK(obj)) { IV v = SvIV(obj); - if (v >= LLONG_MIN && v <= LLONG_MAX) { + if (IVSIZE <= sizeof(*val) || (v >= LLONG_MIN && v <= LLONG_MAX)) { if (val) *val = v; return SWIG_OK; } @@ -235,19 +241,20 @@ SWIG_AsVal_dec(long long)(SV *obj, long long *val) } return SWIG_TypeError; } +%#endif } /* unsigned long long */ %fragment(SWIG_From_frag(unsigned long long),"header", - fragment=SWIG_From_frag(long long), - fragment="", + fragment="SWIG_LongLongAvailable", fragment="") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE SV * SWIG_From_dec(unsigned long long)(unsigned long long value) { SV *sv; - if (value <= UV_MAX) + if (UVSIZE >= sizeof(value) || value <= UV_MAX) sv = newSVuv((UV)(value)); else { //sv = newSVpvf("%llu", value); doesn't work in non 64bit Perl @@ -257,21 +264,25 @@ SWIG_From_dec(unsigned long long)(unsigned long long value) } return sv_2mortal(sv); } +%#endif } %fragment(SWIG_AsVal_frag(unsigned long long),"header", - fragment="", + fragment="SWIG_LongLongAvailable", fragment="", fragment="SWIG_CanCastAsInteger") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(SV *obj, unsigned long long *val) { if (SvUOK(obj)) { + /* pretty sure this should be conditional on + * (UVSIZE <= sizeof(*val) || v <= ULLONG_MAX) */ if (val) *val = SvUV(obj); return SWIG_OK; } else if (SvIOK(obj)) { IV v = SvIV(obj); - if (v >= 0 && v <= ULLONG_MAX) { + if (v >= 0 && (IVSIZE <= sizeof(*val) || v <= ULLONG_MAX)) { if (val) *val = v; return SWIG_OK; } else { @@ -307,6 +318,7 @@ SWIG_AsVal_dec(unsigned long long)(SV *obj, unsigned long long *val) } return SWIG_TypeError; } +%#endif } /* double */ diff --git a/Lib/perl5/perlrun.swg b/Lib/perl5/perlrun.swg index 876fae268..d1865de0a 100644 --- a/Lib/perl5/perlrun.swg +++ b/Lib/perl5/perlrun.swg @@ -144,9 +144,9 @@ typedef int (*SwigMagicFunc)(struct interpreter *, SV *, MAGIC *); # ifdef PERL_OBJECT # define SWIG_croak_null() SWIG_Perl_croak_null(pPerl) -static void SWIG_Perl_croak_null(CPerlObj *pPerl) +static void SWIGUNUSED SWIG_Perl_croak_null(CPerlObj *pPerl) # else -static void SWIG_croak_null() +static void SWIGUNUSED SWIG_croak_null() # endif { SV *err = get_sv("@", GV_ADD); diff --git a/Lib/perl5/std_list.i b/Lib/perl5/std_list.i index 8248ca679..cd5a61120 100644 --- a/Lib/perl5/std_list.i +++ b/Lib/perl5/std_list.i @@ -106,7 +106,7 @@ namespace std { } } %typemap(out) list { - std::list::const_iterator i; + std::list< T >::const_iterator i; unsigned int j; int len = $1.size(); SV **svs = new SV*[len]; @@ -125,7 +125,7 @@ namespace std { %typecheck(SWIG_TYPECHECK_LIST) list { { /* wrapped list? */ - std::list* v; + std::list< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_&descriptor,0) != -1) { $1 = 1; @@ -158,7 +158,7 @@ namespace std { const list* { { /* wrapped list? */ - std::list* v; + std::list< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_descriptor,0) != -1) { $1 = 1; @@ -265,7 +265,7 @@ namespace std { } } %typemap(out) list { - std::list::const_iterator i; + std::list< T >::const_iterator i; unsigned int j; int len = $1.size(); SV **svs = new SV*[len]; @@ -282,7 +282,7 @@ namespace std { %typecheck(SWIG_TYPECHECK_LIST) list { { /* wrapped list? */ - std::list* v; + std::list< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_&descriptor,0) != -1) { $1 = 1; @@ -313,7 +313,7 @@ namespace std { const list* { { /* wrapped list? */ - std::list* v; + std::list< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_descriptor,0) != -1) { $1 = 1; diff --git a/Lib/perl5/std_map.i b/Lib/perl5/std_map.i index 493307dd9..af49ed38e 100644 --- a/Lib/perl5/std_map.i +++ b/Lib/perl5/std_map.i @@ -35,7 +35,7 @@ namespace std { void clear(); %extend { const T& get(const K& key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) return i->second; else @@ -45,14 +45,14 @@ namespace std { (*self)[key] = x; } void del(const K& key) throw (std::out_of_range) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); if (i != self->end()) self->erase(i); else throw std::out_of_range("key not found"); } bool has_key(const K& key) { - std::map::iterator i = self->find(key); + std::map< K, T >::iterator i = self->find(key); return i != self->end(); } } diff --git a/Lib/perl5/std_vector.i b/Lib/perl5/std_vector.i index 860cdba7e..ec8449464 100644 --- a/Lib/perl5/std_vector.i +++ b/Lib/perl5/std_vector.i @@ -119,7 +119,7 @@ namespace std { %typecheck(SWIG_TYPECHECK_VECTOR) vector { { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor,0) != -1) { $1 = 1; @@ -151,7 +151,7 @@ namespace std { const vector* { { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_descriptor,0) != -1) { $1 = 1; @@ -292,7 +292,7 @@ namespace std { %typecheck(SWIG_TYPECHECK_VECTOR) vector { { /* wrapped vector? */ - std::vector* v; + std::vector< T *>* v; int res = SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor,0); if (SWIG_IsOK(res)) { $1 = 1; @@ -323,7 +323,7 @@ namespace std { %typecheck(SWIG_TYPECHECK_VECTOR) const vector&,const vector* { { /* wrapped vector? */ - std::vector *v; + std::vector< T *> *v; int res = SWIG_ConvertPtr($input,%as_voidptrptr(&v), $1_descriptor,0); if (SWIG_IsOK(res)) { $1 = 1; @@ -466,7 +466,7 @@ namespace std { %typecheck(SWIG_TYPECHECK_VECTOR) vector { { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor,0) != -1) { $1 = 1; @@ -496,7 +496,7 @@ namespace std { const vector* { { /* wrapped vector? */ - std::vector* v; + std::vector< T >* v; if (SWIG_ConvertPtr($input,(void **) &v, $1_descriptor,0) != -1) { $1 = 1; diff --git a/Lib/php/const.i b/Lib/php/const.i index 061ba99a2..d62f162c1 100644 --- a/Lib/php/const.i +++ b/Lib/php/const.i @@ -12,10 +12,12 @@ unsigned long, unsigned char, signed char, - bool, enum SWIGTYPE "SWIG_LONG_CONSTANT($symname, ($1_type)$value);"; +%typemap(consttab) bool + "SWIG_BOOL_CONSTANT($symname, ($1_type)$value);"; + %typemap(consttab) float, double "SWIG_DOUBLE_CONSTANT($symname, $value);"; @@ -33,18 +35,13 @@ SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [] { - zval *z_var; zend_constant c; - size_t len = sizeof("$symname") - 1; - MAKE_STD_ZVAL(z_var); - SWIG_SetPointerZval(z_var, (void*)$value, $1_descriptor, 0); - c.value = *z_var; + SWIG_SetPointerZval(&c.value, (void*)$value, $1_descriptor, 0); zval_copy_ctor(&c.value); - c.name = zend_strndup("$symname", len); - c.name_len = len+1; - c.flags = CONST_CS | CONST_PERSISTENT; + c.name = zend_string_init("$symname", sizeof("$symname") - 1, 0); + c.flags = CONST_CS; c.module_number = module_number; - zend_register_constant( &c TSRMLS_CC ); + zend_register_constant(&c); } /* Handled as a global variable. */ diff --git a/Lib/php/director.swg b/Lib/php/director.swg index d9dccdf6f..082b03604 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -80,30 +80,30 @@ namespace Swig { class Director { protected: - zval *swig_self; + // "mutable" so we can get a non-const pointer to it in const methods. + mutable zval swig_self; typedef std::map swig_ownership_map; mutable swig_ownership_map swig_owner; -#ifdef ZTS - // Store the ZTS context so it's available when C++ calls back to PHP. - void *** swig_zts_ctx; -#endif public: - Director(zval *self TSRMLS_DC) : swig_self(self) { - TSRMLS_SET_CTX(swig_zts_ctx); + Director(zval *self) { + ZVAL_COPY_VALUE(&swig_self, self); } - static bool swig_is_overridden_method(char *cname, char *lc_fname TSRMLS_DC) { - zend_class_entry **ce; - zend_function *mptr; - - if (zend_lookup_class(cname, strlen(cname), &ce TSRMLS_CC) != SUCCESS) { - return false; + static bool swig_is_overridden_method(const char *cname, const char *lc_fname) { + bool result = false; + zend_string * cname_str = zend_string_init(cname, strlen(cname), 0); + zend_class_entry *ce = zend_lookup_class(cname_str); + if (ce) { + zval * mptr = zend_hash_str_find(&ce->function_table, lc_fname, strlen(lc_fname)); + if (mptr) { + // common.scope points to zend_class_entry for the declaring class, + // and there's only one of those per class, so we can just use a + // pointer compare here. + result = Z_FUNC_P(mptr)->common.scope != ce; + } } - if (zend_hash_find(&(*ce)->function_table, lc_fname, strlen(lc_fname) + 1, (void **) &mptr) != SUCCESS) { - return false; - } - // common.scope points to the declaring class - return strcmp(mptr->common.scope->name, cname); + zend_string_release(cname_str); + return result; } template @@ -119,8 +119,8 @@ namespace Swig { protected: std::string swig_msg; public: - DirectorException(int code, const char *hdr, const char *msg TSRMLS_DC) : swig_msg(hdr) { - if (msg[0]) { + DirectorException(int code, const char *hdr, const char *msg) : swig_msg(hdr) { + if (msg && msg[0]) { swig_msg += " "; swig_msg += msg; } @@ -135,20 +135,20 @@ namespace Swig { return swig_msg.c_str(); } - static void raise(int code, const char *hdr, const char *msg TSRMLS_DC) { - throw DirectorException(code, hdr, msg TSRMLS_CC); + static void raise(int code, const char *hdr, const char *msg) { + throw DirectorException(code, hdr, msg); } }; /* attempt to call a pure virtual method via a director method */ class DirectorPureVirtualException : public DirectorException { public: - DirectorPureVirtualException(const char *msg TSRMLS_DC) - : DirectorException(E_ERROR, "SWIG director pure virtual method called", msg TSRMLS_CC) { + DirectorPureVirtualException(const char *msg) + : DirectorException(E_ERROR, "SWIG director pure virtual method called", msg) { } - static void raise(const char *msg TSRMLS_DC) { - throw DirectorPureVirtualException(msg TSRMLS_CC); + static void raise(const char *msg) { + throw DirectorPureVirtualException(msg); } }; @@ -156,18 +156,18 @@ namespace Swig { class DirectorMethodException : public DirectorException { public: - DirectorMethodException(const char *msg TSRMLS_DC) - : DirectorException(E_ERROR, "SWIG director method error", msg TSRMLS_CC) { + DirectorMethodException() + : DirectorException(E_ERROR, "SWIG director method error", NULL) { } - static void raise(const char *msg TSRMLS_DC) { - throw DirectorMethodException(msg TSRMLS_CC); + DirectorMethodException(const char *msg) + : DirectorException(E_ERROR, "SWIG director method error", msg) { + } + + static void raise(const char *msg) { + throw DirectorMethodException(msg); } }; } -// DirectorMethodException() is documented to be callable with no parameters -// so use a macro to insert TSRMLS_CC so any ZTS context gets passed. -#define DirectorMethodException() DirectorMethodException("" TSRMLS_CC) - #endif diff --git a/Lib/php/globalvar.i b/Lib/php/globalvar.i index 4f21c5cbf..a5fd779ab 100644 --- a/Lib/php/globalvar.i +++ b/Lib/php/globalvar.i @@ -4,20 +4,22 @@ * Global variables - add the variable to PHP * ----------------------------------------------------------------------------- */ -%typemap(varinit) char *, - char [] +%typemap(varinit) char * { - zval *z_var; - MAKE_STD_ZVAL(z_var); - z_var->type = IS_STRING; - if($1) { - z_var->value.str.val = estrdup($1); - z_var->value.str.len = strlen($1); + zval z_var; + if ($1) { + ZVAL_STRING(&z_var, $1); } else { - z_var->value.str.val = 0; - z_var->value.str.len = 0; + ZVAL_STR(&z_var, ZSTR_EMPTY_ALLOC()); } - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); +} + +%typemap(varinit) char [] +{ + zval z_var; + ZVAL_STRING(&z_var, $1); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) int, @@ -31,139 +33,98 @@ unsigned char, enum SWIGTYPE { - zval *z_var; - MAKE_STD_ZVAL(z_var); - z_var->type = IS_LONG; - z_var->value.lval = (long)$1; - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); + zval z_var; + ZVAL_LONG(&z_var, (long)$1); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) bool { - zval *z_var; - MAKE_STD_ZVAL(z_var); - z_var->type = IS_BOOL; - z_var->value.lval = ($1)?1:0; - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); + zval z_var; + ZVAL_BOOL(&z_var, ($1)?1:0); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) float, double { - zval *z_var; - MAKE_STD_ZVAL(z_var); - z_var->type = IS_DOUBLE; - z_var->value.dval = $1; - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, - sizeof(zval *), NULL); + zval z_var; + ZVAL_DOUBLE(&z_var, (double)$1); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) char { - zval *z_var; - char c[2]; - MAKE_STD_ZVAL(z_var); - c[0] = $1; - c[1] = 0; - z_var->type = IS_STRING; - z_var->value.str.val = estrndup(c, 1); - z_var->value.str.len = 1; - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, - sizeof(zval *), NULL); + zval z_var; + char c = $1; + ZVAL_STRINGL(&z_var, &c, 1); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) SWIGTYPE *, SWIGTYPE [] { - zval *z_var; - MAKE_STD_ZVAL(z_var); - SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0); - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, - sizeof(zval *), NULL); + zval z_var; + SWIG_SetPointerZval(&z_var, (void*)$1, $1_descriptor, 0); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) SWIGTYPE, SWIGTYPE &, SWIGTYPE && { - zval *z_var; - - MAKE_STD_ZVAL(z_var); - SWIG_SetPointerZval(z_var, (void*)&$1, $&1_descriptor, 0); - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&z_var, - sizeof(zval *), NULL); + zval z_var; + SWIG_SetPointerZval(&z_var, (void*)&$1, $&1_descriptor, 0); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit) char [ANY] { - zval *z_var; - MAKE_STD_ZVAL(z_var); - z_var->type = IS_STRING; - if ($1) { - /* varinit char [ANY] */ - ZVAL_STRINGL(z_var,(char*)$1, $1_dim0, 1); - } - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&z_var, sizeof(zval *), NULL); + zval z_var; + /* varinit char [ANY] */ + ZVAL_STRINGL(&z_var, $1, $1_dim0); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &z_var); } %typemap(varinit, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) { + zval resource; void * p = emalloc(sizeof($1)); memcpy(p, &$1, sizeof($1)); - zval * resource; - MAKE_STD_ZVAL(resource); - ZEND_REGISTER_RESOURCE(resource, p, swig_member_ptr); - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&resource, sizeof(zval *), NULL); + ZVAL_RES(&resource, zend_register_resource(p, swig_member_ptr)); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &resource); } %typemap(varin) int, unsigned int, short, unsigned short, long, unsigned long, signed char, unsigned char, enum SWIGTYPE { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - convert_to_long_ex(z_var); - if ($1 != ($1_ltype)((*z_var)->value.lval)) { - $1 = Z_LVAL_PP(z_var); - } + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + $1 = zval_get_long(z_var); } %typemap(varin) bool { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - convert_to_boolean_ex(z_var); - if ($1 != ($1_ltype)((*z_var)->value.lval)) { - $1 = Z_LVAL_PP(z_var); - } + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + convert_to_boolean(z_var); + $1 = (Z_TYPE_P(z_var) == IS_TRUE); } %typemap(varin) double,float { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - convert_to_double_ex(z_var); - if ($1 != ($1_ltype)((*z_var)->value.dval)) { - $1 = Z_DVAL_PP(z_var); - } + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + $1 = zval_get_double(z_var); } %typemap(varin) char { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - convert_to_string_ex(z_var); - if ($1 != *((*z_var)->value.str.val)) { - $1 = *((*z_var)->value.str.val); + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + convert_to_string(z_var); + if ($1 != Z_STRVAL_P(z_var)[0]) { + $1 = Z_STRVAL_P(z_var)[0]; } } %typemap(varin) char * { - zval **z_var; + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); char *s1; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - convert_to_string_ex(z_var); - s1 = Z_STRVAL_PP(z_var); + convert_to_string(z_var); + s1 = Z_STRVAL_P(z_var); if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { if (s1) $1 = estrdup(s1); @@ -175,11 +136,9 @@ %typemap(varin) SWIGTYPE [] { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); if($1) { - SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, $owner); + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, $owner); } } @@ -188,8 +147,8 @@ zval **z_var; char *s1; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - s1 = Z_STRVAL_PP(z_var); + zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1, (void**)&z_var); + s1 = Z_STRVAL_P(z_var); if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { if (s1) strncpy($1, s1, $1_dim0); @@ -198,11 +157,11 @@ %typemap(varin) SWIGTYPE { - zval **z_var; + zval *z_var; $&1_ltype _temp; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if (SWIG_ConvertPtr(*z_var, (void**)&_temp, $&1_descriptor, 0) < 0) { + z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + if (SWIG_ConvertPtr(z_var, (void**)&_temp, $&1_descriptor, 0) < 0) { SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor"); } @@ -212,11 +171,11 @@ %typemap(varin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && { - zval **z_var; + zval *z_var; $1_ltype _temp; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if (SWIG_ConvertPtr(*z_var, (void **)&_temp, $1_descriptor, 0) < 0) { + z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + if (SWIG_ConvertPtr(z_var, (void **)&_temp, $1_descriptor, 0) < 0) { SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor"); } @@ -225,10 +184,8 @@ %typemap(varin, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - void * p = (void*)zend_fetch_resource(*z_var TSRMLS_CC, -1, SWIG_MEMBER_PTR, NULL, 1, swig_member_ptr); + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + void * p = (void*)zend_fetch_resource_ex(z_var, SWIG_MEMBER_PTR, swig_member_ptr); memcpy(&$1, p, sizeof($1)); } @@ -242,114 +199,96 @@ unsigned char, enum SWIGTYPE { - zval **z_var; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if($1 != ($1_ltype)((*z_var)->value.lval)) { - (*z_var)->value.lval = (long)$1; + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + if ($1 != ($1_ltype)Z_LVAL_P(z_var)) { + z_var->value.lval = (long)$1; } } //SAMFIX need to cast zval->type, what if zend-hash_find fails? etc? %typemap(varout) bool { - zval **z_var; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if($1 != ($1_ltype)((*z_var)->value.lval)) { - (*z_var)->value.lval = (long)$1; + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + if ($1 != ($1_ltype)Z_LVAL_P(z_var)) { + z_var->value.lval = (long)$1; } } %typemap(varout) double, float { - zval **z_var; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if($1 != ($1_ltype)((*z_var)->value.dval)) { - (*z_var)->value.dval = (double)$1; + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + if ($1 != ($1_ltype)Z_DVAL_P(z_var)) { + z_var->value.dval = (double)$1; } } %typemap(varout) char { - zval **z_var; - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if($1 != *((*z_var)->value.str.val)) { - char c[2]; - efree((*z_var)->value.str.val); - c[0] = $1; - c[1] = 0; - (*z_var)->value.str.val = estrdup(c); + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + char c = $1; + if ($1 != Z_STRVAL_P(z_val)[0]) { + ZVAL_STRING(z_var, &c); } } %typemap(varout) char * { - zval **z_var; - char *s1; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - s1 = Z_STRVAL_PP(z_var); - if((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { - if(s1) + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + const char *s1 = Z_STRVAL_P(z_var); + if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { + if (s1) efree(s1); - if($1) { - (*z_var)->value.str.val = estrdup($1); - (*z_var)->value.str.len = strlen($1) + 1; + if ($1) { + (z_var)->value.str.val = estrdup($1); + (z_var)->value.str.len = strlen($1) + 1; } else { - (*z_var)->value.str.val = 0; - (*z_var)->value.str.len = 0; + (z_var)->value.str.val = 0; + (z_var)->value.str.len = 0; } } } %typemap(varout) SWIGTYPE { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - SWIG_SetPointerZval(*z_var, (void*)&$1, $&1_descriptor, 0); + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + SWIG_SetPointerZval(z_var, (void*)&$1, $&1_descriptor, 0); } %typemap(varout) SWIGTYPE [] { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - if($1) - SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0); + if($1) { + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0); + } } %typemap(varout) char [ANY] { - zval **z_var; - char *s1; + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + const char *s1 = Z_STRVAL_P(z_var); deliberate error cos this code looks bogus to me - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - s1 = Z_STRVAL_PP(z_var); - if((s1 == NULL) || strcmp(s1, $1)) { - if($1) { - (*z_var)->value.str.val = estrdup($1); - (*z_var)->value.str.len = strlen($1) + 1; + if ((s1 == NULL) || strcmp(s1, $1)) { + if ($1) { + (z_var)->value.str.val = estrdup($1); + (z_var)->value.str.len = strlen($1) + 1; } else { - (*z_var)->value.str.val = 0; - (*z_var)->value.str.len = 0; + (z_var)->value.str.val = 0; + (z_var)->value.str.len = 0; } } } %typemap(varout) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && { - zval **z_var; - - zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); - SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0); + zval *z_var = zend_hash_str_find(&EG(symbol_table), "$1", sizeof("$1") - 1); + SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0); } %typemap(varout, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) { + zval resource; void * p = emalloc(sizeof($1)); memcpy(p, &$1, sizeof($1)); - zval * resource; - MAKE_STD_ZVAL(resource); - ZEND_REGISTER_RESOURCE(resource, p, swig_member_ptr); - zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&resource, sizeof(zval *), NULL); + ZVAL_RES(&resource, zend_register_resource(p, swig_member_ptr)); + zend_hash_str_add(&EG(symbol_table), "$1", sizeof("$1") - 1, &resource); } diff --git a/Lib/php/php.swg b/Lib/php/php.swg index 8b5fb7be3..c9b9a5217 100644 --- a/Lib/php/php.swg +++ b/Lib/php/php.swg @@ -71,72 +71,72 @@ // char array can be in/out, though the passed string may not be big enough... // so we have to size it %typemap(in) char[ANY] -{ - convert_to_string_ex($input); - $1 = ($1_ltype) Z_STRVAL_PP($input); -} +%{ + convert_to_string(&$input); + $1 = ($1_ltype) Z_STRVAL($input); +%} -%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) { - convert_to_string_ex($input); - $1 = ($1_ltype) Z_STRVAL_PP($input); - $2 = ($2_ltype) Z_STRLEN_PP($input); -} +%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) %{ + convert_to_string(&$input); + $1 = ($1_ltype) Z_STRVAL($input); + $2 = ($2_ltype) Z_STRLEN($input); +%} /* Object passed by value. Convert to a pointer */ %typemap(in) SWIGTYPE ($&1_ltype tmp) -{ - if(SWIG_ConvertPtr(*$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); } $1 = *tmp; -} +%} %typemap(directorout) SWIGTYPE ($&1_ltype tmp) -{ +%{ /* If exit was via exception, PHP NULL is returned so skip the conversion. */ if (!EG(exception)) { - if(SWIG_ConvertPtr($input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) + if (SWIG_ConvertPtr($input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); $result = *tmp; } -} +%} %typemap(in) SWIGTYPE *, SWIGTYPE [] -{ - if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0) { SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); } -} +%} %typemap(in) SWIGTYPE & -{ - if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); } -} +%} %typemap(in) SWIGTYPE && -{ - if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); } -} +%} %typemap(in) SWIGTYPE *const& ($*ltype temp) -{ - if(SWIG_ConvertPtr(*$input, (void **) &temp, $*1_descriptor, 0) < 0) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &temp, $*1_descriptor, 0) < 0) { SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $*1_descriptor"); } $1 = ($1_ltype)&temp; -} +%} %typemap(in) SWIGTYPE *DISOWN -{ - if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, SWIG_POINTER_DISOWN ) < 0) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, SWIG_POINTER_DISOWN ) < 0) { SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); } -} +%} %typemap(argout) SWIGTYPE *, SWIGTYPE [], @@ -144,14 +144,14 @@ SWIGTYPE &&; %typemap(in) void * -{ - if(SWIG_ConvertPtr(*$input, (void **) &$1, 0, 0) < 0) { +%{ + if (SWIG_ConvertPtr(&$input, (void **) &$1, 0, 0) < 0) { /* Allow NULL from php for void* */ - if ((*$input)->type==IS_NULL) $1=0; + if (Z_ISNULL($input)) $1=0; else SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); } -} +%} /* Special case when void* is passed by reference so it can be made to point to opaque api structs */ @@ -160,9 +160,9 @@ { /* If they pass NULL by reference, make it into a void* This bit should go in arginit if arginit support init-ing scripting args */ - if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) { + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0) { /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */ - if (!((*$input)->type==IS_NULL && PZVAL_IS_REF(*$input))) { + if (!(Z_ISREF($input) && Z_ISNULL_P(Z_REFVAL($input)))) { /* wasn't a pre/ref/thing, OR anything like an int thing */ SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname."); } @@ -170,7 +170,7 @@ force=0; if (arg1==NULL) { #ifdef __cplusplus - ptr=new $*1_ltype; + ptr=new $*1_ltype(); #else ptr=($*1_ltype) calloc(1,sizeof($*1_ltype)); #endif @@ -181,11 +181,11 @@ } %typemap(argout) void **, void *& -{ +%{ if (force$argnum) { - SWIG_SetPointerZval( *$input, (void*) ptr$argnum, $*1_descriptor, 1); + SWIG_SetPointerZval(&$input, (void*) ptr$argnum, $*1_descriptor, 1); } -} +%} /* Typemap for output values */ @@ -199,35 +199,33 @@ unsigned char, bool, size_t -{ - ZVAL_LONG(return_value,$1); -} +%{ + RETVAL_LONG($1); +%} %typemap(out) enum SWIGTYPE -{ - ZVAL_LONG(return_value, (long)$1); -} +%{ + RETVAL_LONG((long)$1); +%} %typemap(out) long long %{ if ((long long)LONG_MIN <= $1 && $1 <= (long long)LONG_MAX) { - return_value->value.lval = (long)($1); - return_value->type = IS_LONG; + RETVAL_LONG((long)($1)); } else { char temp[256]; sprintf(temp, "%lld", (long long)$1); - ZVAL_STRING(return_value, temp, 1); + RETVAL_STRING(temp); } %} %typemap(out) unsigned long long %{ if ($1 <= (unsigned long long)LONG_MAX) { - return_value->value.lval = (long)($1); - return_value->type = IS_LONG; + RETVAL_LONG((long)($1)); } else { char temp[256]; sprintf(temp, "%llu", (unsigned long long)$1); - ZVAL_STRING(return_value, temp, 1); + RETVAL_STRING(temp); } %} @@ -241,40 +239,38 @@ const unsigned char &, const bool &, const size_t & -{ - ZVAL_LONG(return_value,*$1); -} +%{ + RETVAL_LONG(*$1); +%} %typemap(out) const enum SWIGTYPE & -{ - ZVAL_LONG(return_value, (long)*$1); -} +%{ + RETVAL_LONG((long)*$1); +%} %typemap(out) const enum SWIGTYPE && -{ - ZVAL_LONG(return_value, (long)*$1); -} +%{ + RETVAL_LONG((long)*$1); +%} %typemap(out) const long long & %{ if ((long long)LONG_MIN <= *$1 && *$1 <= (long long)LONG_MAX) { - return_value->value.lval = (long)(*$1); - return_value->type = IS_LONG; + RETVAL_LONG((long)(*$1)); } else { char temp[256]; sprintf(temp, "%lld", (long long)(*$1)); - ZVAL_STRING(return_value, temp, 1); + RETVAL_STRING(temp); } %} %typemap(out) const unsigned long long & %{ if (*$1 <= (unsigned long long)LONG_MAX) { - return_value->value.lval = (long)(*$1); - return_value->type = IS_LONG; + RETVAL_LONG((long)(*$1)); } else { char temp[256]; sprintf(temp, "%llu", (unsigned long long)(*$1)); - ZVAL_STRING(return_value, temp, 1); + RETVAL_STRING(temp); } %} @@ -288,85 +284,85 @@ unsigned char, size_t, enum SWIGTYPE -{ +%{ ZVAL_LONG($input,$1); -} +%} %typemap(directorin) enum SWIGTYPE -{ +%{ ZVAL_LONG($input, (long)$1_name); -} +%} %typemap(directorin) char *, char [] -{ +%{ if(!$1) { ZVAL_NULL($input); } else { - ZVAL_STRING($input, (char *)$1, 1); + ZVAL_STRING($input, (const char*)$1); } -} +%} %typemap(out) bool -{ - ZVAL_BOOL(return_value,($1)?1:0); -} +%{ + RETVAL_BOOL(($1) ? 1 : 0); +%} %typemap(out) const bool & -{ - ZVAL_BOOL(return_value,(*$1)?1:0); -} +%{ + RETVAL_BOOL((*$1) ? 1 : 0); +%} %typemap(directorin) bool -{ - ZVAL_BOOL($input,($1)?1:0); -} +%{ + ZVAL_BOOL($input, ($1) ? 1 : 0); +%} %typemap(out) float, double -{ - ZVAL_DOUBLE(return_value,$1); -} +%{ + RETVAL_DOUBLE($1); +%} %typemap(out) const float &, const double & -{ - ZVAL_DOUBLE(return_value,*$1); -} +%{ + RETVAL_DOUBLE(*$1); +%} %typemap(directorin) float, double -{ - ZVAL_DOUBLE($input,$1); -} +%{ + ZVAL_DOUBLE($input, $1); +%} %typemap(out) char -{ - ZVAL_STRINGL(return_value,&$1, 1, 1); -} +%{ + RETVAL_STRINGL(&$1, 1); +%} %typemap(out) const char & -{ - ZVAL_STRINGL(return_value,&*$1, 1, 1); -} +%{ + RETVAL_STRINGL(&*$1, 1); +%} %typemap(out) char *, char [] -{ - if(!$1) { - ZVAL_NULL(return_value); - } else { - ZVAL_STRING(return_value, (char *)$1, 1); - } -} +%{ + if (!$1) { + RETVAL_NULL(); + } else { + RETVAL_STRING((const char *)$1); + } +%} %typemap(out) char *& -{ - if(!*$1) { - ZVAL_NULL(return_value); - } else { - ZVAL_STRING(return_value, (char *)*$1, 1); - } -} +%{ + if (!*$1) { + RETVAL_NULL(); + } else { + RETVAL_STRING((const char *)*$1); + } +%} %typemap(out) SWIGTYPE *, SWIGTYPE [], @@ -393,16 +389,12 @@ { void * p = emalloc(sizeof($1)); memcpy(p, &$1, sizeof($1)); - zval * resource; - MAKE_STD_ZVAL(resource); - ZEND_REGISTER_RESOURCE(resource, p, swig_member_ptr); - - SWIG_SetPointerZval(return_value, (void *)&$1, $1_descriptor, $owner); + RETVAL_RES(zend_register_resource(p, swig_member_ptr)); } %typemap(in, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) { - void * p = (void*)zend_fetch_resource($input TSRMLS_CC, -1, SWIG_MEMBER_PTR, NULL, 1, swig_member_ptr); + void * p = (void*)zend_fetch_resource_ex(&$input, SWIG_MEMBER_PTR, swig_member_ptr); memcpy(&$1, p, sizeof($1)); } @@ -428,9 +420,9 @@ #endif %typemap(directorin) SWIGTYPE -{ - SWIG_SetPointerZval($input, SWIG_as_voidptr(&$1), $&1_descriptor, 2); -} +%{ + SWIG_SetPointerZval($input, SWIG_as_voidptr(new $1_ltype((const $1_ltype &)$1)), $&1_descriptor, 1|2); +%} %typemap(out) void ""; @@ -438,7 +430,7 @@ { int len = 0; while (len < $1_dim0 && $1[len]) ++len; - RETVAL_STRINGL($1, len, 1); + RETVAL_STRINGL($1, len); } // This typecheck does hard checking for proper argument type. If you want @@ -446,7 +438,13 @@ // it yourself before passing it (e.g. (string)4.7 or (int)"6"). %define %php_typecheck(_type,_prec,is) %typemap(typecheck,precedence=_prec) _type, const _type & - " $1 = (Z_TYPE_PP($input) == is); " + " $1 = (Z_TYPE($input) == is);" +%enddef + +// Like %php_typecheck but allows either of two values. +%define %php_typecheck2(_type,_prec,is1,is2) +%typemap(typecheck,precedence=_prec) _type, const _type & + " $1 = (Z_TYPE($input) == is1 || Z_TYPE($input) == is2);" %enddef %php_typecheck(int,SWIG_TYPECHECK_INTEGER,IS_LONG) @@ -461,18 +459,18 @@ %php_typecheck(unsigned char,SWIG_TYPECHECK_UINT8,IS_LONG) %php_typecheck(size_t,SWIG_TYPECHECK_SIZE,IS_LONG) %php_typecheck(enum SWIGTYPE,SWIG_TYPECHECK_INTEGER,IS_LONG) -%php_typecheck(bool,SWIG_TYPECHECK_BOOL,IS_BOOL) +%php_typecheck2(bool,SWIG_TYPECHECK_BOOL,IS_TRUE,IS_FALSE) %php_typecheck(float,SWIG_TYPECHECK_FLOAT,IS_DOUBLE) %php_typecheck(double,SWIG_TYPECHECK_DOUBLE,IS_DOUBLE) %php_typecheck(char,SWIG_TYPECHECK_CHAR,IS_STRING) %typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) char *, char *&, char [] - " $1 = (Z_TYPE_PP($input) == IS_STRING); " + " $1 = (Z_TYPE($input) == IS_STRING); " %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { void *tmp; - _v = (SWIG_ConvertPtr(*$input, (void **)&tmp, $&1_descriptor, 0) >= 0); + _v = (SWIG_ConvertPtr(&$input, (void **)&tmp, $&1_descriptor, 0) >= 0); } %typecheck(SWIG_TYPECHECK_POINTER) @@ -483,19 +481,19 @@ SWIGTYPE *const& { void *tmp; - _v = (SWIG_ConvertPtr(*$input, (void**)&tmp, $1_descriptor, 0) >= 0); + _v = (SWIG_ConvertPtr(&$input, (void**)&tmp, $1_descriptor, 0) >= 0); } %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *const& { void *tmp; - _v = (SWIG_ConvertPtr(*$input, (void**)&tmp, $*1_descriptor, 0) >= 0); + _v = (SWIG_ConvertPtr(&$input, (void**)&tmp, $*1_descriptor, 0) >= 0); } %typecheck(SWIG_TYPECHECK_VOIDPTR) void * { void *tmp; - _v = (SWIG_ConvertPtr(*$input, (void**)&tmp, 0, 0) >= 0); + _v = (SWIG_ConvertPtr(&$input, (void**)&tmp, 0, 0) >= 0); } /* Exception handling */ @@ -505,19 +503,19 @@ short, unsigned int, unsigned long, - unsigned short { - zend_throw_exception(NULL, const_cast("C++ $1_type exception thrown"), $1 TSRMLS_CC); + unsigned short %{ + zend_throw_exception(NULL, "C++ $1_type exception thrown", $1); return; -} +%} %typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ (void)$1; - zend_throw_exception(NULL, const_cast("C++ $1_type exception thrown"), 0 TSRMLS_CC); + zend_throw_exception(NULL, "C++ $1_type exception thrown", 0); return; %} %typemap(throws) char * %{ - zend_throw_exception(NULL, const_cast($1), 0 TSRMLS_CC); + zend_throw_exception(NULL, $1, 0); return; %} diff --git a/Lib/php/phpinit.swg b/Lib/php/phpinit.swg index 6e5cc29d2..1f252d1ac 100644 --- a/Lib/php/phpinit.swg +++ b/Lib/php/phpinit.swg @@ -6,20 +6,20 @@ %insert(init) "swiginit.swg" %init %{ - SWIG_php_minit { +SWIG_php_minit { SWIG_InitializeModule(0); %} -%fragment("swig_php_init_member_ptr2", "header") { -#define SWIG_MEMBER_PTR ((char*)"CLASS::*") +%fragment("swig_php_init_member_ptr2", "header") %{ +#define SWIG_MEMBER_PTR "CLASS::*" -static void swig_member_ptr_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { - efree(rsrc->ptr); +static void swig_member_ptr_dtor(zend_resource *res) { + efree(res->ptr); } static int swig_member_ptr = 0; -} +%} -%fragment("swig_php_init_member_ptr", "init", fragment="swig_php_init_member_ptr2") { +%fragment("swig_php_init_member_ptr", "init", fragment="swig_php_init_member_ptr2") %{ swig_member_ptr = zend_register_list_destructors_ex(swig_member_ptr_dtor, NULL, SWIG_MEMBER_PTR, module_number); -} +%} diff --git a/Lib/php/phpkw.swg b/Lib/php/phpkw.swg index 36e535f52..db451f957 100644 --- a/Lib/php/phpkw.swg +++ b/Lib/php/phpkw.swg @@ -661,6 +661,21 @@ PHPCN(generator); // As of PHP 5.5 PHPCN(self); PHPCN(static); PHPCN(parent); +/* http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.classes */ +PHPCN(bool); // As of PHP 7.0 +PHPCN(int); // As of PHP 7.0 +PHPCN(float); // As of PHP 7.0 +PHPCN(string); // As of PHP 7.0 +PHPCN(NULL); // As of PHP 7.0 +PHPCN(TRUE); // As of PHP 7.0 +PHPCN(FALSE); // As of PHP 7.0 +PHPCN(resource); // As of PHP 7.0 (currently works but reserved) +PHPCN(object); // As of PHP 7.0 (currently works but reserved) +PHPCN(mixed); // As of PHP 7.0 (currently works but reserved) +PHPCN(numeric); // As of PHP 7.0 (currently works but reserved) +/* http://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.invalid-class-names */ +PHPCN(iterable); // As of PHP 7.1 +PHPCN(void); // As of PHP 7.1 /* From extensions (which of these are actually predefined depends which * extensions are loaded by default). */ PHPCN(xmlwriter); diff --git a/Lib/php/phppointers.i b/Lib/php/phppointers.i index e50ada7ac..d79697b5e 100644 --- a/Lib/php/phppointers.i +++ b/Lib/php/phppointers.i @@ -3,19 +3,23 @@ TYPE &REF ($*1_ltype tmp) %{ /* First Check for SWIG wrapped type */ - if ( ZVAL_IS_NULL( *$input ) ) { + if (Z_ISNULL($input)) { $1 = 0; - } else if ( PZVAL_IS_REF( *$input ) ) { + } else if (Z_ISREF($input)) { /* Not swig wrapped type, so we check if it's a PHP reference type */ - CONVERT_IN( tmp, $*1_ltype, $input ); + CONVERT_IN(tmp, $*1_ltype, $input); $1 = &tmp; } else { - SWIG_PHP_Error( E_ERROR, SWIG_PHP_Arg_Error_Msg($argnum, Expected a reference) ); + SWIG_PHP_Error(E_ERROR, SWIG_PHP_Arg_Error_Msg($argnum, Expected a reference)); } %} %typemap(argout) TYPE *REF, TYPE &REF - "CONVERT_OUT(*$input, tmp$argnum );"; +%{ + if (Z_ISREF($input)) { + CONVERT_OUT(Z_REFVAL($input), tmp$argnum); + } +%} %enddef %pass_by_ref( size_t, CONVERT_INT_IN, ZVAL_LONG ); diff --git a/Lib/php/phprun.swg b/Lib/php/phprun.swg index 00d8bc560..c341e6704 100644 --- a/Lib/php/phprun.swg +++ b/Lib/php/phprun.swg @@ -11,61 +11,31 @@ extern "C" { #include "zend_API.h" #include "zend_exceptions.h" #include "php.h" + +#if PHP_MAJOR_VERSION != 7 +# error These bindings need PHP7 - to generate PHP5 bindings use: swig -php5 +#endif + #include "ext/standard/php_string.h" #include /* for abort(), used in generated code. */ -#ifdef ZEND_RAW_FENTRY -/* ZEND_RAW_FENTRY was added somewhere between 5.2.0 and 5.2.3 */ -# define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_RAW_FENTRY((char*)#ZN, N, A, 0) -#else -/* This causes warnings from GCC >= 4.2 (assigning a string literal to char*). - * But this seems to be unavoidable without directly assuming knowledge of - * the structure, which changed between PHP4 and PHP5. */ -# define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_NAMED_FE(ZN, N, A) -#endif +/* This indirection is to work around const correctness issues in older PHP. + * FIXME: Remove for PHP7? Or might user code be using it? */ +#define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_NAMED_FE(ZN, N, A) -#ifndef Z_SET_ISREF_P -/* For PHP < 5.3 */ -# define Z_SET_ISREF_P(z) (z)->is_ref = 1 -#endif -#ifndef Z_SET_REFCOUNT_P -/* For PHP < 5.3 */ -# define Z_SET_REFCOUNT_P(z, rc) (z)->refcount = (rc) -#endif - -#define SWIG_LONG_CONSTANT(N, V) zend_register_long_constant((char*)#N, sizeof(#N), V, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC) -#define SWIG_DOUBLE_CONSTANT(N, V) zend_register_double_constant((char*)#N, sizeof(#N), V, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC) -#define SWIG_STRING_CONSTANT(N, V) zend_register_stringl_constant((char*)#N, sizeof(#N), (char*)(V), strlen(V), CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC) +#define SWIG_BOOL_CONSTANT(N, V) REGISTER_BOOL_CONSTANT(#N, V, CONST_CS | CONST_PERSISTENT) +#define SWIG_LONG_CONSTANT(N, V) REGISTER_LONG_CONSTANT(#N, V, CONST_CS | CONST_PERSISTENT) +#define SWIG_DOUBLE_CONSTANT(N, V) REGISTER_DOUBLE_CONSTANT(#N, V, CONST_CS | CONST_PERSISTENT) +#define SWIG_STRING_CONSTANT(N, V) REGISTER_STRING_CONSTANT(#N, (char*)V, CONST_CS | CONST_PERSISTENT) #define SWIG_CHAR_CONSTANT(N, V) do {\ - static char swig_char = (V);\ - zend_register_stringl_constant((char*)#N, sizeof(#N), &swig_char, 1, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC);\ + char swig_char = (V);\ + REGISTER_STRINGL_CONSTANT(#N, &swig_char, 1, CONST_CS | CONST_PERSISTENT);\ } while (0) -/* These TSRMLS_ stuff should already be defined now, but with older php under - redhat are not... */ -#ifndef TSRMLS_D -#define TSRMLS_D -#endif -#ifndef TSRMLS_DC -#define TSRMLS_DC -#endif -#ifndef TSRMLS_C -#define TSRMLS_C -#endif -#ifndef TSRMLS_CC -#define TSRMLS_CC -#endif - #ifdef __cplusplus } #endif -/* But in fact SWIG_ConvertPtr is the native interface for getting typed - pointer values out of zvals. We need the TSRMLS_ macros for when we - make PHP type calls later as we handle php resources */ -#define SWIG_ConvertPtr(obj,pp,type,flags) SWIG_ZTS_ConvertPtr(obj,pp,type,flags TSRMLS_CC) - - #define SWIG_fail goto fail static const char *default_error_msg = "Unknown error occurred"; @@ -89,14 +59,10 @@ typedef struct { int newobject; } swig_object_wrapper; -/* empty zend destructor for types without one */ -static ZEND_RSRC_DTOR_FUNC(SWIG_landfill) { (void)rsrc; } - -#define SWIG_SetPointerZval(a,b,c,d) SWIG_ZTS_SetPointerZval(a,b,c,d TSRMLS_CC) #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) static void -SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject TSRMLS_DC) { +SWIG_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject) { /* * First test for Null pointers. Return those as PHP native NULL */ @@ -113,19 +79,19 @@ SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject value->newobject=(newobject & 1); if ((newobject & 2) == 0) { /* Just register the pointer as a resource. */ - ZEND_REGISTER_RESOURCE(z, value, *(int *)(type->clientdata)); + ZVAL_RES(z, zend_register_resource(value, *(int *)(type->clientdata))); } else { /* * Wrap the resource in an object, the resource will be accessible * via the "_cPtr" member. This is currently only used by * directorin typemaps. */ - zval *resource; - zend_class_entry **ce = NULL; + zval resource; + zend_class_entry *ce = NULL; const char *type_name = type->name+3; /* +3 so: _p_Foo -> Foo */ size_t type_name_len; - int result; const char * p; + HashTable * ht; /* Namespace__Foo -> Foo */ /* FIXME: ugly and goes wrong for classes with __ in their names. */ @@ -134,26 +100,27 @@ SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject } type_name_len = strlen(type_name); - MAKE_STD_ZVAL(resource); - ZEND_REGISTER_RESOURCE(resource, value, *(int *)(type->clientdata)); + ZVAL_RES(&resource, zend_register_resource(value, *(int *)(type->clientdata))); if (SWIG_PREFIX_LEN > 0) { - char * classname = (char*)emalloc(SWIG_PREFIX_LEN + type_name_len + 1); - strcpy(classname, SWIG_PREFIX); - strcpy(classname + SWIG_PREFIX_LEN, type_name); - result = zend_lookup_class(classname, SWIG_PREFIX_LEN + type_name_len, &ce TSRMLS_CC); - efree(classname); + zend_string * classname = zend_string_alloc(SWIG_PREFIX_LEN + type_name_len, 0); + memcpy(classname->val, SWIG_PREFIX, SWIG_PREFIX_LEN); + memcpy(classname->val + SWIG_PREFIX_LEN, type_name, type_name_len); + ce = zend_lookup_class(classname); + zend_string_release(classname); } else { - result = zend_lookup_class((char *)type_name, type_name_len, &ce TSRMLS_CC); + zend_string * classname = zend_string_init(type_name, type_name_len, 0); + ce = zend_lookup_class(classname); + zend_string_release(classname); } - if (result != SUCCESS) { + if (ce == NULL) { /* class does not exist */ - object_init(z); - } else { - object_init_ex(z, *ce); + ce = zend_standard_class_def; } - Z_SET_REFCOUNT_P(z, 1); - Z_SET_ISREF_P(z); - zend_hash_update(HASH_OF(z), (char*)"_cPtr", sizeof("_cPtr"), (void*)&resource, sizeof(zval*), NULL); + + ALLOC_HASHTABLE(ht); + zend_hash_init(ht, 1, NULL, NULL, 0); + zend_hash_str_update(ht, "_cPtr", sizeof("_cPtr") - 1, &resource); + object_and_properties_init(z, ce, ht); } return; } @@ -169,11 +136,11 @@ SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject instance of a resource of the type id, so we have to pass type_name as well. The two functions which might call this are: - SWIG_ZTS_ConvertResourcePtr which gets the type name from the resource + SWIG_ConvertResourcePtr which gets the type name from the resource and the registered zend destructors for which we have one per type each with the type name hard wired in. */ static void * -SWIG_ZTS_ConvertResourceData(void * p, const char *type_name, swig_type_info *ty TSRMLS_DC) { +SWIG_ConvertResourceData(void * p, const char *type_name, swig_type_info *ty) { swig_cast_info *tc; void *result = 0; @@ -200,48 +167,53 @@ SWIG_ZTS_ConvertResourceData(void * p, const char *type_name, swig_type_info *ty /* This function returns a pointer of type ty by extracting the pointer and type info from the resource in z. z must be a resource. If it fails, NULL is returned. - It uses SWIG_ZTS_ConvertResourceData to do the real work. */ + It uses SWIG_ConvertResourceData to do the real work. */ static void * -SWIG_ZTS_ConvertResourcePtr(zval *z, swig_type_info *ty, int flags TSRMLS_DC) { +SWIG_ConvertResourcePtr(zval *z, swig_type_info *ty, int flags) { swig_object_wrapper *value; void *p; - int type; const char *type_name; - value = (swig_object_wrapper *) zend_list_find(z->value.lval, &type); - if (type==-1) return NULL; + if (Z_RES_TYPE_P(z) == -1) return NULL; + value = (swig_object_wrapper *) Z_RES_VAL_P(z); if (flags & SWIG_POINTER_DISOWN) { value->newobject = 0; } p = value->ptr; - type_name=zend_rsrc_list_get_rsrc_type(z->value.lval TSRMLS_CC); + type_name=zend_rsrc_list_get_rsrc_type(Z_RES_P(z)); - return SWIG_ZTS_ConvertResourceData(p, type_name, ty TSRMLS_CC); + return SWIG_ConvertResourceData(p, type_name, ty); } /* We allow passing of a RESOURCE pointing to the object or an OBJECT whose _cPtr is a resource pointing to the object */ static int -SWIG_ZTS_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags TSRMLS_DC) { +SWIG_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags) { if (z == NULL) { *ptr = 0; return 0; } - switch (z->type) { + switch (Z_TYPE_P(z)) { case IS_OBJECT: { - zval ** _cPtr; - if (zend_hash_find(HASH_OF(z),(char*)"_cPtr",sizeof("_cPtr"),(void**)&_cPtr)==SUCCESS) { - if ((*_cPtr)->type==IS_RESOURCE) { - *ptr = SWIG_ZTS_ConvertResourcePtr(*_cPtr, ty, flags TSRMLS_CC); - return (*ptr == NULL ? -1 : 0); - } + HashTable * ht = Z_OBJ_HT_P(z)->get_properties(z); + if (ht) { + zval * _cPtr = zend_hash_str_find(ht, "_cPtr", sizeof("_cPtr") - 1); + if (_cPtr) { + if (Z_TYPE_P(_cPtr) == IS_INDIRECT) { + _cPtr = Z_INDIRECT_P(_cPtr); + } + if (Z_TYPE_P(_cPtr) == IS_RESOURCE) { + *ptr = SWIG_ConvertResourcePtr(_cPtr, ty, flags); + return (*ptr == NULL ? -1 : 0); + } + } } break; } case IS_RESOURCE: - *ptr = SWIG_ZTS_ConvertResourcePtr(z, ty, flags TSRMLS_CC); + *ptr = SWIG_ConvertResourcePtr(z, ty, flags); return (*ptr == NULL ? -1 : 0); case IS_NULL: *ptr = 0; @@ -253,22 +225,15 @@ SWIG_ZTS_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags TSRMLS_DC static char const_name[] = "swig_runtime_data_type_pointer"; static swig_module_info *SWIG_Php_GetModule() { - zval *pointer; - swig_module_info *ret = 0; - TSRMLS_FETCH(); - - MAKE_STD_ZVAL(pointer); - - if (zend_get_constant(const_name, sizeof(const_name) - 1, pointer TSRMLS_CC)) { - if (pointer->type == IS_LONG) { - ret = (swig_module_info *) pointer->value.lval; + zval *pointer = zend_get_constant_str(const_name, sizeof(const_name) - 1); + if (pointer) { + if (Z_TYPE_P(pointer) == IS_LONG) { + return (swig_module_info *) pointer->value.lval; } } - FREE_ZVAL(pointer); - return ret; + return NULL; } static void SWIG_Php_SetModule(swig_module_info *pointer) { - TSRMLS_FETCH(); REGISTER_MAIN_LONG_CONSTANT(const_name, (long) pointer, 0); } diff --git a/Lib/php/std_string.i b/Lib/php/std_string.i index aaa5dc9cd..b55751f07 100644 --- a/Lib/php/std_string.i +++ b/Lib/php/std_string.i @@ -24,53 +24,68 @@ namespace std { class string; %typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) string, const string& %{ - $1 = ( Z_TYPE_PP($input) == IS_STRING ) ? 1 : 0; + $1 = (Z_TYPE($input) == IS_STRING) ? 1 : 0; %} %typemap(in) string %{ - convert_to_string_ex($input); - $1.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input)); + convert_to_string(&$input); + $1.assign(Z_STRVAL($input), Z_STRLEN($input)); %} %typemap(directorout) string %{ - convert_to_string_ex(&$input); + if (!EG(exception)) { + convert_to_string($input); $result.assign(Z_STRVAL_P($input), Z_STRLEN_P($input)); + } %} %typemap(out) string %{ - ZVAL_STRINGL($result, const_cast($1.data()), $1.size(), 1); + ZVAL_STRINGL($result, $1.data(), $1.size()); %} %typemap(directorin) string, const string& %{ - ZVAL_STRINGL($input, const_cast($1.data()), $1.size(), 1); + ZVAL_STRINGL($input, $1.data(), $1.size()); %} %typemap(out) const string & %{ - ZVAL_STRINGL($result, const_cast($1->data()), $1->size(), 1); + ZVAL_STRINGL($result, $1->data(), $1->size()); %} %typemap(throws) string, const string& %{ - zend_throw_exception(NULL, const_cast($1.c_str()), 0 TSRMLS_CC); + zend_throw_exception(NULL, $1.c_str(), 0); return; %} + %typemap(in) const string & ($*1_ltype temp) %{ + convert_to_string(&$input); + temp.assign(Z_STRVAL($input), Z_STRLEN($input)); + $1 = &temp; + %} + /* These next two handle a function which takes a non-const reference to * a std::string and modifies the string. */ - %typemap(in) string & ($*1_ltype temp) %{ - convert_to_string_ex($input); - temp.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input)); - $1 = &temp; + %typemap(in,byref=1) string & ($*1_ltype temp) %{ + { + zval * p = Z_ISREF($input) ? Z_REFVAL($input) : &$input; + convert_to_string(p); + temp.assign(Z_STRVAL_P(p), Z_STRLEN_P(p)); + $1 = &temp; + } %} %typemap(directorout) string & ($*1_ltype *temp) %{ - convert_to_string_ex(&$input); + if (!EG(exception)) { + convert_to_string($input); temp = new $*1_ltype(Z_STRVAL_P($input), Z_STRLEN_P($input)); swig_acquire_ownership(temp); $result = temp; + } %} %typemap(argout) string & %{ - ZVAL_STRINGL(*($input), const_cast($1->data()), $1->size(), 1); + if (Z_ISREF($input)) { + ZVAL_STRINGL(Z_REFVAL($input), $1->data(), $1->size()); + } %} /* SWIG will apply the non-const typemap above to const string& without diff --git a/Lib/php/typemaps.i b/Lib/php/typemaps.i index ca49ec327..c248a588e 100644 --- a/Lib/php/typemaps.i +++ b/Lib/php/typemaps.i @@ -27,87 +27,77 @@ %define BOOL_TYPEMAP(TYPE) %typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) %{ - convert_to_boolean_ex($input); - temp = Z_LVAL_PP($input) ? true : false; + convert_to_boolean(&$input); + temp = (Z_TYPE($input) == IS_TRUE); $1 = &temp; %} %typemap(argout) TYPE *INPUT, TYPE &INPUT ""; %typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp), TYPE &OUTPUT(TYPE temp) "$1 = &temp;"; %typemap(argout,fragment="t_output_helper") TYPE *OUTPUT, TYPE &OUTPUT { - zval *o; - MAKE_STD_ZVAL(o); - ZVAL_BOOL(o,temp$argnum); - t_output_helper( &$result, o TSRMLS_CC ); + zval o; + ZVAL_BOOL(&o, temp$argnum); + t_output_helper($result, &o); } %typemap(in) TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) %{ - convert_to_boolean_ex($input); - lvalue = (*$input)->value.lval ? true : false; + convert_to_boolean($input); + lvalue = (Z_TYPE_P($input) == IS_TRUE); $1 = &lvalue; %} %typemap(argout) TYPE *REFERENCE, TYPE &REFERENCE %{ - (*$arg)->value.lval = lvalue$argnum ? true : false; - (*$arg)->type = IS_BOOL; + ZVAL_BOOL(&$arg, lvalue$argnum ? true : false); %} %enddef %define DOUBLE_TYPEMAP(TYPE) %typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) %{ - convert_to_double_ex($input); - temp = (TYPE) Z_DVAL_PP($input); + temp = (TYPE) zval_get_double(&$input); $1 = &temp; %} %typemap(argout) TYPE *INPUT, TYPE &INPUT ""; %typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp), TYPE &OUTPUT(TYPE temp) "$1 = &temp;"; %typemap(argout,fragment="t_output_helper") TYPE *OUTPUT, TYPE &OUTPUT { - zval *o; - MAKE_STD_ZVAL(o); - ZVAL_DOUBLE(o,temp$argnum); - t_output_helper( &$result, o TSRMLS_CC ); + zval o; + ZVAL_DOUBLE(&o, temp$argnum); + t_output_helper($result, &o); } %typemap(in) TYPE *REFERENCE (TYPE dvalue), TYPE &REFERENCE (TYPE dvalue) %{ - convert_to_double_ex($input); - dvalue = (TYPE) (*$input)->value.dval; + dvalue = (TYPE) zval_get_double(&$input); $1 = &dvalue; %} %typemap(argout) TYPE *REFERENCE, TYPE &REFERENCE %{ - $1->value.dval = (double)(lvalue$argnum); - $1->type = IS_DOUBLE; + ZVAL_DOUBLE(&$arg, (double)(lvalue$argnum)); %} %enddef %define INT_TYPEMAP(TYPE) %typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) %{ - convert_to_long_ex($input); - temp = (TYPE) Z_LVAL_PP($input); + temp = (TYPE) zval_get_long(&$input); $1 = &temp; %} %typemap(argout) TYPE *INPUT, TYPE &INPUT ""; %typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp), TYPE &OUTPUT(TYPE temp) "$1 = &temp;"; %typemap(argout,fragment="t_output_helper") TYPE *OUTPUT, TYPE &OUTPUT { - zval *o; - MAKE_STD_ZVAL(o); - ZVAL_LONG(o,temp$argnum); - t_output_helper( &$result, o TSRMLS_CC ); + zval o; + ZVAL_LONG(&o, temp$argnum); + t_output_helper($result, &o); } %typemap(in) TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) %{ - convert_to_long_ex($input); - lvalue = (TYPE) (*$input)->value.lval; + lvalue = (TYPE) zval_get_long(&$input); $1 = &lvalue; %} %typemap(argout) TYPE *REFERENCE, TYPE &REFERENCE %{ - (*$arg)->value.lval = (long)(lvalue$argnum); - (*$arg)->type = IS_LONG; + ZVAL_LONG(&$arg, (long)(lvalue$argnum)); %} %enddef @@ -128,16 +118,15 @@ INT_TYPEMAP(signed char); INT_TYPEMAP(long long); %typemap(argout,fragment="t_output_helper") long long *OUTPUT { - zval *o; - MAKE_STD_ZVAL(o); + zval o; if ((long long)LONG_MIN <= temp$argnum && temp$argnum <= (long long)LONG_MAX) { - ZVAL_LONG(o, temp$argnum); + ZVAL_LONG(&o, (long)temp$argnum); } else { char temp[256]; sprintf(temp, "%lld", (long long)temp$argnum); - ZVAL_STRING(o, temp, 1); + ZVAL_STRING(&o, temp); } - t_output_helper( &$result, o TSRMLS_CC ); + t_output_helper($result, &o); } %typemap(in) TYPE *REFERENCE (long long lvalue) %{ @@ -147,38 +136,35 @@ INT_TYPEMAP(long long); %typemap(argout) long long *REFERENCE %{ if ((long long)LONG_MIN <= lvalue$argnum && lvalue$argnum <= (long long)LONG_MAX) { - (*$arg)->value.lval = (long)(lvalue$argnum); - (*$arg)->type = IS_LONG; + ZVAL_LONG(&$arg, (long)temp$argnum); } else { char temp[256]; sprintf(temp, "%lld", (long long)lvalue$argnum); - ZVAL_STRING((*$arg), temp, 1); + ZVAL_STRING(&$arg, temp); } %} %typemap(argout) long long &OUTPUT %{ if ((long long)LONG_MIN <= *arg$argnum && *arg$argnum <= (long long)LONG_MAX) { - ($result)->value.lval = (long)(*arg$argnum); - ($result)->type = IS_LONG; + ZVAL_LONG($result, (long)(*arg$argnum)); } else { char temp[256]; sprintf(temp, "%lld", (long long)(*arg$argnum)); - ZVAL_STRING($result, temp, 1); + ZVAL_STRING($result, temp); } %} INT_TYPEMAP(unsigned long long); %typemap(argout,fragment="t_output_helper") unsigned long long *OUTPUT { - zval *o; - MAKE_STD_ZVAL(o); + zval o; if (temp$argnum <= (unsigned long long)LONG_MAX) { - ZVAL_LONG(o, temp$argnum); + ZVAL_LONG(&o, temp$argnum); } else { char temp[256]; sprintf(temp, "%llu", (unsigned long long)temp$argnum); - ZVAL_STRING(o, temp, 1); + ZVAL_STRING(&o, temp); } - t_output_helper( &$result, o TSRMLS_CC ); + t_output_helper($result, &o); } %typemap(in) TYPE *REFERENCE (unsigned long long lvalue) %{ @@ -188,23 +174,21 @@ INT_TYPEMAP(unsigned long long); %typemap(argout) unsigned long long *REFERENCE %{ if (lvalue$argnum <= (unsigned long long)LONG_MAX) { - (*$arg)->value.lval = (long)(lvalue$argnum); - (*$arg)->type = IS_LONG; + ZVAL_LONG($arg, (long)(lvalue$argnum)); } else { char temp[256]; sprintf(temp, "%llu", (unsigned long long)lvalue$argnum); - ZVAL_STRING((*$arg), temp, 1); + ZVAL_STRING((*$arg), temp); } %} %typemap(argout) unsigned long long &OUTPUT %{ if (*arg$argnum <= (unsigned long long)LONG_MAX) { - ($result)->value.lval = (long)(*arg$argnum); - ($result)->type = IS_LONG; + ZVAL_LONG($result, (long)(*arg$argnum)); } else { char temp[256]; sprintf(temp, "%llu", (unsigned long long)(*arg$argnum)); - ZVAL_STRING($result, temp, 1); + ZVAL_STRING($result, temp); } %} @@ -270,18 +254,17 @@ INT_TYPEMAP(unsigned long long); %typemap(in) char INPUT[ANY] ( char temp[$1_dim0] ) %{ - convert_to_string_ex($input); - strncpy(temp,Z_LVAL_PP($input),$1_dim0); + convert_to_string(&$input); + strncpy(temp, Z_STRVAL($input), $1_dim0); $1 = temp; %} %typemap(in,numinputs=0) char OUTPUT[ANY] ( char temp[$1_dim0] ) "$1 = temp;"; %typemap(argout,fragment="t_output_helper") char OUTPUT[ANY] { - zval *o; - MAKE_STD_ZVAL(o); - ZVAL_STRINGL(o,temp$argnum,$1_dim0); - t_output_helper( &$result, o TSRMLS_CC ); + zval o; + ZVAL_STRINGL(&o, temp$argnum, $1_dim0); + t_output_helper($result, &o); } %typemap(in,numinputs=0) void **OUTPUT (int force), @@ -289,9 +272,9 @@ INT_TYPEMAP(unsigned long long); %{ /* If they pass NULL by reference, make it into a void* This bit should go in arginit if arginit support init-ing scripting args */ - if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) { + if (SWIG_ConvertPtr(&$input, (void **) &$1, $1_descriptor, 0) < 0) { /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */ - if (!((*$input)->type==IS_NULL && PZVAL_IS_REF(*$input))) { + if (!(Z_ISREF($input) && Z_ISNULL_P(Z_REFVAL($input)))) { /* wasn't a pre/ref/thing, OR anything like an int thing */ SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname."); } @@ -299,7 +282,7 @@ INT_TYPEMAP(unsigned long long); force=0; if (arg1==NULL) { #ifdef __cplusplus - ptr=new $*1_ltype; + ptr=new $*1_ltype(); #else ptr=($*1_ltype) calloc(1,sizeof($*1_ltype)); #endif @@ -313,7 +296,7 @@ INT_TYPEMAP(unsigned long long); void *&OUTPUT %{ if (force$argnum) { /* pass back arg$argnum through params ($arg) if we can */ - if (!PZVAL_IS_REF(*$arg)) { + if (!Z_ISREF($arg)) { SWIG_PHP_Error(E_WARNING, "Parameter $argnum of $symname wasn't passed by reference"); } else { SWIG_SetPointerZval(*$arg, (void *) ptr$argnum, $*1_descriptor, 1); diff --git a/Lib/php/utils.i b/Lib/php/utils.i index 408a3b366..8581646a2 100644 --- a/Lib/php/utils.i +++ b/Lib/php/utils.i @@ -1,70 +1,65 @@ %define CONVERT_BOOL_IN(lvar,t,invar) - convert_to_boolean_ex(invar); - lvar = (t) Z_LVAL_PP(invar); + lvar = (t) zval_is_true(&invar); %enddef %define CONVERT_INT_IN(lvar,t,invar) - convert_to_long_ex(invar); - lvar = (t) Z_LVAL_PP(invar); + lvar = (t) zval_get_long(&invar); %enddef %define CONVERT_LONG_LONG_IN(lvar,t,invar) - switch ((*(invar))->type) { + switch (Z_TYPE(invar)) { case IS_DOUBLE: - lvar = (t) (*(invar))->value.dval; + lvar = (t) Z_DVAL(invar); break; case IS_STRING: { char * endptr; errno = 0; - lvar = (t) strtoll((*(invar))->value.str.val, &endptr, 10); + lvar = (t) strtoll(Z_STRVAL(invar), &endptr, 10); if (*endptr && !errno) break; /* FALL THRU */ } default: - convert_to_long_ex(invar); - lvar = (t) (*(invar))->value.lval; + lvar = (t) zval_get_long(&invar); } %enddef %define CONVERT_UNSIGNED_LONG_LONG_IN(lvar,t,invar) - switch ((*(invar))->type) { + switch (Z_TYPE(invar)) { case IS_DOUBLE: - lvar = (t) (*(invar))->value.dval; + lvar = (t) Z_DVAL(invar); break; case IS_STRING: { char * endptr; errno = 0; - lvar = (t) strtoull((*(invar))->value.str.val, &endptr, 10); + lvar = (t) strtoull(Z_STRVAL(invar), &endptr, 10); if (*endptr && !errno) break; /* FALL THRU */ } default: - convert_to_long_ex(invar); - lvar = (t) (*(invar))->value.lval; + lvar = (t) zval_get_long(&invar); } %enddef %define CONVERT_INT_OUT(lvar,invar) - lvar = (t) Z_LVAL_PP(invar); + lvar = (t) zval_get_long(&invar); %enddef %define CONVERT_FLOAT_IN(lvar,t,invar) - convert_to_double_ex(invar); - lvar = (t) Z_DVAL_PP(invar); + lvar = (t) zval_get_double(&invar); %enddef %define CONVERT_CHAR_IN(lvar,t,invar) - convert_to_string_ex(invar); - lvar = (t) *Z_STRVAL_PP(invar); + convert_to_string(&invar); + lvar = (t) Z_STRVAL(invar)[0]; %enddef %define CONVERT_STRING_IN(lvar,t,invar) - if ((*invar)->type==IS_NULL) { + if (Z_ISNULL(invar)) { lvar = (t) 0; } else { - convert_to_string_ex(invar); - lvar = (t) Z_STRVAL_PP(invar); + convert_to_string(&invar); + lvar = (t) Z_STRVAL(invar); } %enddef @@ -80,35 +75,42 @@ %} %typemap(directorout) TYPE %{ - CONVERT_IN($result,$1_ltype,&$input); + if (!EG(exception)) { + CONVERT_IN($result, $1_ltype, *$input); + } else { + typedef $1_ltype swig_result_typedef; + $result = swig_result_typedef(); + } %} %typemap(directorout) const TYPE & ($*1_ltype temp) %{ - CONVERT_IN(temp,$*1_ltype,&$input); + if (!EG(exception)) { + CONVERT_IN(temp, $*1_ltype, *$input); + } else { + typedef $*1_ltype swig_result_typedef; + temp = swig_result_typedef(); + } $result = &temp; %} %enddef %fragment("t_output_helper","header") %{ static void -t_output_helper(zval **target, zval *o TSRMLS_DC) { - zval *tmp; - if ( (*target)->type == IS_ARRAY ) { +t_output_helper(zval *target, zval *o) { + zval tmp; + if (Z_TYPE_P(target) == IS_ARRAY) { /* it's already an array, just append */ - add_next_index_zval( *target, o ); + add_next_index_zval(target, o); return; } - if ( (*target)->type == IS_NULL ) { - REPLACE_ZVAL_VALUE(target,o,1); - FREE_ZVAL(o); + if (Z_TYPE_P(target) == IS_NULL) { + /* NULL isn't refcounted */ + ZVAL_COPY_VALUE(target, o); return; } - ALLOC_INIT_ZVAL(tmp); - *tmp = **target; - zval_copy_ctor(tmp); - array_init(*target); - add_next_index_zval( *target, tmp); - add_next_index_zval( *target, o); - + ZVAL_DUP(&tmp, target); + array_init(target); + add_next_index_zval(target, &tmp); + add_next_index_zval(target, o); } %} diff --git a/Lib/php5/const.i b/Lib/php5/const.i new file mode 100644 index 000000000..061ba99a2 --- /dev/null +++ b/Lib/php5/const.i @@ -0,0 +1,51 @@ +/* ----------------------------------------------------------------------------- + * const.i + * + * Typemaps for constants + * ----------------------------------------------------------------------------- */ + +%typemap(consttab) int, + unsigned int, + short, + unsigned short, + long, + unsigned long, + unsigned char, + signed char, + bool, + enum SWIGTYPE + "SWIG_LONG_CONSTANT($symname, ($1_type)$value);"; + +%typemap(consttab) float, + double + "SWIG_DOUBLE_CONSTANT($symname, $value);"; + +%typemap(consttab) char + "SWIG_CHAR_CONSTANT($symname, $value);"; + +%typemap(consttab) char *, + const char *, + char [], + const char [] + "SWIG_STRING_CONSTANT($symname, $value);"; + +%typemap(consttab) SWIGTYPE *, + SWIGTYPE &, + SWIGTYPE &&, + SWIGTYPE [] { + zval *z_var; + zend_constant c; + size_t len = sizeof("$symname") - 1; + MAKE_STD_ZVAL(z_var); + SWIG_SetPointerZval(z_var, (void*)$value, $1_descriptor, 0); + c.value = *z_var; + zval_copy_ctor(&c.value); + c.name = zend_strndup("$symname", len); + c.name_len = len+1; + c.flags = CONST_CS | CONST_PERSISTENT; + c.module_number = module_number; + zend_register_constant( &c TSRMLS_CC ); +} + +/* Handled as a global variable. */ +%typemap(consttab) SWIGTYPE (CLASS::*) ""; diff --git a/Lib/php5/director.swg b/Lib/php5/director.swg new file mode 100644 index 000000000..638a1697d --- /dev/null +++ b/Lib/php5/director.swg @@ -0,0 +1,170 @@ +/* ----------------------------------------------------------------------------- + * director.swg + * + * This file contains support for director classes so that PHP proxy + * methods can be called from C++. + * ----------------------------------------------------------------------------- */ + +#ifndef SWIG_DIRECTOR_PHP_HEADER_ +#define SWIG_DIRECTOR_PHP_HEADER_ + +#include +#include +#include + +namespace Swig { + + /* memory handler */ + struct GCItem { + virtual ~GCItem() { + } + + virtual int get_own() const { + return 0; + } + }; + + struct GCItem_var { + GCItem_var(GCItem *item = 0) : _item(item) { + } + + GCItem_var& operator=(GCItem *item) { + GCItem *tmp = _item; + _item = item; + delete tmp; + return *this; + } + + ~GCItem_var() { + delete _item; + } + + GCItem * operator->() const { + return _item; + } + + private: + GCItem *_item; + }; + + struct GCItem_Object : GCItem { + GCItem_Object(int own) : _own(own) { + } + + virtual ~GCItem_Object() { + } + + int get_own() const { + return _own; + } + + private: + int _own; + }; + + template + struct GCItem_T : GCItem { + GCItem_T(Type *ptr) : _ptr(ptr) { + } + + virtual ~GCItem_T() { + delete _ptr; + } + + private: + Type *_ptr; + }; + + class Director { + protected: + zval *swig_self; + typedef std::map swig_ownership_map; + mutable swig_ownership_map swig_owner; +#ifdef ZTS + // Store the ZTS context so it's available when C++ calls back to PHP. + void *** swig_zts_ctx; +#endif + public: + Director(zval *self TSRMLS_DC) : swig_self(self) { + TSRMLS_SET_CTX(swig_zts_ctx); + } + + static bool swig_is_overridden_method(char *cname, char *lc_fname TSRMLS_DC) { + zend_class_entry **ce; + zend_function *mptr; + + if (zend_lookup_class(cname, strlen(cname), &ce TSRMLS_CC) != SUCCESS) { + return false; + } + if (zend_hash_find(&(*ce)->function_table, lc_fname, strlen(lc_fname) + 1, (void **) &mptr) != SUCCESS) { + return false; + } + // common.scope points to the declaring class + return strcmp(mptr->common.scope->name, cname); + } + + template + void swig_acquire_ownership(Type *vptr) const { + if (vptr) { + swig_owner[vptr] = new GCItem_T(vptr); + } + } + }; + + /* base class for director exceptions */ + class DirectorException : public std::exception { + protected: + std::string swig_msg; + public: + DirectorException(int code, const char *hdr, const char *msg TSRMLS_DC) : swig_msg(hdr) { + if (msg[0]) { + swig_msg += " "; + swig_msg += msg; + } + SWIG_ErrorCode() = code; + SWIG_ErrorMsg() = swig_msg.c_str(); + } + + virtual ~DirectorException() throw() { + } + + const char *what() const throw() { + return swig_msg.c_str(); + } + + static void raise(int code, const char *hdr, const char *msg TSRMLS_DC) { + throw DirectorException(code, hdr, msg TSRMLS_CC); + } + }; + + /* attempt to call a pure virtual method via a director method */ + class DirectorPureVirtualException : public DirectorException { + public: + DirectorPureVirtualException(const char *msg TSRMLS_DC) + : DirectorException(E_ERROR, "SWIG director pure virtual method called", msg TSRMLS_CC) { + } + + static void raise(const char *msg TSRMLS_DC) { + throw DirectorPureVirtualException(msg TSRMLS_CC); + } + }; + + /* any php exception that occurs during a director method call */ + class DirectorMethodException : public DirectorException + { + public: + DirectorMethodException(const char *msg TSRMLS_DC) + : DirectorException(E_ERROR, "SWIG director method error", msg TSRMLS_CC) { + } + + static void raise(const char *msg TSRMLS_DC) { + throw DirectorMethodException(msg TSRMLS_CC); + } + }; +} + +// DirectorMethodException() is documented to be callable with no parameters +// so use a macro to insert TSRMLS_CC so any ZTS context gets passed. +#define DirectorMethodException() DirectorMethodException("" TSRMLS_CC) + +#endif diff --git a/Lib/php5/factory.i b/Lib/php5/factory.i new file mode 100644 index 000000000..c4e082dd2 --- /dev/null +++ b/Lib/php5/factory.i @@ -0,0 +1,109 @@ +/* + Implement a more natural wrap for factory methods, for example, if + you have: + + ---- geometry.h -------- + struct Geometry { + enum GeomType{ + POINT, + CIRCLE + }; + + virtual ~Geometry() {} + virtual int draw() = 0; + + // + // Factory method for all the Geometry objects + // + static Geometry *create(GeomType i); + }; + + struct Point : Geometry { + int draw() { return 1; } + double width() { return 1.0; } + }; + + struct Circle : Geometry { + int draw() { return 2; } + double radius() { return 1.5; } + }; + + // + // Factory method for all the Geometry objects + // + Geometry *Geometry::create(GeomType type) { + switch (type) { + case POINT: return new Point(); + case CIRCLE: return new Circle(); + default: return 0; + } + } + ---- geometry.h -------- + + + You can use the %factory with the Geometry::create method as follows: + + %newobject Geometry::create; + %factory(Geometry *Geometry::create, Point, Circle); + %include "geometry.h" + + and Geometry::create will return a 'Point' or 'Circle' instance + instead of the plain 'Geometry' type. For example, in python: + + circle = Geometry.create(Geometry.CIRCLE) + r = circle.radius() + + where circle is a Circle proxy instance. + + NOTES: remember to fully qualify all the type names and don't + use %factory inside a namespace declaration, ie, instead of + + namespace Foo { + %factory(Geometry *Geometry::create, Point, Circle); + } + + use + + %factory(Foo::Geometry *Foo::Geometry::create, Foo::Point, Foo::Circle); + + +*/ + +/* for loop for macro with one argument */ +%define %_formacro_1(macro, arg1,...)macro(arg1) +#if #__VA_ARGS__ != "__fordone__" +%_formacro_1(macro, __VA_ARGS__) +#endif +%enddef + +/* for loop for macro with one argument */ +%define %formacro_1(macro,...)%_formacro_1(macro,__VA_ARGS__,__fordone__)%enddef +%define %formacro(macro,...)%_formacro_1(macro,__VA_ARGS__,__fordone__)%enddef + +/* for loop for macro with two arguments */ +%define %_formacro_2(macro, arg1, arg2, ...)macro(arg1, arg2) +#if #__VA_ARGS__ != "__fordone__" +%_formacro_2(macro, __VA_ARGS__) +#endif +%enddef + +/* for loop for macro with two arguments */ +%define %formacro_2(macro,...)%_formacro_2(macro, __VA_ARGS__, __fordone__)%enddef + +%define %_factory_dispatch(Type) +if (!dcast) { + Type *dobj = dynamic_cast($1); + if (dobj) { + dcast = 1; + SWIG_SetPointerZval(return_value, SWIG_as_voidptr(dobj),$descriptor(Type *), $owner); + } +}%enddef + +%define %factory(Method,Types...) +%typemap(out) Method { + int dcast = 0; + %formacro(%_factory_dispatch, Types) + if (!dcast) { + SWIG_SetPointerZval(return_value, SWIG_as_voidptr($1),$descriptor, $owner); + } +}%enddef diff --git a/Lib/php5/globalvar.i b/Lib/php5/globalvar.i new file mode 100644 index 000000000..a3e99f510 --- /dev/null +++ b/Lib/php5/globalvar.i @@ -0,0 +1,361 @@ +/* ----------------------------------------------------------------------------- + * globalvar.i + * + * Global variables - add the variable to PHP + * ----------------------------------------------------------------------------- */ + +%typemap(varinit) char * +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + z_var->type = IS_STRING; + if($1) { + z_var->value.str.val = estrdup($1); + z_var->value.str.len = strlen($1); + } else { + z_var->value.str.val = 0; + z_var->value.str.len = 0; + } + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); +} + +%typemap(varinit) char [] +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + z_var->type = IS_STRING; + z_var->value.str.val = estrdup($1); + z_var->value.str.len = strlen($1); + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); +} + +%typemap(varinit) int, + unsigned int, + unsigned short, + short, + unsigned short, + long, + unsigned long, + signed char, + unsigned char, + enum SWIGTYPE +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + z_var->type = IS_LONG; + z_var->value.lval = (long)$1; + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); +} + +%typemap(varinit) bool +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + z_var->type = IS_BOOL; + z_var->value.lval = ($1)?1:0; + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL); +} + +%typemap(varinit) float, double +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + z_var->type = IS_DOUBLE; + z_var->value.dval = $1; + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, + sizeof(zval *), NULL); +} + +%typemap(varinit) char +{ + zval *z_var; + char c[2]; + MAKE_STD_ZVAL(z_var); + c[0] = $1; + c[1] = 0; + z_var->type = IS_STRING; + z_var->value.str.val = estrndup(c, 1); + z_var->value.str.len = 1; + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, + sizeof(zval *), NULL); +} + +%typemap(varinit) SWIGTYPE *, SWIGTYPE [] +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0); + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, + sizeof(zval *), NULL); +} + +%typemap(varinit) SWIGTYPE, SWIGTYPE &, SWIGTYPE && +{ + zval *z_var; + + MAKE_STD_ZVAL(z_var); + SWIG_SetPointerZval(z_var, (void*)&$1, $&1_descriptor, 0); + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&z_var, + sizeof(zval *), NULL); +} + +%typemap(varinit) char [ANY] +{ + zval *z_var; + MAKE_STD_ZVAL(z_var); + z_var->type = IS_STRING; + ZVAL_STRINGL(z_var,(char*)$1, $1_dim0, 1); + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&z_var, sizeof(zval *), NULL); +} + +%typemap(varinit, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +{ + void * p = emalloc(sizeof($1)); + memcpy(p, &$1, sizeof($1)); + zval * resource; + MAKE_STD_ZVAL(resource); + ZEND_REGISTER_RESOURCE(resource, p, swig_member_ptr); + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&resource, sizeof(zval *), NULL); +} + +%typemap(varin) int, unsigned int, short, unsigned short, long, unsigned long, signed char, unsigned char, enum SWIGTYPE +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + convert_to_long_ex(z_var); + if ($1 != ($1_ltype)((*z_var)->value.lval)) { + $1 = Z_LVAL_PP(z_var); + } +} + +%typemap(varin) bool +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + convert_to_boolean_ex(z_var); + if ($1 != ($1_ltype)((*z_var)->value.lval)) { + $1 = Z_LVAL_PP(z_var); + } +} + +%typemap(varin) double,float +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + convert_to_double_ex(z_var); + if ($1 != ($1_ltype)((*z_var)->value.dval)) { + $1 = Z_DVAL_PP(z_var); + } +} + +%typemap(varin) char +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + convert_to_string_ex(z_var); + if ($1 != *((*z_var)->value.str.val)) { + $1 = *((*z_var)->value.str.val); + } +} + +%typemap(varin) char * +{ + zval **z_var; + char *s1; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + convert_to_string_ex(z_var); + s1 = Z_STRVAL_PP(z_var); + if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { + if (s1) + $1 = estrdup(s1); + else + $1 = NULL; + } +} + + +%typemap(varin) SWIGTYPE [] +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if($1) { + SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, $owner); + } +} + +%typemap(varin) char [ANY] +{ + zval **z_var; + char *s1; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + s1 = Z_STRVAL_PP(z_var); + if ((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { + if (s1) + strncpy($1, s1, $1_dim0); + } +} + +%typemap(varin) SWIGTYPE +{ + zval **z_var; + $&1_ltype _temp; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if (SWIG_ConvertPtr(*z_var, (void**)&_temp, $&1_descriptor, 0) < 0) { + SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor"); + } + + $1 = *($&1_ltype)_temp; + +} + +%typemap(varin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && +{ + zval **z_var; + $1_ltype _temp; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if (SWIG_ConvertPtr(*z_var, (void **)&_temp, $1_descriptor, 0) < 0) { + SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor"); + } + + $1 = ($1_ltype)_temp; +} + +%typemap(varin, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + void * p = (void*)zend_fetch_resource(*z_var TSRMLS_CC, -1, SWIG_MEMBER_PTR, NULL, 1, swig_member_ptr); + memcpy(&$1, p, sizeof($1)); +} + +%typemap(varout) int, + unsigned int, + unsigned short, + short, + long, + unsigned long, + signed char, + unsigned char, + enum SWIGTYPE +{ + zval **z_var; + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if($1 != ($1_ltype)((*z_var)->value.lval)) { + (*z_var)->value.lval = (long)$1; + } +} + +//SAMFIX need to cast zval->type, what if zend-hash_find fails? etc? +%typemap(varout) bool +{ + zval **z_var; + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if($1 != ($1_ltype)((*z_var)->value.lval)) { + (*z_var)->value.lval = (long)$1; + } +} + +%typemap(varout) double, float +{ + zval **z_var; + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if($1 != ($1_ltype)((*z_var)->value.dval)) { + (*z_var)->value.dval = (double)$1; + } +} + +%typemap(varout) char +{ + zval **z_var; + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if($1 != *((*z_var)->value.str.val)) { + char c[2]; + efree((*z_var)->value.str.val); + c[0] = $1; + c[1] = 0; + (*z_var)->value.str.val = estrdup(c); + } +} + +%typemap(varout) char * +{ + zval **z_var; + char *s1; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + s1 = Z_STRVAL_PP(z_var); + if((s1 == NULL) || ($1 == NULL) || strcmp(s1, $1)) { + if(s1) + efree(s1); + if($1) { + (*z_var)->value.str.val = estrdup($1); + (*z_var)->value.str.len = strlen($1) + 1; + } else { + (*z_var)->value.str.val = 0; + (*z_var)->value.str.len = 0; + } + } +} + +%typemap(varout) SWIGTYPE +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + SWIG_SetPointerZval(*z_var, (void*)&$1, $&1_descriptor, 0); +} + +%typemap(varout) SWIGTYPE [] +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + if($1) + SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0); +} + +%typemap(varout) char [ANY] +{ + zval **z_var; + char *s1; +deliberate error cos this code looks bogus to me + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + s1 = Z_STRVAL_PP(z_var); + if((s1 == NULL) || strcmp(s1, $1)) { + if($1) { + (*z_var)->value.str.val = estrdup($1); + (*z_var)->value.str.len = strlen($1) + 1; + } else { + (*z_var)->value.str.val = 0; + (*z_var)->value.str.len = 0; + } + } +} + +%typemap(varout) SWIGTYPE *, SWIGTYPE &, SWIGTYPE && +{ + zval **z_var; + + zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var); + SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0); +} + +%typemap(varout, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +{ + void * p = emalloc(sizeof($1)); + memcpy(p, &$1, sizeof($1)); + zval * resource; + MAKE_STD_ZVAL(resource); + ZEND_REGISTER_RESOURCE(resource, p, swig_member_ptr); + zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&resource, sizeof(zval *), NULL); +} diff --git a/Lib/php5/php.swg b/Lib/php5/php.swg new file mode 100644 index 000000000..535c7d347 --- /dev/null +++ b/Lib/php5/php.swg @@ -0,0 +1,529 @@ +/* ----------------------------------------------------------------------------- + * php.swg + * + * PHP configuration file + * ----------------------------------------------------------------------------- */ + +%runtime "swigrun.swg" // Common C API type-checking code +%runtime "phprun.swg" // PHP runtime functions + +%include // PHP initialization routine. + +%include // Global variables. +%include + +// use %init %{ "/*code goes here*/ " %} +// or %minit %{ "/* code goes here*/ " %} to +// insert code in the PHP_MINIT_FUNCTION +#define %minit %insert("init") + +// use %rinit %{ "/* code goes here*/ " %} to +// insert code in the PHP_RINIT_FUNCTION +#define %rinit %insert("rinit") + +// use %shutdown %{ " /*code goes here*/ " %} to +// insert code in the PHP_MSHUTDOWN_FUNCTION +#define %shutdown %insert("shutdown") +#define %mshutdown %insert("shutdown") + +// use %rshutdown %{ " /*code goes here*/" %} to +// insert code in the PHP_RSHUTDOWN_FUNCTION +#define %rshutdown %insert("rshutdown") + +/* Typemaps for input parameters by value */ + +%include + +%pass_by_val(bool,CONVERT_BOOL_IN); + +%pass_by_val(size_t, CONVERT_INT_IN); + +%pass_by_val(enum SWIGTYPE, CONVERT_INT_IN); + +%pass_by_val(signed int, CONVERT_INT_IN); +%pass_by_val(int,CONVERT_INT_IN); +%pass_by_val(unsigned int,CONVERT_INT_IN); + +%pass_by_val(signed short, CONVERT_INT_IN); +%pass_by_val(short,CONVERT_INT_IN); +%pass_by_val(unsigned short, CONVERT_INT_IN); + +%pass_by_val(signed long, CONVERT_INT_IN); +%pass_by_val(long, CONVERT_INT_IN); +%pass_by_val(unsigned long, CONVERT_INT_IN); + +%pass_by_val(signed long long, CONVERT_LONG_LONG_IN); +%pass_by_val(long long, CONVERT_LONG_LONG_IN); +%pass_by_val(unsigned long long, CONVERT_UNSIGNED_LONG_LONG_IN); + +%pass_by_val(signed char, CONVERT_INT_IN); +%pass_by_val(char, CONVERT_CHAR_IN); +%pass_by_val(unsigned char, CONVERT_INT_IN); + +%pass_by_val(float, CONVERT_FLOAT_IN); + +%pass_by_val(double, CONVERT_FLOAT_IN); + +%pass_by_val(char *, CONVERT_STRING_IN); +%typemap(in) char *& = const char *&; +%typemap(directorout) char *& = const char *&; + +// char array can be in/out, though the passed string may not be big enough... +// so we have to size it +%typemap(in) char[ANY] +{ + convert_to_string_ex($input); + $1 = ($1_ltype) Z_STRVAL_PP($input); +} + +%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) { + convert_to_string_ex($input); + $1 = ($1_ltype) Z_STRVAL_PP($input); + $2 = ($2_ltype) Z_STRLEN_PP($input); +} + +/* Object passed by value. Convert to a pointer */ +%typemap(in) SWIGTYPE ($&1_ltype tmp) +{ + if(SWIG_ConvertPtr(*$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) { + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); + } + $1 = *tmp; +} + +%typemap(directorout) SWIGTYPE ($&1_ltype tmp) +{ + /* If exit was via exception, PHP NULL is returned so skip the conversion. */ + if (!EG(exception)) { + if(SWIG_ConvertPtr($input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); + $result = *tmp; + } +} + +%typemap(in) SWIGTYPE *, + SWIGTYPE [] +{ + if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) { + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); + } +} + +%typemap(in) SWIGTYPE & +{ + if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); + } +} + +%typemap(in) SWIGTYPE && +{ + if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) { + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor"); + } +} + +%typemap(in) SWIGTYPE *const& ($*ltype temp) +{ + if(SWIG_ConvertPtr(*$input, (void **) &temp, $*1_descriptor, 0) < 0) { + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $*1_descriptor"); + } + $1 = ($1_ltype)&temp; +} + +%typemap(in) SWIGTYPE *DISOWN +{ + if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, SWIG_POINTER_DISOWN ) < 0) { + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); + } +} + +%typemap(argout) SWIGTYPE *, + SWIGTYPE [], + SWIGTYPE &, + SWIGTYPE &&; + +%typemap(in) void * +{ + if(SWIG_ConvertPtr(*$input, (void **) &$1, 0, 0) < 0) { + /* Allow NULL from php for void* */ + if ((*$input)->type==IS_NULL) $1=0; + else + SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor"); + } +} + +/* Special case when void* is passed by reference so it can be made to point + to opaque api structs */ +%typemap(in) void ** ($*1_ltype ptr, int force), + void *& ($*1_ltype ptr, int force) +{ + /* If they pass NULL by reference, make it into a void* + This bit should go in arginit if arginit support init-ing scripting args */ + if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) { + /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */ + if (!((*$input)->type==IS_NULL && PZVAL_IS_REF(*$input))) { + /* wasn't a pre/ref/thing, OR anything like an int thing */ + SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname."); + } + } + force=0; + if (arg1==NULL) { +#ifdef __cplusplus + ptr=new $*1_ltype(); +#else + ptr=($*1_ltype) calloc(1,sizeof($*1_ltype)); +#endif + $1=&ptr; + /* have to passback arg$arg too */ + force=1; + } +} +%typemap(argout) void **, + void *& +{ + if (force$argnum) { + SWIG_SetPointerZval( *$input, (void*) ptr$argnum, $*1_descriptor, 1); + } +} + +/* Typemap for output values */ + +%typemap(out) int, + unsigned int, + short, + unsigned short, + long, + unsigned long, + signed char, + unsigned char, + bool, + size_t +{ + ZVAL_LONG(return_value,$1); +} + +%typemap(out) enum SWIGTYPE +{ + ZVAL_LONG(return_value, (long)$1); +} + +%typemap(out) long long +%{ + if ((long long)LONG_MIN <= $1 && $1 <= (long long)LONG_MAX) { + return_value->value.lval = (long)($1); + return_value->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%lld", (long long)$1); + ZVAL_STRING(return_value, temp, 1); + } +%} +%typemap(out) unsigned long long +%{ + if ($1 <= (unsigned long long)LONG_MAX) { + return_value->value.lval = (long)($1); + return_value->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%llu", (unsigned long long)$1); + ZVAL_STRING(return_value, temp, 1); + } +%} + +%typemap(out) const int &, + const unsigned int &, + const short &, + const unsigned short &, + const long &, + const unsigned long &, + const signed char &, + const unsigned char &, + const bool &, + const size_t & +{ + ZVAL_LONG(return_value,*$1); +} + +%typemap(out) const enum SWIGTYPE & +{ + ZVAL_LONG(return_value, (long)*$1); +} + +%typemap(out) const enum SWIGTYPE && +{ + ZVAL_LONG(return_value, (long)*$1); +} + +%typemap(out) const long long & +%{ + if ((long long)LONG_MIN <= *$1 && *$1 <= (long long)LONG_MAX) { + return_value->value.lval = (long)(*$1); + return_value->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%lld", (long long)(*$1)); + ZVAL_STRING(return_value, temp, 1); + } +%} +%typemap(out) const unsigned long long & +%{ + if (*$1 <= (unsigned long long)LONG_MAX) { + return_value->value.lval = (long)(*$1); + return_value->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%llu", (unsigned long long)(*$1)); + ZVAL_STRING(return_value, temp, 1); + } +%} + +%typemap(directorin) int, + unsigned int, + short, + unsigned short, + long, + unsigned long, + signed char, + unsigned char, + size_t, + enum SWIGTYPE +{ + ZVAL_LONG($input,$1); +} + +%typemap(directorin) enum SWIGTYPE +{ + ZVAL_LONG($input, (long)$1_name); +} + +%typemap(directorin) char *, char [] +{ + if(!$1) { + ZVAL_NULL($input); + } else { + ZVAL_STRING($input, (char *)$1, 1); + } +} + +%typemap(out) bool +{ + ZVAL_BOOL(return_value,($1)?1:0); +} + +%typemap(out) const bool & +{ + ZVAL_BOOL(return_value,(*$1)?1:0); +} + +%typemap(directorin) bool +{ + ZVAL_BOOL($input,($1)?1:0); +} + +%typemap(out) float, + double +{ + ZVAL_DOUBLE(return_value,$1); +} + +%typemap(out) const float &, + const double & +{ + ZVAL_DOUBLE(return_value,*$1); +} + +%typemap(directorin) float, + double +{ + ZVAL_DOUBLE($input,$1); +} + +%typemap(out) char +{ + ZVAL_STRINGL(return_value,&$1, 1, 1); +} + +%typemap(out) const char & +{ + ZVAL_STRINGL(return_value,&*$1, 1, 1); +} + +%typemap(out) char *, + char [] +{ + if(!$1) { + ZVAL_NULL(return_value); + } else { + ZVAL_STRING(return_value, (char *)$1, 1); + } +} + +%typemap(out) char *& +{ + if(!*$1) { + ZVAL_NULL(return_value); + } else { + ZVAL_STRING(return_value, (char *)*$1, 1); + } +} + +%typemap(out) SWIGTYPE *, + SWIGTYPE [], + SWIGTYPE &, + SWIGTYPE && +%{ + SWIG_SetPointerZval(return_value, (void *)$1, $1_descriptor, $owner); +%} + +%typemap(out) SWIGTYPE *const& +%{ + SWIG_SetPointerZval(return_value, (void *)*$1, $*1_descriptor, $owner); +%} + +%typemap(directorin) SWIGTYPE *, + SWIGTYPE [], + SWIGTYPE &, + SWIGTYPE && +%{ + SWIG_SetPointerZval($input, (void *)&$1, $1_descriptor, ($owner)|2); +%} + +%typemap(out, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +{ + void * p = emalloc(sizeof($1)); + memcpy(p, &$1, sizeof($1)); + ZEND_REGISTER_RESOURCE(return_value, p, swig_member_ptr); +} + +%typemap(in, fragment="swig_php_init_member_ptr") SWIGTYPE (CLASS::*) +{ + void * p = (void*)zend_fetch_resource($input TSRMLS_CC, -1, SWIG_MEMBER_PTR, NULL, 1, swig_member_ptr); + memcpy(&$1, p, sizeof($1)); +} + +%typemap(out) SWIGTYPE *DYNAMIC, + SWIGTYPE &DYNAMIC +{ + swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor, (void **) &$1); + SWIG_SetPointerZval(return_value, (void *)$1, ty, $owner); +} + +%typemap(out) SWIGTYPE +#ifdef __cplusplus +{ + $&1_ltype resultobj = new $1_ltype((const $1_ltype &) $1); + SWIG_SetPointerZval(return_value, (void *)resultobj, $&1_descriptor, 1); +} +#else +{ + $&1_ltype resultobj = ($&1_ltype) emalloc(sizeof($1_type)); + memcpy(resultobj, &$1, sizeof($1_type)); + SWIG_SetPointerZval(return_value, (void *)resultobj, $&1_descriptor, 1); +} +#endif + +%typemap(directorin) SWIGTYPE +{ + SWIG_SetPointerZval($input, SWIG_as_voidptr(new $1_ltype((const $1_ltype &)$1)), $&1_descriptor, 1|2); +} + +%typemap(out) void ""; + +%typemap(out) char [ANY] +{ + int len = 0; + while (len < $1_dim0 && $1[len]) ++len; + RETVAL_STRINGL($1, len, 1); +} + +// This typecheck does hard checking for proper argument type. If you want +// an argument to be converted from a different PHP type, you must convert +// it yourself before passing it (e.g. (string)4.7 or (int)"6"). +%define %php_typecheck(_type,_prec,is) +%typemap(typecheck,precedence=_prec) _type, const _type & + " $1 = (Z_TYPE_PP($input) == is); " +%enddef + +%php_typecheck(int,SWIG_TYPECHECK_INTEGER,IS_LONG) +%php_typecheck(unsigned int,SWIG_TYPECHECK_UINT32,IS_LONG) +%php_typecheck(short,SWIG_TYPECHECK_INT16,IS_LONG) +%php_typecheck(unsigned short,SWIG_TYPECHECK_UINT16,IS_LONG) +%php_typecheck(long,SWIG_TYPECHECK_INT32,IS_LONG) +%php_typecheck(unsigned long,SWIG_TYPECHECK_UINT32,IS_LONG) +%php_typecheck(long long,SWIG_TYPECHECK_INT64,IS_LONG) +%php_typecheck(unsigned long long,SWIG_TYPECHECK_UINT64,IS_LONG) +%php_typecheck(signed char,SWIG_TYPECHECK_INT8,IS_LONG) +%php_typecheck(unsigned char,SWIG_TYPECHECK_UINT8,IS_LONG) +%php_typecheck(size_t,SWIG_TYPECHECK_SIZE,IS_LONG) +%php_typecheck(enum SWIGTYPE,SWIG_TYPECHECK_INTEGER,IS_LONG) +%php_typecheck(bool,SWIG_TYPECHECK_BOOL,IS_BOOL) +%php_typecheck(float,SWIG_TYPECHECK_FLOAT,IS_DOUBLE) +%php_typecheck(double,SWIG_TYPECHECK_DOUBLE,IS_DOUBLE) +%php_typecheck(char,SWIG_TYPECHECK_CHAR,IS_STRING) + +%typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) char *, char *&, char [] + " $1 = (Z_TYPE_PP($input) == IS_STRING); " + +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE +{ + void *tmp; + _v = (SWIG_ConvertPtr(*$input, (void **)&tmp, $&1_descriptor, 0) >= 0); +} + +%typecheck(SWIG_TYPECHECK_POINTER) + SWIGTYPE *, + SWIGTYPE [], + SWIGTYPE &, + SWIGTYPE &&, + SWIGTYPE *const& +{ + void *tmp; + _v = (SWIG_ConvertPtr(*$input, (void**)&tmp, $1_descriptor, 0) >= 0); +} + +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *const& +{ + void *tmp; + _v = (SWIG_ConvertPtr(*$input, (void**)&tmp, $*1_descriptor, 0) >= 0); +} + +%typecheck(SWIG_TYPECHECK_VOIDPTR) void * +{ + void *tmp; + _v = (SWIG_ConvertPtr(*$input, (void**)&tmp, 0, 0) >= 0); +} + +/* Exception handling */ + +%typemap(throws) int, + long, + short, + unsigned int, + unsigned long, + unsigned short { + zend_throw_exception(NULL, const_cast("C++ $1_type exception thrown"), $1 TSRMLS_CC); + return; +} + +%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ + (void)$1; + zend_throw_exception(NULL, const_cast("C++ $1_type exception thrown"), 0 TSRMLS_CC); + return; +%} + +%typemap(throws) char * %{ + zend_throw_exception(NULL, const_cast($1), 0 TSRMLS_CC); + return; +%} + +/* Array reference typemaps */ +%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } +%apply SWIGTYPE && { SWIGTYPE ((&&)[ANY]) } + +/* const pointers */ +%apply SWIGTYPE * { SWIGTYPE *const } + + +/* php keywords */ +%include diff --git a/Lib/php5/phpinit.swg b/Lib/php5/phpinit.swg new file mode 100644 index 000000000..d8a61b02b --- /dev/null +++ b/Lib/php5/phpinit.swg @@ -0,0 +1,25 @@ + +/* ------------------------------------------------------------ + * The start of the PHP initialization function + * ------------------------------------------------------------ */ + +%insert(init) "swiginit.swg" + +%init %{ +SWIG_php_minit { + SWIG_InitializeModule(0); +%} + +%fragment("swig_php_init_member_ptr2", "header") { +#define SWIG_MEMBER_PTR ((char*)"CLASS::*") + +static void swig_member_ptr_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { + efree(rsrc->ptr); +} + +static int swig_member_ptr = 0; +} + +%fragment("swig_php_init_member_ptr", "init", fragment="swig_php_init_member_ptr2") { + swig_member_ptr = zend_register_list_destructors_ex(swig_member_ptr_dtor, NULL, SWIG_MEMBER_PTR, module_number); +} diff --git a/Lib/php5/phpkw.swg b/Lib/php5/phpkw.swg new file mode 100644 index 000000000..36e535f52 --- /dev/null +++ b/Lib/php5/phpkw.swg @@ -0,0 +1,866 @@ +/* ----------------------------------------------------------------------------- + * phpkw.swg + * ----------------------------------------------------------------------------- */ + +/* Keyword (case insensitive) */ +#define PHPKW(x) %keywordwarn("'" `x` "' is a PHP keyword, renaming to 'c_" `x` "'",sourcefmt="%(lower)s",rename="c_%s") `x` + +/* Class (case insensitive) */ +#define PHPCN(x) %keywordwarn("'" `x` "' is a PHP reserved class name, renaming to 'c_" `x` "'",%$isclass,sourcefmt="%(lower)s",rename="c_%s") `x` + +/* Constant (case insensitive) */ +#define PHPBN1a(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "enum conflicts with a built-in constant '"`x`"' in PHP"),%$isenumitem,sourcefmt="%(lower)s") `x` +#define PHPBN1b(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "constant conflicts with a built-in constant '"`x`"' in PHP"),%$isconstant,sourcefmt="%(lower)s") `x` +%define PHPBN1(X) + PHPBN1a(X); PHPBN1b(X) +%enddef + +/* Constant (case sensitive) */ +#define PHPBN2a(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "enum conflicts with a built-in constant '"`x`"' in PHP"),%$isenumitem) `x` +#define PHPBN2b(x) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, "constant conflicts with a built-in constant '"`x`"' in PHP"),%$isconstant) `x` +%define PHPBN2(X) + PHPBN2a(X); PHPBN2b(X) +%enddef + +#define PHPFN(x) %keywordwarn("'" `x` "' is a PHP built-in function, renaming to 'c_" `x` "'",sourcefmt="%(lower)s",%$isfunction,%$not %$ismember,rename="c_%s") `x` + +/* From: http://php.net/manual/en/reserved.keywords.php + * "You cannot use any of the following words as constants, class names, + * function or method names. Using them as variable names is generally OK, but + * could lead to confusion." + */ +/* Check is case insensitive - these *MUST* be listed in lower case here */ +PHPKW(__halt_compiler); +PHPKW(abstract); +PHPKW(and); +PHPKW(array); +PHPKW(as); +PHPKW(break); +PHPKW(callable); // As of PHP 5.4 +PHPKW(case); +PHPKW(catch); +PHPKW(class); +PHPKW(clone); +PHPKW(const); +PHPKW(continue); +PHPKW(declare); +PHPKW(default); +PHPKW(die); // "Language construct" +PHPKW(do); +PHPKW(echo); // "Language construct" +PHPKW(else); +PHPKW(elseif); +PHPKW(empty); // "Language construct" +PHPKW(enddeclare); +PHPKW(endfor); +PHPKW(endforeach); +PHPKW(endif); +PHPKW(endswitch); +PHPKW(endwhile); +PHPKW(eval); // "Language construct" +PHPKW(exit); // "Language construct" +PHPKW(extends); +PHPKW(final); +PHPKW(finally); // As of PHP 5.5 +PHPKW(for); +PHPKW(foreach); +PHPKW(function); +PHPKW(global); +PHPKW(goto); // As of PHP 5.3 +PHPKW(if); +PHPKW(implements); +PHPKW(include); // "Language construct" +PHPKW(include_once); // "Language construct" +PHPKW(instanceof); +PHPKW(insteadof); // As of PHP 5.4 +PHPKW(interface); +PHPKW(isset); // "Language construct" +PHPKW(list); // "Language construct" +PHPKW(namespace); // As of PHP 5.3 +PHPKW(new); +PHPKW(or); +PHPKW(print); // "Language construct" +PHPKW(private); +PHPKW(protected); +PHPKW(public); +PHPKW(require); // "Language construct" +PHPKW(require_once); // "Language construct" +PHPKW(return); // "Language construct" +PHPKW(static); +PHPKW(switch); +PHPKW(throw); +PHPKW(trait); // As of PHP 5.4 +PHPKW(try); +PHPKW(unset); // "Language construct" +PHPKW(use); +PHPKW(var); +PHPKW(while); +PHPKW(xor); +PHPKW(yield); // As of PHP 5.5 + +// Compile-time "magic" constants +// From: http://php.net/manual/en/reserved.keywords.php +// also at: http://php.net/manual/en/language.constants.predefined.php +/* These *MUST* be listed in lower case here */ +PHPKW(__class__); +PHPKW(__dir__); // As of PHP 5.3 +PHPKW(__file__); +PHPKW(__function__); +PHPKW(__line__); +PHPKW(__method__); +PHPKW(__namespace__); // As of PHP 5.3 +PHPKW(__trait__); // As of PHP 5.4 + +/* We classify these as built-in names since they conflict, but PHP still runs */ + +/* Predefined case-insensitive constants */ +/* These *MUST* be listed in lower case here */ +PHPBN1(null); +PHPBN1(true); +PHPBN1(false); + +/* "Core Predefined Constants" from http://php.net/manual/en/reserved.constants.php */ +/* These are case sensitive */ +PHPBN2(PHP_VERSION); +PHPBN2(PHP_MAJOR_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_MINOR_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_RELEASE_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_VERSION_ID); // As of PHP 5.2.7 +PHPBN2(PHP_EXTRA_VERSION); // As of PHP 5.2.7 +PHPBN2(PHP_ZTS); // As of PHP 5.2.7 +PHPBN2(PHP_DEBUG); // As of PHP 5.2.7 +PHPBN2(PHP_MAXPATHLEN); // As of PHP 5.3.0 +PHPBN2(PHP_OS); +PHPBN2(PHP_SAPI); +PHPBN2(PHP_EOL); // As of PHP 5.0.2 +PHPBN2(PHP_INT_MAX); // As of PHP 5.0.5 +PHPBN2(PHP_INT_SIZE); // As of PHP 5.0.5 +PHPBN2(DEFAULT_INCLUDE_PATH); +PHPBN2(PEAR_INSTALL_DIR); +PHPBN2(PEAR_EXTENSION_DIR); +PHPBN2(PHP_EXTENSION_DIR); +PHPBN2(PHP_PREFIX); +PHPBN2(PHP_BINDIR); +PHPBN2(PHP_BINARY); // As of PHP 5.4 +PHPBN2(PHP_MANDIR); // As of PHP 5.3.7 +PHPBN2(PHP_LIBDIR); +PHPBN2(PHP_DATADIR); +PHPBN2(PHP_SYSCONFDIR); +PHPBN2(PHP_LOCALSTATEDIR); +PHPBN2(PHP_CONFIG_FILE_PATH); +PHPBN2(PHP_CONFIG_FILE_SCAN_DIR); +PHPBN2(PHP_SHLIB_SUFFIX); +PHPBN2(E_ERROR); +PHPBN2(E_WARNING); +PHPBN2(E_PARSE); +PHPBN2(E_NOTICE); +PHPBN2(E_CORE_ERROR); +PHPBN2(E_CORE_WARNING); +PHPBN2(E_COMPILE_ERROR); +PHPBN2(E_COMPILE_WARNING); +PHPBN2(E_USER_ERROR); +PHPBN2(E_USER_WARNING); +PHPBN2(E_USER_NOTICE); +PHPBN2(E_DEPRECATED); // As of PHP 5.3.0 +PHPBN2(E_USER_DEPRECATED); // As of PHP 5.3.0 +PHPBN2(E_ALL); +PHPBN2(E_STRICT); +PHPBN2(__COMPILER_HALT_OFFSET__); // As of PHP 5.1.0 +// TRUE, FALSE, NULL are listed on the same page, but are actually +// case-insensitive, whereas all the other constants listed there seem to be +// case-sensitive, so we handle TRUE, FALSE, NULL in PHPBN1. +PHPBN2(PHP_OUTPUT_HANDLER_START); +PHPBN2(PHP_OUTPUT_HANDLER_CONT); +PHPBN2(PHP_OUTPUT_HANDLER_END); +/* These don't actually seem to be set (tested on Linux, I guess they're + * Windows only?) */ +PHPBN2(PHP_WINDOWS_NT_DOMAIN_CONTROLLER); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_NT_SERVER); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_NT_WORKSTATION); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_BUILD); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_MAJOR); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_MINOR); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_PLATFORM); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_PRODUCTTYPE); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_SP_MAJOR); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_SP_MINOR); // As of PHP 5.3 +PHPBN2(PHP_WINDOWS_VERSION_SUITEMASK); // As of PHP 5.3 +/* "Standard Predefined Constants" from http://php.net/manual/en/reserved.constants.php */ +PHPBN2(EXTR_OVERWRITE); +PHPBN2(EXTR_SKIP); +PHPBN2(EXTR_PREFIX_SAME); +PHPBN2(EXTR_PREFIX_ALL); +PHPBN2(EXTR_PREFIX_INVALID); +PHPBN2(EXTR_PREFIX_IF_EXISTS); +PHPBN2(EXTR_IF_EXISTS); +PHPBN2(SORT_ASC); +PHPBN2(SORT_DESC); +PHPBN2(SORT_REGULAR); +PHPBN2(SORT_NUMERIC); +PHPBN2(SORT_STRING); +PHPBN2(CASE_LOWER); +PHPBN2(CASE_UPPER); +PHPBN2(COUNT_NORMAL); +PHPBN2(COUNT_RECURSIVE); +PHPBN2(ASSERT_ACTIVE); +PHPBN2(ASSERT_CALLBACK); +PHPBN2(ASSERT_BAIL); +PHPBN2(ASSERT_WARNING); +PHPBN2(ASSERT_QUIET_EVAL); +PHPBN2(CONNECTION_ABORTED); +PHPBN2(CONNECTION_NORMAL); +PHPBN2(CONNECTION_TIMEOUT); +PHPBN2(INI_USER); +PHPBN2(INI_PERDIR); +PHPBN2(INI_SYSTEM); +PHPBN2(INI_ALL); +PHPBN2(INI_SCANNER_NORMAL); // As of PHP 5.3 +PHPBN2(INI_SCANNER_RAW); // As of PHP 5.3 +PHPBN2(M_E); +PHPBN2(M_LOG2E); +PHPBN2(M_LOG10E); +PHPBN2(M_LN2); +PHPBN2(M_LN10); +PHPBN2(M_PI); +PHPBN2(M_PI_2); +PHPBN2(M_PI_4); +PHPBN2(M_1_PI); +PHPBN2(M_2_PI); +PHPBN2(M_2_SQRTPI); +PHPBN2(M_SQRT2); +PHPBN2(M_SQRT1_2); +PHPBN2(M_EULER); // As of PHP 5.2 +PHPBN2(M_LNPI); // As of PHP 5.2 +PHPBN2(M_SQRT3); // As of PHP 5.2 +PHPBN2(M_SQRTPI); // As of PHP 5.2 +PHPBN2(CRYPT_SALT_LENGTH); +PHPBN2(CRYPT_STD_DES); +PHPBN2(CRYPT_EXT_DES); +PHPBN2(CRYPT_MD5); +PHPBN2(CRYPT_BLOWFISH); +PHPBN2(DIRECTORY_SEPARATOR); +PHPBN2(SEEK_SET); +PHPBN2(SEEK_CUR); +PHPBN2(SEEK_END); +PHPBN2(LOCK_SH); +PHPBN2(LOCK_EX); +PHPBN2(LOCK_UN); +PHPBN2(LOCK_NB); +PHPBN2(HTML_SPECIALCHARS); +PHPBN2(HTML_ENTITIES); +PHPBN2(ENT_COMPAT); +PHPBN2(ENT_QUOTES); +PHPBN2(ENT_NOQUOTES); +PHPBN2(INFO_GENERAL); +PHPBN2(INFO_CREDITS); +PHPBN2(INFO_CONFIGURATION); +PHPBN2(INFO_MODULES); +PHPBN2(INFO_ENVIRONMENT); +PHPBN2(INFO_VARIABLES); +PHPBN2(INFO_LICENSE); +PHPBN2(INFO_ALL); +PHPBN2(CREDITS_GROUP); +PHPBN2(CREDITS_GENERAL); +PHPBN2(CREDITS_SAPI); +PHPBN2(CREDITS_MODULES); +PHPBN2(CREDITS_DOCS); +PHPBN2(CREDITS_FULLPAGE); +PHPBN2(CREDITS_QA); +PHPBN2(CREDITS_ALL); +PHPBN2(STR_PAD_LEFT); +PHPBN2(STR_PAD_RIGHT); +PHPBN2(STR_PAD_BOTH); +PHPBN2(PATHINFO_DIRNAME); +PHPBN2(PATHINFO_BASENAME); +PHPBN2(PATHINFO_EXTENSION); +PHPBN2(PATHINFO_FILENAME); // As of PHP 5.2 +PHPBN2(PATH_SEPARATOR); +PHPBN2(CHAR_MAX); +PHPBN2(LC_CTYPE); +PHPBN2(LC_NUMERIC); +PHPBN2(LC_TIME); +PHPBN2(LC_COLLATE); +PHPBN2(LC_MONETARY); +PHPBN2(LC_ALL); +PHPBN2(LC_MESSAGES); +PHPBN2(ABDAY_1); +PHPBN2(ABDAY_2); +PHPBN2(ABDAY_3); +PHPBN2(ABDAY_4); +PHPBN2(ABDAY_5); +PHPBN2(ABDAY_6); +PHPBN2(ABDAY_7); +PHPBN2(DAY_1); +PHPBN2(DAY_2); +PHPBN2(DAY_3); +PHPBN2(DAY_4); +PHPBN2(DAY_5); +PHPBN2(DAY_6); +PHPBN2(DAY_7); +PHPBN2(ABMON_1); +PHPBN2(ABMON_2); +PHPBN2(ABMON_3); +PHPBN2(ABMON_4); +PHPBN2(ABMON_5); +PHPBN2(ABMON_6); +PHPBN2(ABMON_7); +PHPBN2(ABMON_8); +PHPBN2(ABMON_9); +PHPBN2(ABMON_10); +PHPBN2(ABMON_11); +PHPBN2(ABMON_12); +PHPBN2(MON_1); +PHPBN2(MON_2); +PHPBN2(MON_3); +PHPBN2(MON_4); +PHPBN2(MON_5); +PHPBN2(MON_6); +PHPBN2(MON_7); +PHPBN2(MON_8); +PHPBN2(MON_9); +PHPBN2(MON_10); +PHPBN2(MON_11); +PHPBN2(MON_12); +PHPBN2(AM_STR); +PHPBN2(PM_STR); +PHPBN2(D_T_FMT); +PHPBN2(D_FMT); +PHPBN2(T_FMT); +PHPBN2(T_FMT_AMPM); +PHPBN2(ERA); +PHPBN2(ERA_YEAR); +PHPBN2(ERA_D_T_FMT); +PHPBN2(ERA_D_FMT); +PHPBN2(ERA_T_FMT); +PHPBN2(ALT_DIGITS); +PHPBN2(INT_CURR_SYMBOL); +PHPBN2(CURRENCY_SYMBOL); +PHPBN2(CRNCYSTR); +PHPBN2(MON_DECIMAL_POINT); +PHPBN2(MON_THOUSANDS_SEP); +PHPBN2(MON_GROUPING); +PHPBN2(POSITIVE_SIGN); +PHPBN2(NEGATIVE_SIGN); +PHPBN2(INT_FRAC_DIGITS); +PHPBN2(FRAC_DIGITS); +PHPBN2(P_CS_PRECEDES); +PHPBN2(P_SEP_BY_SPACE); +PHPBN2(N_CS_PRECEDES); +PHPBN2(N_SEP_BY_SPACE); +PHPBN2(P_SIGN_POSN); +PHPBN2(N_SIGN_POSN); +PHPBN2(DECIMAL_POINT); +PHPBN2(RADIXCHAR); +PHPBN2(THOUSANDS_SEP); +PHPBN2(THOUSEP); +PHPBN2(GROUPING); +PHPBN2(YESEXPR); +PHPBN2(NOEXPR); +PHPBN2(YESSTR); +PHPBN2(NOSTR); +PHPBN2(CODESET); +PHPBN2(LOG_EMERG); +PHPBN2(LOG_ALERT); +PHPBN2(LOG_CRIT); +PHPBN2(LOG_ERR); +PHPBN2(LOG_WARNING); +PHPBN2(LOG_NOTICE); +PHPBN2(LOG_INFO); +PHPBN2(LOG_DEBUG); +PHPBN2(LOG_KERN); +PHPBN2(LOG_USER); +PHPBN2(LOG_MAIL); +PHPBN2(LOG_DAEMON); +PHPBN2(LOG_AUTH); +PHPBN2(LOG_SYSLOG); +PHPBN2(LOG_LPR); +PHPBN2(LOG_NEWS); +PHPBN2(LOG_UUCP); +PHPBN2(LOG_CRON); +PHPBN2(LOG_AUTHPRIV); +PHPBN2(LOG_LOCAL0); +PHPBN2(LOG_LOCAL1); +PHPBN2(LOG_LOCAL2); +PHPBN2(LOG_LOCAL3); +PHPBN2(LOG_LOCAL4); +PHPBN2(LOG_LOCAL5); +PHPBN2(LOG_LOCAL6); +PHPBN2(LOG_LOCAL7); +PHPBN2(LOG_PID); +PHPBN2(LOG_CONS); +PHPBN2(LOG_ODELAY); +PHPBN2(LOG_NDELAY); +PHPBN2(LOG_NOWAIT); +PHPBN2(LOG_PERROR); + +/* Added in PHP 5.2 */ +PHPBN2(PREG_BACKTRACK_LIMIT_ERROR); +PHPBN2(PREG_BAD_UTF8_ERROR); +PHPBN2(PREG_INTERNAL_ERROR); +PHPBN2(PREG_NO_ERROR); +PHPBN2(PREG_RECURSION_LIMIT_ERROR); +PHPBN2(UPLOAD_ERR_EXTENSION); +PHPBN2(STREAM_SHUT_RD); +PHPBN2(STREAM_SHUT_WR); +PHPBN2(STREAM_SHUT_RDWR); +PHPBN2(CURLE_FILESIZE_EXCEEDED); +PHPBN2(CURLE_FTP_SSL_FAILED); +PHPBN2(CURLE_LDAP_INVALID_URL); +PHPBN2(CURLFTPAUTH_DEFAULT); +PHPBN2(CURLFTPAUTH_SSL); +PHPBN2(CURLFTPAUTH_TLS); +PHPBN2(CURLFTPSSL_ALL); +PHPBN2(CURLFTPSSL_CONTROL); +PHPBN2(CURLFTPSSL_NONE); +PHPBN2(CURLFTPSSL_TRY); +PHPBN2(CURLOPT_FTP_SSL); +PHPBN2(CURLOPT_FTPSSLAUTH); +PHPBN2(CURLOPT_TCP_NODELAY); // Added in PHP 5.2.1 +PHPBN2(CURLOPT_TIMEOUT_MS); // Added in PHP 5.2.3 +PHPBN2(CURLOPT_CONNECTTIMEOUT_MS); // Added in PHP 5.2.3 +PHPBN2(GMP_VERSION); // Added in PHP 5.2.2 +PHPBN2(SWFTEXTFIELD_USEFONT); +PHPBN2(SWFTEXTFIELD_AUTOSIZE); +PHPBN2(SWF_SOUND_NOT_COMPRESSED); +PHPBN2(SWF_SOUND_ADPCM_COMPRESSED); +PHPBN2(SWF_SOUND_MP3_COMPRESSED); +PHPBN2(SWF_SOUND_NOT_COMPRESSED_LE); +PHPBN2(SWF_SOUND_NELLY_COMPRESSED); +PHPBN2(SWF_SOUND_5KHZ); +PHPBN2(SWF_SOUND_11KHZ); +PHPBN2(SWF_SOUND_22KHZ); +PHPBN2(SWF_SOUND_44KHZ); +PHPBN2(SWF_SOUND_8BITS); +PHPBN2(SWF_SOUND_16BITS); +PHPBN2(SWF_SOUND_MONO); +PHPBN2(SWF_SOUND_STEREO); +PHPBN2(OPENSSL_VERSION_NUMBER); +PHPBN2(SNMP_OID_OUTPUT_FULL); +PHPBN2(SNMP_OID_OUTPUT_NUMERIC); +PHPBN2(MSG_EAGAIN); +PHPBN2(MSG_ENOMSG); + +/* Added in PHP 5.3 */ +PHPBN2(CURLOPT_PROGRESSFUNCTION); +PHPBN2(IMG_FILTER_PIXELATE); +PHPBN2(JSON_ERROR_CTRL_CHAR); +PHPBN2(JSON_ERROR_DEPTH); +PHPBN2(JSON_ERROR_NONE); +PHPBN2(JSON_ERROR_STATE_MISMATCH); +PHPBN2(JSON_ERROR_SYNTAX); +PHPBN2(JSON_FORCE_OBJECT); +PHPBN2(JSON_HEX_TAG); +PHPBN2(JSON_HEX_AMP); +PHPBN2(JSON_HEX_APOS); +PHPBN2(JSON_HEX_QUOT); +PHPBN2(LDAP_OPT_NETWORK_TIMEOUT); +PHPBN2(LIBXML_LOADED_VERSION); +PHPBN2(PREG_BAD_UTF8_OFFSET_ERROR); +PHPBN2(BUS_ADRALN); +PHPBN2(BUS_ADRERR); +PHPBN2(BUS_OBJERR); +PHPBN2(CLD_CONTIUNED); +PHPBN2(CLD_DUMPED); +PHPBN2(CLD_EXITED); +PHPBN2(CLD_KILLED); +PHPBN2(CLD_STOPPED); +PHPBN2(CLD_TRAPPED); +PHPBN2(FPE_FLTDIV); +PHPBN2(FPE_FLTINV); +PHPBN2(FPE_FLTOVF); +PHPBN2(FPE_FLTRES); +PHPBN2(FPE_FLTSUB); +PHPBN2(FPE_FLTUND); +PHPBN2(FPE_INTDIV); +PHPBN2(FPE_INTOVF); +PHPBN2(ILL_BADSTK); +PHPBN2(ILL_COPROC); +PHPBN2(ILL_ILLADR); +PHPBN2(ILL_ILLOPC); +PHPBN2(ILL_ILLOPN); +PHPBN2(ILL_ILLTRP); +PHPBN2(ILL_PRVOPC); +PHPBN2(ILL_PRVREG); +PHPBN2(POLL_ERR); +PHPBN2(POLL_HUP); +PHPBN2(POLL_IN); +PHPBN2(POLL_MSG); +PHPBN2(POLL_OUT); +PHPBN2(POLL_PRI); +PHPBN2(SEGV_ACCERR); +PHPBN2(SEGV_MAPERR); +PHPBN2(SI_ASYNCIO); +PHPBN2(SI_KERNEL); +PHPBN2(SI_MESGQ); +PHPBN2(SI_NOINFO); +PHPBN2(SI_QUEUE); +PHPBN2(SI_SIGIO); +PHPBN2(SI_TIMER); +PHPBN2(SI_TKILL); +PHPBN2(SI_USER); +PHPBN2(SIG_BLOCK); +PHPBN2(SIG_SETMASK); +PHPBN2(SIG_UNBLOCK); +PHPBN2(TRAP_BRKPT); +PHPBN2(TRAP_TRACE); + +/* Added in PHP 5.4 */ +PHPBN2(ENT_DISALLOWED); +PHPBN2(ENT_HTML401); +PHPBN2(ENT_HTML5); +PHPBN2(ENT_SUBSTITUTE); +PHPBN2(ENT_XML1); +PHPBN2(ENT_XHTML); +PHPBN2(IPPROTO_IP); +PHPBN2(IPPROTO_IPV6); +PHPBN2(IPV6_MULTICAST_HOPS); +PHPBN2(IPV6_MULTICAST_IF); +PHPBN2(IPV6_MULTICAST_LOOP); +PHPBN2(IP_MULTICAST_IF); +PHPBN2(IP_MULTICAST_LOOP); +PHPBN2(IP_MULTICAST_TTL); +PHPBN2(MCAST_JOIN_GROUP); +PHPBN2(MCAST_LEAVE_GROUP); +PHPBN2(MCAST_BLOCK_SOURCE); +PHPBN2(MCAST_UNBLOCK_SOURCE); +PHPBN2(MCAST_JOIN_SOURCE_GROUP); +PHPBN2(MCAST_LEAVE_SOURCE_GROUP); +PHPBN2(CURLOPT_MAX_RECV_SPEED_LARGE); +PHPBN2(CURLOPT_MAX_SEND_SPEED_LARGE); +PHPBN2(LIBXML_HTML_NODEFDTD); +PHPBN2(LIBXML_HTML_NOIMPLIED); +PHPBN2(LIBXML_PEDANTIC); +PHPBN2(OPENSSL_CIPHER_AES_128_CBC); +PHPBN2(OPENSSL_CIPHER_AES_192_CBC); +PHPBN2(OPENSSL_CIPHER_AES_256_CBC); +PHPBN2(OPENSSL_RAW_DATA); +PHPBN2(OPENSSL_ZERO_PADDING); +PHPBN2(PHP_OUTPUT_HANDLER_CLEAN); +PHPBN2(PHP_OUTPUT_HANDLER_CLEANABLE); +PHPBN2(PHP_OUTPUT_HANDLER_DISABLED); +PHPBN2(PHP_OUTPUT_HANDLER_FINAL); +PHPBN2(PHP_OUTPUT_HANDLER_FLUSH); +PHPBN2(PHP_OUTPUT_HANDLER_FLUSHABLE); +PHPBN2(PHP_OUTPUT_HANDLER_REMOVABLE); +PHPBN2(PHP_OUTPUT_HANDLER_STARTED); +PHPBN2(PHP_OUTPUT_HANDLER_STDFLAGS); +PHPBN2(PHP_OUTPUT_HANDLER_WRITE); +PHPBN2(PHP_SESSION_ACTIVE); +PHPBN2(PHP_SESSION_DISABLED); +PHPBN2(PHP_SESSION_NONE); +PHPBN2(STREAM_META_ACCESS); +PHPBN2(STREAM_META_GROUP); +PHPBN2(STREAM_META_GROUP_NAME); +PHPBN2(STREAM_META_OWNER); +PHPBN2(STREAM_META_OWNER_NAME); +PHPBN2(STREAM_META_TOUCH); +PHPBN2(ZLIB_ENCODING_DEFLATE); +PHPBN2(ZLIB_ENCODING_GZIP); +PHPBN2(ZLIB_ENCODING_RAW); +PHPBN2(U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR); +PHPBN2(IDNA_CHECK_BIDI); +PHPBN2(IDNA_CHECK_CONTEXTJ); +PHPBN2(IDNA_NONTRANSITIONAL_TO_ASCII); +PHPBN2(IDNA_NONTRANSITIONAL_TO_UNICODE); +PHPBN2(INTL_IDNA_VARIANT_2003); +PHPBN2(INTL_IDNA_VARIANT_UTS46); +PHPBN2(IDNA_ERROR_EMPTY_LABEL); +PHPBN2(IDNA_ERROR_LABEL_TOO_LONG); +PHPBN2(IDNA_ERROR_DOMAIN_NAME_TOO_LONG); +PHPBN2(IDNA_ERROR_LEADING_HYPHEN); +PHPBN2(IDNA_ERROR_TRAILING_HYPHEN); +PHPBN2(IDNA_ERROR_HYPHEN_3_4); +PHPBN2(IDNA_ERROR_LEADING_COMBINING_MARK); +PHPBN2(IDNA_ERROR_DISALLOWED); +PHPBN2(IDNA_ERROR_PUNYCODE); +PHPBN2(IDNA_ERROR_LABEL_HAS_DOT); +PHPBN2(IDNA_ERROR_INVALID_ACE_LABEL); +PHPBN2(IDNA_ERROR_BIDI); +PHPBN2(IDNA_ERROR_CONTEXTJ); +PHPBN2(JSON_PRETTY_PRINT); +PHPBN2(JSON_UNESCAPED_SLASHES); +PHPBN2(JSON_NUMERIC_CHECK); +PHPBN2(JSON_UNESCAPED_UNICODE); +PHPBN2(JSON_BIGINT_AS_STRING); + +/* Added in PHP 5.5 */ +PHPBN2(IMG_AFFINE_TRANSLATE); +PHPBN2(IMG_AFFINE_SCALE); +PHPBN2(IMG_AFFINE_ROTATE); +PHPBN2(IMG_AFFINE_SHEAR_HORIZONTAL); +PHPBN2(IMG_AFFINE_SHEAR_VERTICAL); +PHPBN2(IMG_CROP_DEFAULT); +PHPBN2(IMG_CROP_TRANSPARENT); +PHPBN2(IMG_CROP_BLACK); +PHPBN2(IMG_CROP_WHITE); +PHPBN2(IMG_CROP_SIDES); +PHPBN2(IMG_FLIP_BOTH); +PHPBN2(IMG_FLIP_HORIZONTAL); +PHPBN2(IMG_FLIP_VERTICAL); +PHPBN2(IMG_BELL); +PHPBN2(IMG_BESSEL); +PHPBN2(IMG_BICUBIC); +PHPBN2(IMG_BICUBIC_FIXED); +PHPBN2(IMG_BLACKMAN); +PHPBN2(IMG_BOX); +PHPBN2(IMG_BSPLINE); +PHPBN2(IMG_CATMULLROM); +PHPBN2(IMG_GAUSSIAN); +PHPBN2(IMG_GENERALIZED_CUBIC); +PHPBN2(IMG_HERMITE); +PHPBN2(IMG_HAMMING); +PHPBN2(IMG_HANNING); +PHPBN2(IMG_MITCHELL); +PHPBN2(IMG_POWER); +PHPBN2(IMG_QUADRATIC); +PHPBN2(IMG_SINC); +PHPBN2(IMG_NEAREST_NEIGHBOUR); +PHPBN2(IMG_WEIGHTED4); +PHPBN2(IMG_TRIANGLE); +PHPBN2(JSON_ERROR_RECURSION); +PHPBN2(JSON_ERROR_INF_OR_NAN); +PHPBN2(JSON_ERROR_UNSUPPORTED_TYPE); +PHPBN2(MYSQLI_SERVER_PUBLIC_KEY); + +/* Added in PHP 5.6 */ +PHPBN2(LDAP_ESCAPE_DN); +PHPBN2(LDAP_ESCAPE_FILTER); +PHPBN2(OPENSSL_DEFAULT_STREAM_CIPHERS); +PHPBN2(STREAM_CRYPTO_METHOD_ANY_CLIENT); +PHPBN2(STREAM_CRYPTO_METHOD_ANY_SERVER); +PHPBN2(STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT); +PHPBN2(STREAM_CRYPTO_METHOD_TLSv1_0_SERVER); +PHPBN2(STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT); +PHPBN2(STREAM_CRYPTO_METHOD_TLSv1_1_SERVER); +PHPBN2(STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT); +PHPBN2(STREAM_CRYPTO_METHOD_TLSv1_2_SERVER); +PHPBN2(PGSQL_CONNECT_ASYNC); +PHPBN2(PGSQL_CONNECTION_AUTH_OK); +PHPBN2(PGSQL_CONNECTION_AWAITING_RESPONSE); +PHPBN2(PGSQL_CONNECTION_MADE); +PHPBN2(PGSQL_CONNECTION_SETENV); +PHPBN2(PGSQL_CONNECTION_SSL_STARTUP); +PHPBN2(PGSQL_CONNECTION_STARTED); +PHPBN2(PGSQL_DML_ESCAPE); +PHPBN2(PGSQL_POLLING_ACTIVE); +PHPBN2(PGSQL_POLLING_FAILED); +PHPBN2(PGSQL_POLLING_OK); +PHPBN2(PGSQL_POLLING_READING); +PHPBN2(PGSQL_POLLING_WRITING); + +/* Class names reserved by PHP (case insensitive) */ +PHPCN(directory); +PHPCN(stdclass); +PHPCN(__php_incomplete_class); +/* Added in PHP5. */ +PHPCN(exception); +PHPCN(errorexception); // As of PHP 5.1 +PHPCN(php_user_filter); +PHPCN(closure); // As of PHP 5.3 +PHPCN(generator); // As of PHP 5.5 +PHPCN(self); +PHPCN(static); +PHPCN(parent); +/* From extensions (which of these are actually predefined depends which + * extensions are loaded by default). */ +PHPCN(xmlwriter); +PHPCN(libxmlerror); +PHPCN(simplexmlelement); +PHPCN(soapclient); +PHPCN(soapvar); +PHPCN(soapserver); +PHPCN(soapfault); +PHPCN(soapparam); +PHPCN(soapheader); +PHPCN(recursiveiteratoriterator); +PHPCN(filteriterator); +PHPCN(recursivefilteriterator); +PHPCN(parentiterator); +PHPCN(limititerator); +PHPCN(cachingiterator); +PHPCN(recursivecachingiterator); +PHPCN(iteratoriterator); +PHPCN(norewinditerator); +PHPCN(appenditerator); +PHPCN(infiniteiterator); +PHPCN(emptyiterator); +PHPCN(arrayobject); +PHPCN(arrayiterator); +PHPCN(recursivearrayiterator); +PHPCN(splfileinfo); +PHPCN(directoryiterator); +PHPCN(recursivedirectoryiterator); +PHPCN(splfileobject); +PHPCN(spltempfileobject); +PHPCN(simplexmliterator); +PHPCN(logicexception); +PHPCN(badfunctioncallexception); +PHPCN(badmethodcallexception); +PHPCN(domainexception); +PHPCN(invalidargumentexception); +PHPCN(lengthexception); +PHPCN(outofrangeexception); +PHPCN(runtimeexception); +PHPCN(outofboundsexception); +PHPCN(overflowexception); +PHPCN(rangeexception); +PHPCN(underflowexception); +PHPCN(unexpectedvalueexception); +PHPCN(splobjectstorage); +PHPCN(reflectionexception); +PHPCN(reflection); +PHPCN(reflectionfunction); +PHPCN(reflectionparameter); +PHPCN(reflectionmethod); +PHPCN(reflectionclass); +PHPCN(reflectionobject); +PHPCN(reflectionproperty); +PHPCN(reflectionextension); +PHPCN(domexception); +PHPCN(domstringlist); +PHPCN(domnamelist); +PHPCN(domimplementationlist); +PHPCN(domimplementationsource); +PHPCN(domimplementation); +PHPCN(domnode); +PHPCN(domnamespacenode); +PHPCN(domdocumentfragment); +PHPCN(domdocument); +PHPCN(domnodelist); +PHPCN(domnamednodemap); +PHPCN(domcharacterdata); +PHPCN(domattr); +PHPCN(domelement); +PHPCN(domtext); +PHPCN(domcomment); +PHPCN(domtypeinfo); +PHPCN(domuserdatahandler); +PHPCN(domdomerror); +PHPCN(domerrorhandler); +PHPCN(domlocator); +PHPCN(domconfiguration); +PHPCN(domcdatasection); +PHPCN(domdocumenttype); +PHPCN(domnotation); +PHPCN(domentity); +PHPCN(domentityreference); +PHPCN(domprocessinginstruction); +PHPCN(domstringextend); +PHPCN(domxpath); +PHPCN(xmlreader); +PHPCN(sqlitedatabase); +PHPCN(sqliteresult); +PHPCN(sqliteunbuffered); +PHPCN(sqliteexception); +PHPCN(datetime); + +/* Built-in PHP functions (incomplete). */ +/* Includes Array Functions - http://php.net/manual/en/ref.array.php */ +/* Check is case insensitive - these *MUST* be listed in lower case here */ +PHPFN(acos); +PHPFN(array_change_key_case); +PHPFN(array_chunk); +PHPFN(array_column); +PHPFN(array_combine); +PHPFN(array_count_values); +PHPFN(array_diff); +PHPFN(array_diff_assoc); +PHPFN(array_diff_key); +PHPFN(array_diff_uassoc); +PHPFN(array_diff_ukey); +PHPFN(array_fill); +PHPFN(array_fill_keys); +PHPFN(array_filter); +PHPFN(array_flip); +PHPFN(array_intersect); +PHPFN(array_intersect_assoc); +PHPFN(array_intersect_key); +PHPFN(array_intersect_uassoc); +PHPFN(array_intersect_ukey); +PHPFN(array_key_exists); +PHPFN(array_keys); +PHPFN(array_map); +PHPFN(array_merge); +PHPFN(array_merge_recursive); +PHPFN(array_multisort); +PHPFN(array_pad); +PHPFN(array_pop); +PHPFN(array_product); +PHPFN(array_push); +PHPFN(array_rand); +PHPFN(array_reduce); +PHPFN(array_replace); +PHPFN(array_replace_recursive); +PHPFN(array_reverse); +PHPFN(array_search); +PHPFN(array_shift); +PHPFN(array_slice); +PHPFN(array_splice); +PHPFN(array_sum); +PHPFN(array_udiff); +PHPFN(array_udiff_assoc); +PHPFN(array_udiff_uassoc); +PHPFN(array_uintersect); +PHPFN(array_uintersect_assoc); +PHPFN(array_uintersect_uassoc); +PHPFN(array_unique); +PHPFN(array_unshift); +PHPFN(array_values); +PHPFN(array_walk); +PHPFN(array_walk_recursive); +PHPFN(arsort); +PHPFN(asin); +PHPFN(asort); +PHPFN(atan); +PHPFN(atan2); +PHPFN(ceil); +PHPFN(compact); +PHPFN(cos); +PHPFN(cosh); +PHPFN(count); +PHPFN(current); +PHPFN(each); +PHPFN(end); +PHPFN(exp); +PHPFN(extract); +PHPFN(floor); +PHPFN(fmod); +PHPFN(in_array); +PHPFN(key); +PHPFN(key_exists); +PHPFN(krsort); +PHPFN(ksort); +PHPFN(log); +PHPFN(log10); +PHPFN(max); +PHPFN(min); +PHPFN(natcasesort); +PHPFN(natsort); +PHPFN(next); +PHPFN(pos); +PHPFN(pow); +PHPFN(prev); +PHPFN(range); +PHPFN(reset); +PHPFN(rsort); +PHPFN(shuffle); +PHPFN(sin); +PHPFN(sinh); +PHPFN(sizeof); +PHPFN(sort); +PHPFN(sqrt); +PHPFN(tan); +PHPFN(tanh); +PHPFN(uasort); +PHPFN(uksort); +PHPFN(usort); + +#undef PHPKW +#undef PHPBN1a +#undef PHPBN1b +#undef PHPBN1 +#undef PHPBN2a +#undef PHPBN2b +#undef PHPBN2 +#undef PHPCN +#undef PHPFN diff --git a/Lib/php5/phppointers.i b/Lib/php5/phppointers.i new file mode 100644 index 000000000..e50ada7ac --- /dev/null +++ b/Lib/php5/phppointers.i @@ -0,0 +1,42 @@ +%define %pass_by_ref( TYPE, CONVERT_IN, CONVERT_OUT ) +%typemap(in, byref=1) TYPE *REF ($*1_ltype tmp), + TYPE &REF ($*1_ltype tmp) +%{ + /* First Check for SWIG wrapped type */ + if ( ZVAL_IS_NULL( *$input ) ) { + $1 = 0; + } else if ( PZVAL_IS_REF( *$input ) ) { + /* Not swig wrapped type, so we check if it's a PHP reference type */ + CONVERT_IN( tmp, $*1_ltype, $input ); + $1 = &tmp; + } else { + SWIG_PHP_Error( E_ERROR, SWIG_PHP_Arg_Error_Msg($argnum, Expected a reference) ); + } +%} +%typemap(argout) TYPE *REF, + TYPE &REF + "CONVERT_OUT(*$input, tmp$argnum );"; +%enddef + +%pass_by_ref( size_t, CONVERT_INT_IN, ZVAL_LONG ); + +%pass_by_ref( signed int, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( int, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( unsigned int, CONVERT_INT_IN, ZVAL_LONG ); + +%pass_by_ref( signed short, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( short, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( unsigned short, CONVERT_INT_IN, ZVAL_LONG ); + +%pass_by_ref( signed long, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( long, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( unsigned long, CONVERT_INT_IN, ZVAL_LONG ); + +%pass_by_ref( signed char, CONVERT_INT_IN, ZVAL_LONG ); +%pass_by_ref( char, CONVERT_CHAR_IN, ZVAL_STRING ); +%pass_by_ref( unsigned char, CONVERT_INT_IN, ZVAL_LONG ); + +%pass_by_ref( float, CONVERT_FLOAT_IN, ZVAL_DOUBLE ); +%pass_by_ref( double, CONVERT_FLOAT_IN, ZVAL_DOUBLE ); + +%pass_by_ref( char *, CONVERT_CHAR_IN, ZVAL_STRING ); diff --git a/Lib/php5/phprun.swg b/Lib/php5/phprun.swg new file mode 100644 index 000000000..3900df9ef --- /dev/null +++ b/Lib/php5/phprun.swg @@ -0,0 +1,280 @@ +/* ----------------------------------------------------------------------------- + * phprun.swg + * + * PHP runtime library + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#endif +#include "zend.h" +#include "zend_API.h" +#include "zend_exceptions.h" +#include "php.h" + +#if PHP_MAJOR_VERSION != 5 +# error These bindings need PHP5 - to generate PHP7 bindings use: swig -php7 +#endif + +#include "ext/standard/php_string.h" +#include /* for abort(), used in generated code. */ + +#ifdef ZEND_RAW_FENTRY +/* ZEND_RAW_FENTRY was added somewhere between 5.2.0 and 5.2.3 */ +# define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_RAW_FENTRY((char*)#ZN, N, A, 0) +#else +/* This causes warnings from GCC >= 4.2 (assigning a string literal to char*). + * But this seems to be unavoidable without directly assuming knowledge of + * the structure, which changed between PHP4 and PHP5. */ +# define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_NAMED_FE(ZN, N, A) +#endif + +#ifndef ZEND_FE_END +# define ZEND_FE_END { NULL, NULL, NULL } +#endif + +#ifndef Z_SET_ISREF_P +/* For PHP < 5.3 */ +# define Z_SET_ISREF_P(z) (z)->is_ref = 1 +#endif +#ifndef Z_SET_REFCOUNT_P +/* For PHP < 5.3 */ +# define Z_SET_REFCOUNT_P(z, rc) (z)->refcount = (rc) +#endif + +#define SWIG_LONG_CONSTANT(N, V) zend_register_long_constant((char*)#N, sizeof(#N), V, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC) +#define SWIG_DOUBLE_CONSTANT(N, V) zend_register_double_constant((char*)#N, sizeof(#N), V, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC) +#define SWIG_STRING_CONSTANT(N, V) zend_register_stringl_constant((char*)#N, sizeof(#N), (char*)(V), strlen(V), CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC) +#define SWIG_CHAR_CONSTANT(N, V) do {\ + static char swig_char = (V);\ + zend_register_stringl_constant((char*)#N, sizeof(#N), &swig_char, 1, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC);\ +} while (0) + +/* These TSRMLS_ stuff should already be defined now, but with older php under + redhat are not... */ +#ifndef TSRMLS_D +#define TSRMLS_D +#endif +#ifndef TSRMLS_DC +#define TSRMLS_DC +#endif +#ifndef TSRMLS_C +#define TSRMLS_C +#endif +#ifndef TSRMLS_CC +#define TSRMLS_CC +#endif + +#ifdef __cplusplus +} +#endif + +/* But in fact SWIG_ConvertPtr is the native interface for getting typed + pointer values out of zvals. We need the TSRMLS_ macros for when we + make PHP type calls later as we handle php resources */ +#define SWIG_ConvertPtr(obj,pp,type,flags) SWIG_ZTS_ConvertPtr(obj,pp,type,flags TSRMLS_CC) + + +#define SWIG_fail goto fail + +static const char *default_error_msg = "Unknown error occurred"; +static int default_error_code = E_ERROR; + +#define SWIG_PHP_Arg_Error_Msg(argnum,extramsg) "Error in argument " #argnum " "#extramsg + +#define SWIG_PHP_Error(code,msg) do { SWIG_ErrorCode() = code; SWIG_ErrorMsg() = msg; SWIG_fail; } while (0) + +#define SWIG_contract_assert(expr,msg) \ + if (!(expr) ) { zend_printf("Contract Assert Failed %s\n",msg ); } else + +/* Standard SWIG API */ +#define SWIG_GetModule(clientdata) SWIG_Php_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_Php_SetModule(pointer) + +/* used to wrap returned objects in so we know whether they are newobject + and need freeing, or not */ +typedef struct { + void * ptr; + int newobject; +} swig_object_wrapper; + +#define SWIG_SetPointerZval(a,b,c,d) SWIG_ZTS_SetPointerZval(a,b,c,d TSRMLS_CC) +#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) + +static void +SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject TSRMLS_DC) { + /* + * First test for Null pointers. Return those as PHP native NULL + */ + if (!ptr ) { + ZVAL_NULL(z); + return; + } + if (type->clientdata) { + swig_object_wrapper *value; + if (! (*(int *)(type->clientdata))) + zend_error(E_ERROR, "Type: %s failed to register with zend",type->name); + value=(swig_object_wrapper *)emalloc(sizeof(swig_object_wrapper)); + value->ptr=ptr; + value->newobject=(newobject & 1); + if ((newobject & 2) == 0) { + /* Just register the pointer as a resource. */ + ZEND_REGISTER_RESOURCE(z, value, *(int *)(type->clientdata)); + } else { + /* + * Wrap the resource in an object, the resource will be accessible + * via the "_cPtr" member. This is currently only used by + * directorin typemaps. + */ + zval *resource; + zend_class_entry **ce = NULL; + const char *type_name = type->name+3; /* +3 so: _p_Foo -> Foo */ + size_t type_name_len; + int result; + const char * p; + + /* Namespace__Foo -> Foo */ + /* FIXME: ugly and goes wrong for classes with __ in their names. */ + while ((p = strstr(type_name, "__")) != NULL) { + type_name = p + 2; + } + type_name_len = strlen(type_name); + + MAKE_STD_ZVAL(resource); + ZEND_REGISTER_RESOURCE(resource, value, *(int *)(type->clientdata)); + if (SWIG_PREFIX_LEN > 0) { + char * classname = (char*)emalloc(SWIG_PREFIX_LEN + type_name_len + 1); + strcpy(classname, SWIG_PREFIX); + strcpy(classname + SWIG_PREFIX_LEN, type_name); + result = zend_lookup_class(classname, SWIG_PREFIX_LEN + type_name_len, &ce TSRMLS_CC); + efree(classname); + } else { + result = zend_lookup_class((char *)type_name, type_name_len, &ce TSRMLS_CC); + } + if (result != SUCCESS) { + /* class does not exist */ + object_init(z); + } else { + object_init_ex(z, *ce); + } + Z_SET_REFCOUNT_P(z, 1); + Z_SET_ISREF_P(z); + zend_hash_update(HASH_OF(z), (char*)"_cPtr", sizeof("_cPtr"), (void*)&resource, sizeof(zval*), NULL); + } + return; + } + zend_error(E_ERROR, "Type: %s not registered with zend",type->name); +} + +/* This pointer conversion routine takes the native pointer p (along with + its type name) and converts it by calling appropriate casting functions + according to ty. The resultant pointer is returned, or NULL is returned + if the pointer can't be cast. + + Sadly PHP has no API to find a type name from a type id, only from an + instance of a resource of the type id, so we have to pass type_name as well. + + The two functions which might call this are: + SWIG_ZTS_ConvertResourcePtr which gets the type name from the resource + and the registered zend destructors for which we have one per type each + with the type name hard wired in. */ +static void * +SWIG_ZTS_ConvertResourceData(void * p, const char *type_name, swig_type_info *ty TSRMLS_DC) { + swig_cast_info *tc; + void *result = 0; + + if (!ty) { + /* They don't care about the target type, so just pass on the pointer! */ + return p; + } + + if (! type_name) { + /* can't convert p to ptr type ty if we don't know what type p is */ + return NULL; + } + + /* convert and cast p from type_name to ptr as ty. */ + tc = SWIG_TypeCheck(type_name, ty); + if (tc) { + int newmemory = 0; + result = SWIG_TypeCast(tc, p, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } + return result; +} + +/* This function returns a pointer of type ty by extracting the pointer + and type info from the resource in z. z must be a resource. + If it fails, NULL is returned. + It uses SWIG_ZTS_ConvertResourceData to do the real work. */ +static void * +SWIG_ZTS_ConvertResourcePtr(zval *z, swig_type_info *ty, int flags TSRMLS_DC) { + swig_object_wrapper *value; + void *p; + int type; + const char *type_name; + + value = (swig_object_wrapper *) zend_list_find(z->value.lval, &type); + if (type==-1) return NULL; + if (flags & SWIG_POINTER_DISOWN) { + value->newobject = 0; + } + p = value->ptr; + + type_name=zend_rsrc_list_get_rsrc_type(z->value.lval TSRMLS_CC); + + return SWIG_ZTS_ConvertResourceData(p, type_name, ty TSRMLS_CC); +} + +/* We allow passing of a RESOURCE pointing to the object or an OBJECT whose + _cPtr is a resource pointing to the object */ +static int +SWIG_ZTS_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags TSRMLS_DC) { + if (z == NULL) { + *ptr = 0; + return 0; + } + + switch (z->type) { + case IS_OBJECT: { + zval ** _cPtr; + if (zend_hash_find(HASH_OF(z),(char*)"_cPtr",sizeof("_cPtr"),(void**)&_cPtr)==SUCCESS) { + if ((*_cPtr)->type==IS_RESOURCE) { + *ptr = SWIG_ZTS_ConvertResourcePtr(*_cPtr, ty, flags TSRMLS_CC); + return (*ptr == NULL ? -1 : 0); + } + } + break; + } + case IS_RESOURCE: + *ptr = SWIG_ZTS_ConvertResourcePtr(z, ty, flags TSRMLS_CC); + return (*ptr == NULL ? -1 : 0); + case IS_NULL: + *ptr = 0; + return 0; + } + + return -1; +} + +static char const_name[] = "swig_runtime_data_type_pointer"; +static swig_module_info *SWIG_Php_GetModule() { + zval *pointer; + swig_module_info *ret = 0; + TSRMLS_FETCH(); + + MAKE_STD_ZVAL(pointer); + + if (zend_get_constant(const_name, sizeof(const_name) - 1, pointer TSRMLS_CC)) { + if (pointer->type == IS_LONG) { + ret = (swig_module_info *) pointer->value.lval; + } + } + FREE_ZVAL(pointer); + return ret; +} + +static void SWIG_Php_SetModule(swig_module_info *pointer) { + TSRMLS_FETCH(); + REGISTER_MAIN_LONG_CONSTANT(const_name, (long) pointer, 0); +} diff --git a/Lib/php5/std_common.i b/Lib/php5/std_common.i new file mode 100644 index 000000000..092bf012b --- /dev/null +++ b/Lib/php5/std_common.i @@ -0,0 +1,10 @@ +/* ----------------------------------------------------------------------------- + * std_common.i + * + * SWIG typemaps for STL - common utilities + * ----------------------------------------------------------------------------- */ + +%include + +%apply size_t { std::size_t }; + diff --git a/Lib/php5/std_deque.i b/Lib/php5/std_deque.i new file mode 100644 index 000000000..cb98f6c2f --- /dev/null +++ b/Lib/php5/std_deque.i @@ -0,0 +1 @@ +%include diff --git a/Lib/php5/std_map.i b/Lib/php5/std_map.i new file mode 100644 index 000000000..6d5e3db13 --- /dev/null +++ b/Lib/php5/std_map.i @@ -0,0 +1,76 @@ +/* ----------------------------------------------------------------------------- + * std_map.i + * + * SWIG typemaps for std::map + * ----------------------------------------------------------------------------- */ + +%include + +// ------------------------------------------------------------------------ +// std::map +// ------------------------------------------------------------------------ + +%{ +#include +#include +#include +%} + +// exported class + +namespace std { + + template class map { + // add typemaps here + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef K key_type; + typedef T mapped_type; + map(); + map(const map &); + + unsigned int size() const; + void clear(); + %extend { + const T& get(const K& key) throw (std::out_of_range) { + std::map::iterator i = self->find(key); + if (i != self->end()) + return i->second; + else + throw std::out_of_range("key not found"); + } + void set(const K& key, const T& x) { + (*self)[key] = x; + } + void del(const K& key) throw (std::out_of_range) { + std::map::iterator i = self->find(key); + if (i != self->end()) + self->erase(i); + else + throw std::out_of_range("key not found"); + } + bool has_key(const K& key) { + std::map::iterator i = self->find(key); + return i != self->end(); + } + bool is_empty() const { + return self->empty(); + } + } + }; + +// Legacy macros (deprecated) +%define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_key ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_value ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO, T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO) +#warning "specialize_std_map_on_both ignored - macro is deprecated and no longer necessary" +%enddef + +} diff --git a/Lib/php5/std_pair.i b/Lib/php5/std_pair.i new file mode 100644 index 000000000..fe45ee676 --- /dev/null +++ b/Lib/php5/std_pair.i @@ -0,0 +1,34 @@ +/* ----------------------------------------------------------------------------- + * std_pair.i + * + * SWIG typemaps for std::pair + * ----------------------------------------------------------------------------- */ + +%include +%include + +// ------------------------------------------------------------------------ +// std::pair +// ------------------------------------------------------------------------ + +%{ +#include +%} + +namespace std { + + template struct pair { + + pair(); + pair(T first, U second); + pair(const pair& p); + + template pair(const pair &p); + + T first; + U second; + }; + + // add specializations here + +} diff --git a/Lib/php5/std_string.i b/Lib/php5/std_string.i new file mode 100644 index 000000000..aaa5dc9cd --- /dev/null +++ b/Lib/php5/std_string.i @@ -0,0 +1,79 @@ +/* ----------------------------------------------------------------------------- + * std_string.i + * + * SWIG typemaps for std::string types + * ----------------------------------------------------------------------------- */ + +// ------------------------------------------------------------------------ +// std::string is typemapped by value +// This can prevent exporting methods which return a string +// in order for the user to modify it. +// However, I think I'll wait until someone asks for it... +// ------------------------------------------------------------------------ + +%include + +%{ +#include +%} + +namespace std { + + %naturalvar string; + + class string; + + %typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) string, const string& %{ + $1 = ( Z_TYPE_PP($input) == IS_STRING ) ? 1 : 0; + %} + + %typemap(in) string %{ + convert_to_string_ex($input); + $1.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input)); + %} + + %typemap(directorout) string %{ + convert_to_string_ex(&$input); + $result.assign(Z_STRVAL_P($input), Z_STRLEN_P($input)); + %} + + %typemap(out) string %{ + ZVAL_STRINGL($result, const_cast($1.data()), $1.size(), 1); + %} + + %typemap(directorin) string, const string& %{ + ZVAL_STRINGL($input, const_cast($1.data()), $1.size(), 1); + %} + + %typemap(out) const string & %{ + ZVAL_STRINGL($result, const_cast($1->data()), $1->size(), 1); + %} + + %typemap(throws) string, const string& %{ + zend_throw_exception(NULL, const_cast($1.c_str()), 0 TSRMLS_CC); + return; + %} + + /* These next two handle a function which takes a non-const reference to + * a std::string and modifies the string. */ + %typemap(in) string & ($*1_ltype temp) %{ + convert_to_string_ex($input); + temp.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input)); + $1 = &temp; + %} + + %typemap(directorout) string & ($*1_ltype *temp) %{ + convert_to_string_ex(&$input); + temp = new $*1_ltype(Z_STRVAL_P($input), Z_STRLEN_P($input)); + swig_acquire_ownership(temp); + $result = temp; + %} + + %typemap(argout) string & %{ + ZVAL_STRINGL(*($input), const_cast($1->data()), $1->size(), 1); + %} + + /* SWIG will apply the non-const typemap above to const string& without + * this more specific typemap. */ + %typemap(argout) const string & ""; +} diff --git a/Lib/php5/std_vector.i b/Lib/php5/std_vector.i new file mode 100644 index 000000000..9cc1486ef --- /dev/null +++ b/Lib/php5/std_vector.i @@ -0,0 +1,102 @@ +/* ----------------------------------------------------------------------------- + * std_vector.i + * ----------------------------------------------------------------------------- */ + +%include + +%{ +#include +#include +%} + +namespace std { + + template class vector { + public: + typedef size_t size_type; + typedef T value_type; + typedef const value_type& const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + void clear(); + %rename(push) push_back; + void push_back(const value_type& x); + %extend { + bool is_empty() const { + return $self->empty(); + } + T pop() throw (std::out_of_range) { + if (self->size() == 0) + throw std::out_of_range("pop from empty vector"); + T x = self->back(); + self->pop_back(); + return x; + } + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i class vector { + public: + typedef size_t size_type; + typedef bool value_type; + typedef bool const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + void clear(); + %rename(push) push_back; + void push_back(const value_type& x); + %extend { + bool is_empty() const { + return $self->empty(); + } + bool pop() throw (std::out_of_range) { + if (self->size() == 0) + throw std::out_of_range("pop from empty vector"); + bool x = self->back(); + self->pop_back(); + return x; + } + bool get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i +%include +%include +%include +%include + diff --git a/Lib/php5/typemaps.i b/Lib/php5/typemaps.i new file mode 100644 index 000000000..faae0a6ac --- /dev/null +++ b/Lib/php5/typemaps.i @@ -0,0 +1,322 @@ +/* ----------------------------------------------------------------------------- + * typemaps.i. + * + * SWIG Typemap library for PHP. + * + * This library provides standard typemaps for modifying SWIG's behavior. + * With enough entries in this file, I hope that very few people actually + * ever need to write a typemap. + * + * Define macros to define the following typemaps: + * + * TYPE *INPUT. Argument is passed in as native variable by value. + * TYPE *OUTPUT. Argument is returned as an array from the function call. + * TYPE *INOUT. Argument is passed in by value, and out as part of returned list + * TYPE *REFERENCE. Argument is passed in as native variable with value + * semantics. Variable value is changed with result. + * Use like this: + * int foo(int *REFERENCE); + * + * $a = 0; + * $rc = foo($a); + * + * Even though $a looks like it's passed by value, + * its value can be changed by foo(). + * ----------------------------------------------------------------------------- */ + +%define BOOL_TYPEMAP(TYPE) +%typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) +%{ + convert_to_boolean_ex($input); + temp = Z_LVAL_PP($input) ? true : false; + $1 = &temp; +%} +%typemap(argout) TYPE *INPUT, TYPE &INPUT ""; +%typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp), TYPE &OUTPUT(TYPE temp) "$1 = &temp;"; +%typemap(argout,fragment="t_output_helper") TYPE *OUTPUT, TYPE &OUTPUT +{ + zval *o; + MAKE_STD_ZVAL(o); + ZVAL_BOOL(o,temp$argnum); + t_output_helper( &$result, o TSRMLS_CC ); +} +%typemap(in) TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) +%{ + convert_to_boolean_ex($input); + lvalue = (*$input)->value.lval ? true : false; + $1 = &lvalue; +%} +%typemap(argout) TYPE *REFERENCE, TYPE &REFERENCE +%{ + (*$arg)->value.lval = lvalue$argnum ? true : false; + (*$arg)->type = IS_BOOL; +%} +%enddef + +%define DOUBLE_TYPEMAP(TYPE) +%typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) +%{ + convert_to_double_ex($input); + temp = (TYPE) Z_DVAL_PP($input); + $1 = &temp; +%} +%typemap(argout) TYPE *INPUT, TYPE &INPUT ""; +%typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp), TYPE &OUTPUT(TYPE temp) "$1 = &temp;"; +%typemap(argout,fragment="t_output_helper") TYPE *OUTPUT, TYPE &OUTPUT +{ + zval *o; + MAKE_STD_ZVAL(o); + ZVAL_DOUBLE(o,temp$argnum); + t_output_helper( &$result, o TSRMLS_CC ); +} +%typemap(in) TYPE *REFERENCE (TYPE dvalue), TYPE &REFERENCE (TYPE dvalue) +%{ + convert_to_double_ex($input); + dvalue = (TYPE) (*$input)->value.dval; + $1 = &dvalue; +%} +%typemap(argout) TYPE *REFERENCE, TYPE &REFERENCE +%{ + $1->value.dval = (double)(lvalue$argnum); + $1->type = IS_DOUBLE; +%} +%enddef + +%define INT_TYPEMAP(TYPE) +%typemap(in) TYPE *INPUT(TYPE temp), TYPE &INPUT(TYPE temp) +%{ + convert_to_long_ex($input); + temp = (TYPE) Z_LVAL_PP($input); + $1 = &temp; +%} +%typemap(argout) TYPE *INPUT, TYPE &INPUT ""; +%typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp), TYPE &OUTPUT(TYPE temp) "$1 = &temp;"; +%typemap(argout,fragment="t_output_helper") TYPE *OUTPUT, TYPE &OUTPUT +{ + zval *o; + MAKE_STD_ZVAL(o); + ZVAL_LONG(o,temp$argnum); + t_output_helper( &$result, o TSRMLS_CC ); +} +%typemap(in) TYPE *REFERENCE (TYPE lvalue), TYPE &REFERENCE (TYPE lvalue) +%{ + convert_to_long_ex($input); + lvalue = (TYPE) (*$input)->value.lval; + $1 = &lvalue; +%} +%typemap(argout) TYPE *REFERENCE, TYPE &REFERENCE +%{ + (*$arg)->value.lval = (long)(lvalue$argnum); + (*$arg)->type = IS_LONG; +%} +%enddef + +BOOL_TYPEMAP(bool); + +DOUBLE_TYPEMAP(float); +DOUBLE_TYPEMAP(double); + +INT_TYPEMAP(int); +INT_TYPEMAP(short); +INT_TYPEMAP(long); +INT_TYPEMAP(unsigned int); +INT_TYPEMAP(unsigned short); +INT_TYPEMAP(unsigned long); +INT_TYPEMAP(unsigned char); +INT_TYPEMAP(signed char); + +INT_TYPEMAP(long long); +%typemap(argout,fragment="t_output_helper") long long *OUTPUT +{ + zval *o; + MAKE_STD_ZVAL(o); + if ((long long)LONG_MIN <= temp$argnum && temp$argnum <= (long long)LONG_MAX) { + ZVAL_LONG(o, temp$argnum); + } else { + char temp[256]; + sprintf(temp, "%lld", (long long)temp$argnum); + ZVAL_STRING(o, temp, 1); + } + t_output_helper( &$result, o TSRMLS_CC ); +} +%typemap(in) TYPE *REFERENCE (long long lvalue) +%{ + CONVERT_LONG_LONG_IN(lvalue, long long, $input) + $1 = &lvalue; +%} +%typemap(argout) long long *REFERENCE +%{ + if ((long long)LONG_MIN <= lvalue$argnum && lvalue$argnum <= (long long)LONG_MAX) { + (*$arg)->value.lval = (long)(lvalue$argnum); + (*$arg)->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%lld", (long long)lvalue$argnum); + ZVAL_STRING((*$arg), temp, 1); + } +%} +%typemap(argout) long long &OUTPUT +%{ + if ((long long)LONG_MIN <= *arg$argnum && *arg$argnum <= (long long)LONG_MAX) { + ($result)->value.lval = (long)(*arg$argnum); + ($result)->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%lld", (long long)(*arg$argnum)); + ZVAL_STRING($result, temp, 1); + } +%} +INT_TYPEMAP(unsigned long long); +%typemap(argout,fragment="t_output_helper") unsigned long long *OUTPUT +{ + zval *o; + MAKE_STD_ZVAL(o); + if (temp$argnum <= (unsigned long long)LONG_MAX) { + ZVAL_LONG(o, temp$argnum); + } else { + char temp[256]; + sprintf(temp, "%llu", (unsigned long long)temp$argnum); + ZVAL_STRING(o, temp, 1); + } + t_output_helper( &$result, o TSRMLS_CC ); +} +%typemap(in) TYPE *REFERENCE (unsigned long long lvalue) +%{ + CONVERT_UNSIGNED_LONG_LONG_IN(lvalue, unsigned long long, $input) + $1 = &lvalue; +%} +%typemap(argout) unsigned long long *REFERENCE +%{ + if (lvalue$argnum <= (unsigned long long)LONG_MAX) { + (*$arg)->value.lval = (long)(lvalue$argnum); + (*$arg)->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%llu", (unsigned long long)lvalue$argnum); + ZVAL_STRING((*$arg), temp, 1); + } +%} +%typemap(argout) unsigned long long &OUTPUT +%{ + if (*arg$argnum <= (unsigned long long)LONG_MAX) { + ($result)->value.lval = (long)(*arg$argnum); + ($result)->type = IS_LONG; + } else { + char temp[256]; + sprintf(temp, "%llu", (unsigned long long)(*arg$argnum)); + ZVAL_STRING($result, temp, 1); + } +%} + +%typemap(in) bool *INOUT = bool *INPUT; +%typemap(in) float *INOUT = float *INPUT; +%typemap(in) double *INOUT = double *INPUT; + +%typemap(in) int *INOUT = int *INPUT; +%typemap(in) short *INOUT = short *INPUT; +%typemap(in) long *INOUT = long *INPUT; +%typemap(in) long long *INOUT = long long *INPUT; +%typemap(in) unsigned *INOUT = unsigned *INPUT; +%typemap(in) unsigned short *INOUT = unsigned short *INPUT; +%typemap(in) unsigned long *INOUT = unsigned long *INPUT; +%typemap(in) unsigned char *INOUT = unsigned char *INPUT; +%typemap(in) unsigned long long *INOUT = unsigned long long *INPUT; +%typemap(in) signed char *INOUT = signed char *INPUT; + +%typemap(in) bool &INOUT = bool *INPUT; +%typemap(in) float &INOUT = float *INPUT; +%typemap(in) double &INOUT = double *INPUT; + +%typemap(in) int &INOUT = int *INPUT; +%typemap(in) short &INOUT = short *INPUT; +%typemap(in) long &INOUT = long *INPUT; +%typemap(in) long long &INOUT = long long *INPUT; +%typemap(in) long long &INPUT = long long *INPUT; +%typemap(in) unsigned &INOUT = unsigned *INPUT; +%typemap(in) unsigned short &INOUT = unsigned short *INPUT; +%typemap(in) unsigned long &INOUT = unsigned long *INPUT; +%typemap(in) unsigned char &INOUT = unsigned char *INPUT; +%typemap(in) unsigned long long &INOUT = unsigned long long *INPUT; +%typemap(in) unsigned long long &INPUT = unsigned long long *INPUT; +%typemap(in) signed char &INOUT = signed char *INPUT; + +%typemap(argout) bool *INOUT = bool *OUTPUT; +%typemap(argout) float *INOUT = float *OUTPUT; +%typemap(argout) double *INOUT= double *OUTPUT; + +%typemap(argout) int *INOUT = int *OUTPUT; +%typemap(argout) short *INOUT = short *OUTPUT; +%typemap(argout) long *INOUT= long *OUTPUT; +%typemap(argout) long long *INOUT= long long *OUTPUT; +%typemap(argout) unsigned short *INOUT= unsigned short *OUTPUT; +%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT; +%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT; +%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT; +%typemap(argout) signed char *INOUT = signed char *OUTPUT; + +%typemap(argout) bool &INOUT = bool *OUTPUT; +%typemap(argout) float &INOUT = float *OUTPUT; +%typemap(argout) double &INOUT= double *OUTPUT; + +%typemap(argout) int &INOUT = int *OUTPUT; +%typemap(argout) short &INOUT = short *OUTPUT; +%typemap(argout) long &INOUT= long *OUTPUT; +%typemap(argout) long long &INOUT= long long *OUTPUT; +%typemap(argout) unsigned short &INOUT= unsigned short *OUTPUT; +%typemap(argout) unsigned long &INOUT = unsigned long *OUTPUT; +%typemap(argout) unsigned char &INOUT = unsigned char *OUTPUT; +%typemap(argout) unsigned long long &INOUT = unsigned long long *OUTPUT; +%typemap(argout) signed char &INOUT = signed char *OUTPUT; + +%typemap(in) char INPUT[ANY] ( char temp[$1_dim0] ) +%{ + convert_to_string_ex($input); + strncpy(temp,Z_STRVAL_PP($input),$1_dim0); + $1 = temp; +%} +%typemap(in,numinputs=0) char OUTPUT[ANY] ( char temp[$1_dim0] ) + "$1 = temp;"; +%typemap(argout,fragment="t_output_helper") char OUTPUT[ANY] +{ + zval *o; + MAKE_STD_ZVAL(o); + ZVAL_STRINGL(o,temp$argnum,$1_dim0); + t_output_helper( &$result, o TSRMLS_CC ); +} + +%typemap(in,numinputs=0) void **OUTPUT (int force), + void *&OUTPUT (int force) +%{ + /* If they pass NULL by reference, make it into a void* + This bit should go in arginit if arginit support init-ing scripting args */ + if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) { + /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */ + if (!((*$input)->type==IS_NULL && PZVAL_IS_REF(*$input))) { + /* wasn't a pre/ref/thing, OR anything like an int thing */ + SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname."); + } + } + force=0; + if (arg1==NULL) { +#ifdef __cplusplus + ptr=new $*1_ltype(); +#else + ptr=($*1_ltype) calloc(1,sizeof($*1_ltype)); +#endif + $1=&ptr; + /* have to passback arg$arg too */ + force=1; + } +%} + +%typemap(argout) void **OUTPUT, + void *&OUTPUT +%{ + if (force$argnum) { /* pass back arg$argnum through params ($arg) if we can */ + if (!PZVAL_IS_REF(*$arg)) { + SWIG_PHP_Error(E_WARNING, "Parameter $argnum of $symname wasn't passed by reference"); + } else { + SWIG_SetPointerZval(*$arg, (void *) ptr$argnum, $*1_descriptor, 1); + } + } +%} diff --git a/Lib/php5/utils.i b/Lib/php5/utils.i new file mode 100644 index 000000000..408a3b366 --- /dev/null +++ b/Lib/php5/utils.i @@ -0,0 +1,114 @@ + +%define CONVERT_BOOL_IN(lvar,t,invar) + convert_to_boolean_ex(invar); + lvar = (t) Z_LVAL_PP(invar); +%enddef + +%define CONVERT_INT_IN(lvar,t,invar) + convert_to_long_ex(invar); + lvar = (t) Z_LVAL_PP(invar); +%enddef + +%define CONVERT_LONG_LONG_IN(lvar,t,invar) + switch ((*(invar))->type) { + case IS_DOUBLE: + lvar = (t) (*(invar))->value.dval; + break; + case IS_STRING: { + char * endptr; + errno = 0; + lvar = (t) strtoll((*(invar))->value.str.val, &endptr, 10); + if (*endptr && !errno) break; + /* FALL THRU */ + } + default: + convert_to_long_ex(invar); + lvar = (t) (*(invar))->value.lval; + } +%enddef + +%define CONVERT_UNSIGNED_LONG_LONG_IN(lvar,t,invar) + switch ((*(invar))->type) { + case IS_DOUBLE: + lvar = (t) (*(invar))->value.dval; + break; + case IS_STRING: { + char * endptr; + errno = 0; + lvar = (t) strtoull((*(invar))->value.str.val, &endptr, 10); + if (*endptr && !errno) break; + /* FALL THRU */ + } + default: + convert_to_long_ex(invar); + lvar = (t) (*(invar))->value.lval; + } +%enddef + +%define CONVERT_INT_OUT(lvar,invar) + lvar = (t) Z_LVAL_PP(invar); +%enddef + +%define CONVERT_FLOAT_IN(lvar,t,invar) + convert_to_double_ex(invar); + lvar = (t) Z_DVAL_PP(invar); +%enddef + +%define CONVERT_CHAR_IN(lvar,t,invar) + convert_to_string_ex(invar); + lvar = (t) *Z_STRVAL_PP(invar); +%enddef + +%define CONVERT_STRING_IN(lvar,t,invar) + if ((*invar)->type==IS_NULL) { + lvar = (t) 0; + } else { + convert_to_string_ex(invar); + lvar = (t) Z_STRVAL_PP(invar); + } +%enddef + +%define %pass_by_val( TYPE, CONVERT_IN ) +%typemap(in) TYPE +%{ + CONVERT_IN($1,$1_ltype,$input); +%} +%typemap(in) const TYPE & ($*1_ltype temp) +%{ + CONVERT_IN(temp,$*1_ltype,$input); + $1 = &temp; +%} +%typemap(directorout) TYPE +%{ + CONVERT_IN($result,$1_ltype,&$input); +%} +%typemap(directorout) const TYPE & ($*1_ltype temp) +%{ + CONVERT_IN(temp,$*1_ltype,&$input); + $result = &temp; +%} +%enddef + +%fragment("t_output_helper","header") %{ +static void +t_output_helper(zval **target, zval *o TSRMLS_DC) { + zval *tmp; + if ( (*target)->type == IS_ARRAY ) { + /* it's already an array, just append */ + add_next_index_zval( *target, o ); + return; + } + if ( (*target)->type == IS_NULL ) { + REPLACE_ZVAL_VALUE(target,o,1); + FREE_ZVAL(o); + return; + } + ALLOC_INIT_ZVAL(tmp); + *tmp = **target; + zval_copy_ctor(tmp); + array_init(*target); + add_next_index_zval( *target, tmp); + add_next_index_zval( *target, o); + +} +%} diff --git a/Lib/python/README b/Lib/python/README index 98ec5605d..fa8ef61e7 100644 --- a/Lib/python/README +++ b/Lib/python/README @@ -15,7 +15,6 @@ complex.i C99 or C++ complex type cstring.i Various forms of C character string handling cwstring.i Various forms of C wchar_t string handling embed.i embedding the Python interpreter in something else -embed15.i embedding the Python interpreter in something else file.i FILE C type implicit.i Allow the use of implicit C++ constructors wchar.i wchar_t C type diff --git a/Lib/python/boost_shared_ptr.i b/Lib/python/boost_shared_ptr.i index 560a49f81..c031adcc8 100644 --- a/Lib/python/boost_shared_ptr.i +++ b/Lib/python/boost_shared_ptr.i @@ -51,7 +51,7 @@ %variable_fail(res, "$type", "$name"); } if (!argp) { - %argument_nullref("$type", $symname, $argnum); + %variable_nullref("$type", "$name"); } else { $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get()); if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); @@ -137,7 +137,9 @@ %variable_fail(res, "$type", "$name"); } SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared; - if (!argp) { %argument_nullref("$type", $symname, $argnum); } + if (!argp) { + %variable_nullref("$type", "$name"); + } if (newmem & SWIG_CAST_NEW_MEMORY) { tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); diff --git a/Lib/python/builtin.swg b/Lib/python/builtin.swg index 1d892375c..75b131333 100644 --- a/Lib/python/builtin.swg +++ b/Lib/python/builtin.swg @@ -1,211 +1,29 @@ -#define SWIGPY_UNARYFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a) { \ - return wrapper(a, NULL); \ -} - -#define SWIGPY_DESTRUCTOR_CLOSURE(wrapper) \ -SWIGINTERN void \ -wrapper##_closure(PyObject *a) { \ - SwigPyObject *sobj; \ - sobj = (SwigPyObject *)a; \ - Py_XDECREF(sobj->dict); \ - if (sobj->own) { \ - PyObject *o = wrapper(a, NULL); \ - Py_XDECREF(o); \ - } \ - if (PyType_IS_GC(a->ob_type)) { \ - PyObject_GC_Del(a); \ - } else { \ - PyObject_Del(a); \ - } \ -} - -#define SWIGPY_INQUIRY_CLOSURE(wrapper) \ -SWIGINTERN int \ -wrapper##_closure(PyObject *a) { \ - PyObject *pyresult; \ - int result; \ - pyresult = wrapper(a, NULL); \ - result = pyresult && PyObject_IsTrue(pyresult) ? 1 : 0; \ - Py_XDECREF(pyresult); \ - return result; \ -} - -#define SWIGPY_BINARYFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a, PyObject *b) { \ - PyObject *tuple, *result; \ - tuple = PyTuple_New(1); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, b); \ - Py_XINCREF(b); \ - result = wrapper(a, tuple); \ - Py_DECREF(tuple); \ - return result; \ -} - -typedef ternaryfunc ternarycallfunc; - -#define SWIGPY_TERNARYFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a, PyObject *b, PyObject *c) { \ - PyObject *tuple, *result; \ - tuple = PyTuple_New(2); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, b); \ - PyTuple_SET_ITEM(tuple, 1, c); \ - Py_XINCREF(b); \ - Py_XINCREF(c); \ - result = wrapper(a, tuple); \ - Py_DECREF(tuple); \ - return result; \ -} - -#define SWIGPY_TERNARYCALLFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *callable_object, PyObject *args, PyObject *) { \ - return wrapper(callable_object, args); \ -} - -#define SWIGPY_LENFUNC_CLOSURE(wrapper) \ -SWIGINTERN Py_ssize_t \ -wrapper##_closure(PyObject *a) { \ - PyObject *resultobj; \ - Py_ssize_t result; \ - resultobj = wrapper(a, NULL); \ - result = PyNumber_AsSsize_t(resultobj, NULL); \ - Py_DECREF(resultobj); \ - return result; \ -} - -#define SWIGPY_SSIZESSIZEARGFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a, Py_ssize_t b, Py_ssize_t c) { \ - PyObject *tuple, *result; \ - tuple = PyTuple_New(2); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); \ - PyTuple_SET_ITEM(tuple, 1, _PyLong_FromSsize_t(c)); \ - result = wrapper(a, tuple); \ - Py_DECREF(tuple); \ - return result; \ -} - -#define SWIGPY_SSIZESSIZEOBJARGPROC_CLOSURE(wrapper) \ -SWIGINTERN int \ -wrapper##_closure(PyObject *a, Py_ssize_t b, Py_ssize_t c, PyObject *d) { \ - PyObject *tuple, *resultobj; \ - int result; \ - tuple = PyTuple_New(d ? 3 : 2); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); \ - PyTuple_SET_ITEM(tuple, 1, _PyLong_FromSsize_t(c)); \ - if (d) { \ - PyTuple_SET_ITEM(tuple, 2, d); \ - Py_INCREF(d); \ - } \ - resultobj = wrapper(a, tuple); \ - result = resultobj ? 0 : -1; \ - Py_DECREF(tuple); \ - Py_XDECREF(resultobj); \ - return result; \ -} - -#define SWIGPY_SSIZEARGFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a, Py_ssize_t b) { \ - PyObject *tuple, *result; \ - tuple = PyTuple_New(1); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); \ - result = wrapper(a, tuple); \ - Py_DECREF(tuple); \ - return result; \ -} - -#define SWIGPY_FUNPACK_SSIZEARGFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a, Py_ssize_t b) { \ - PyObject *arg, *result; \ - arg = _PyLong_FromSsize_t(b); \ - result = wrapper(a, arg); \ - Py_DECREF(arg); \ - return result; \ -} - -#define SWIGPY_SSIZEOBJARGPROC_CLOSURE(wrapper) \ -SWIGINTERN int \ -wrapper##_closure(PyObject *a, Py_ssize_t b, PyObject *c) { \ - PyObject *tuple, *resultobj; \ - int result; \ - tuple = PyTuple_New(2); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); \ - PyTuple_SET_ITEM(tuple, 1, c); \ - Py_XINCREF(c); \ - resultobj = wrapper(a, tuple); \ - result = resultobj ? 0 : -1; \ - Py_XDECREF(resultobj); \ - Py_DECREF(tuple); \ - return result; \ -} - -#define SWIGPY_OBJOBJARGPROC_CLOSURE(wrapper) \ -SWIGINTERN int \ -wrapper##_closure(PyObject *a, PyObject *b, PyObject *c) { \ - PyObject *tuple, *resultobj; \ - int result; \ - tuple = PyTuple_New(c ? 2 : 1); \ - assert(tuple); \ - PyTuple_SET_ITEM(tuple, 0, b); \ - Py_XINCREF(b); \ - if (c) { \ - PyTuple_SET_ITEM(tuple, 1, c); \ - Py_XINCREF(c); \ - } \ - resultobj = wrapper(a, tuple); \ - result = resultobj ? 0 : -1; \ - Py_XDECREF(resultobj); \ - Py_DECREF(tuple); \ - return result; \ -} - -#define SWIGPY_REPRFUNC_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a) { \ - return wrapper(a, NULL); \ -} - -#define SWIGPY_HASHFUNC_CLOSURE(wrapper) \ -SWIGINTERN long \ -wrapper##_closure(PyObject *a) { \ - PyObject *pyresult; \ - long result; \ - pyresult = wrapper(a, NULL); \ - if (!pyresult || !PyLong_Check(pyresult)) \ - return -1; \ - result = PyLong_AsLong(pyresult); \ - Py_DECREF(pyresult); \ - return result; \ -} - -#define SWIGPY_ITERNEXT_CLOSURE(wrapper) \ -SWIGINTERN PyObject * \ -wrapper##_closure(PyObject *a) { \ - PyObject *result; \ - result = wrapper(a, NULL); \ - if (result && result == Py_None) { \ - Py_DECREF(result); \ - result = NULL; \ - } \ - return result; \ -} - #ifdef __cplusplus extern "C" { #endif +SWIGINTERN Py_hash_t +SwigPyObject_hash(PyObject *obj) { + SwigPyObject *sobj = (SwigPyObject *)obj; + void *ptr = sobj->ptr; + return (Py_hash_t)ptr; +} + +SWIGINTERN Py_hash_t +SWIG_PyNumber_AsPyHash(PyObject *obj) { + Py_hash_t result = -1; +#if PY_VERSION_HEX < 0x03020000 + if (PyLong_Check(obj)) + result = PyLong_AsLong(obj); +#else + if (PyNumber_Check(obj)) + result = PyNumber_AsSsize_t(obj, NULL); +#endif + else + PyErr_Format(PyExc_TypeError, "Wrong type for hash function"); + return result; +} + SWIGINTERN int SwigPyBuiltin_BadInit(PyObject *self, PyObject *SWIGUNUSEDPARM(args), PyObject *SWIGUNUSEDPARM(kwds)) { PyErr_Format(PyExc_TypeError, "Cannot create new instances of type '%.300s'", self->ob_type->tp_name); @@ -213,11 +31,10 @@ SwigPyBuiltin_BadInit(PyObject *self, PyObject *SWIGUNUSEDPARM(args), PyObject * } SWIGINTERN void -SwigPyBuiltin_BadDealloc(PyObject *pyobj) { - SwigPyObject *sobj; - sobj = (SwigPyObject *)pyobj; +SwigPyBuiltin_BadDealloc(PyObject *obj) { + SwigPyObject *sobj = (SwigPyObject *)obj; if (sobj->own) { - PyErr_Format(PyExc_TypeError, "Swig detected a memory leak in type '%.300s': no callable destructor found.", pyobj->ob_type->tp_name); + PyErr_Format(PyExc_TypeError, "Swig detected a memory leak in type '%.300s': no callable destructor found.", obj->ob_type->tp_name); } } @@ -347,9 +164,13 @@ SwigPyStaticVar_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value) } SWIGINTERN int -SwigPyObjectType_setattro(PyTypeObject *type, PyObject *name, PyObject *value) { +SwigPyObjectType_setattro(PyObject *typeobject, PyObject *name, PyObject *value) { PyObject *attribute; + PyTypeObject *type; descrsetfunc local_set; + + assert(PyType_Check(typeobject)); + type = (PyTypeObject *)typeobject; attribute = _PyType_Lookup(type, name); if (attribute != NULL) { /* Implement descriptor functionality, if any */ @@ -378,16 +199,15 @@ SwigPyStaticVar_Type(void) { static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { - /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(&PyType_Type, 0) #else PyObject_HEAD_INIT(&PyType_Type) - 0, + 0, /* ob_size */ #endif - "swig_static_var_getset_descriptor", - sizeof(PyGetSetDescrObject), - 0, + "swig_static_var_getset_descriptor", /* tp_name */ + sizeof(PyGetSetDescrObject), /* tp_basicsize */ + 0, /* tp_itemsize */ (destructor)SwigPyStaticVar_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ @@ -433,10 +253,19 @@ SwigPyStaticVar_Type(void) { 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 - 0, /* tp_version */ + 0, /* tp_version_tag */ +#endif +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ #endif #ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ +#if PY_VERSION_HEX >= 0x02050000 + 0, /* tp_prev */ +#endif + 0 /* tp_next */ #endif }; staticvar_type = tmp; @@ -451,6 +280,95 @@ SwigPyStaticVar_Type(void) { return &staticvar_type; } +SWIGINTERN PyTypeObject* +SwigPyObjectType(void) { + static char swigpyobjecttype_doc[] = "Metaclass for SWIG wrapped types"; + static PyTypeObject swigpyobjecttype_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(&PyType_Type, 0) +#else + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ +#endif + "SwigPyObjectType", /* tp_name */ + PyType_Type.tp_basicsize, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + SwigPyObjectType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_CLASS, /* tp_flags */ + swigpyobjecttype_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#if PY_VERSION_HEX >= 0x02060000 + 0, /* tp_version_tag */ +#endif +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ +#if PY_VERSION_HEX >= 0x02050000 + 0, /* tp_prev */ +#endif + 0 /* tp_next */ +#endif + }; + swigpyobjecttype_type = tmp; + type_init = 1; + swigpyobjecttype_type.tp_base = &PyType_Type; +#if PY_VERSION_HEX < 0x02020000 + swigpyobjecttype_type.ob_type = &PyType_Type; +#else + if (PyType_Ready(&swigpyobjecttype_type) < 0) + return NULL; +#endif + } + return &swigpyobjecttype_type; +} + SWIGINTERN PyGetSetDescrObject * SwigPyStaticVar_new_getset(PyTypeObject *type, PyGetSetDef *getset) { @@ -509,6 +427,295 @@ SwigPyBuiltin_SetMetaType (PyTypeObject *type, PyTypeObject *metatype) #endif } + +/* Start of callback function macros for use in PyTypeObject */ + +typedef PyObject *(*SwigPyWrapperFunction)(PyObject *, PyObject *); + +#define SWIGPY_UNARYFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_unaryfunc_closure(PyObject *a) { \ + return SwigPyBuiltin_unaryfunc_closure(wrapper, a); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_unaryfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + return wrapper(a, NULL); +} + +#define SWIGPY_DESTRUCTOR_CLOSURE(wrapper) \ +SWIGINTERN void \ +wrapper##_destructor_closure(PyObject *a) { \ + SwigPyBuiltin_destructor_closure(wrapper, #wrapper, a); \ +} +SWIGINTERN void +SwigPyBuiltin_destructor_closure(SwigPyWrapperFunction wrapper, const char *wrappername, PyObject *a) { + SwigPyObject *sobj; + sobj = (SwigPyObject *)a; + Py_XDECREF(sobj->dict); + if (sobj->own) { + PyObject *o; + PyObject *val = 0, *type = 0, *tb = 0; + PyErr_Fetch(&val, &type, &tb); + o = wrapper(a, NULL); + if (!o) { + PyObject *deallocname = PyString_FromString(wrappername); + PyErr_WriteUnraisable(deallocname); + Py_DECREF(deallocname); + } + PyErr_Restore(val, type, tb); + Py_XDECREF(o); + } + if (PyType_IS_GC(a->ob_type)) { + PyObject_GC_Del(a); + } else { + PyObject_Del(a); + } +} + +#define SWIGPY_INQUIRY_CLOSURE(wrapper) \ +SWIGINTERN int \ +wrapper##_inquiry_closure(PyObject *a) { \ + return SwigPyBuiltin_inquiry_closure(wrapper, a); \ +} +SWIGINTERN int +SwigPyBuiltin_inquiry_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + PyObject *pyresult; + int result; + pyresult = wrapper(a, NULL); + result = pyresult && PyObject_IsTrue(pyresult) ? 1 : 0; + Py_XDECREF(pyresult); + return result; +} + +#define SWIGPY_GETITERFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_getiterfunc_closure(PyObject *a) { \ + return SwigPyBuiltin_getiterfunc_closure(wrapper, a); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_getiterfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + return wrapper(a, NULL); +} + +#define SWIGPY_BINARYFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_binaryfunc_closure(PyObject *a, PyObject *b) { \ + return SwigPyBuiltin_binaryfunc_closure(wrapper, a, b); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_binaryfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a, PyObject *b) { + PyObject *tuple, *result; + tuple = PyTuple_New(1); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, b); + Py_XINCREF(b); + result = wrapper(a, tuple); + Py_DECREF(tuple); + return result; +} + +typedef ternaryfunc ternarycallfunc; + +#define SWIGPY_TERNARYFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_ternaryfunc_closure(PyObject *a, PyObject *b, PyObject *c) { \ + return SwigPyBuiltin_ternaryfunc_closure(wrapper, a, b, c); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_ternaryfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a, PyObject *b, PyObject *c) { + PyObject *tuple, *result; + tuple = PyTuple_New(2); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, b); + PyTuple_SET_ITEM(tuple, 1, c); + Py_XINCREF(b); + Py_XINCREF(c); + result = wrapper(a, tuple); + Py_DECREF(tuple); + return result; +} + +#define SWIGPY_TERNARYCALLFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_ternarycallfunc_closure(PyObject *a, PyObject *b, PyObject *c) { \ + return SwigPyBuiltin_ternarycallfunc_closure(wrapper, a, b, c); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_ternarycallfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a, PyObject *b, PyObject *c) { + (void) c; + return wrapper(a, b); +} + +#define SWIGPY_LENFUNC_CLOSURE(wrapper) \ +SWIGINTERN Py_ssize_t \ +wrapper##_lenfunc_closure(PyObject *a) { \ + return SwigPyBuiltin_lenfunc_closure(wrapper, a); \ +} +SWIGINTERN Py_ssize_t +SwigPyBuiltin_lenfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + PyObject *resultobj; + Py_ssize_t result; + resultobj = wrapper(a, NULL); + result = PyNumber_AsSsize_t(resultobj, NULL); + Py_DECREF(resultobj); + return result; +} + +#define SWIGPY_SSIZESSIZEARGFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_ssizessizeargfunc_closure(PyObject *a, Py_ssize_t b, Py_ssize_t c) { \ + return SwigPyBuiltin_ssizessizeargfunc_closure(wrapper, a, b, c); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_ssizessizeargfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a, Py_ssize_t b, Py_ssize_t c) { + PyObject *tuple, *result; + tuple = PyTuple_New(2); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); + PyTuple_SET_ITEM(tuple, 1, _PyLong_FromSsize_t(c)); + result = wrapper(a, tuple); + Py_DECREF(tuple); + return result; +} + +#define SWIGPY_SSIZESSIZEOBJARGPROC_CLOSURE(wrapper) \ +SWIGINTERN int \ +wrapper##_ssizessizeobjargproc_closure(PyObject *a, Py_ssize_t b, Py_ssize_t c, PyObject *d) { \ + return SwigPyBuiltin_ssizessizeobjargproc_closure(wrapper, a, b, c, d); \ +} +SWIGINTERN int +SwigPyBuiltin_ssizessizeobjargproc_closure(SwigPyWrapperFunction wrapper, PyObject *a, Py_ssize_t b, Py_ssize_t c, PyObject *d) { + PyObject *tuple, *resultobj; + int result; + tuple = PyTuple_New(d ? 3 : 2); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); + PyTuple_SET_ITEM(tuple, 1, _PyLong_FromSsize_t(c)); + if (d) { + PyTuple_SET_ITEM(tuple, 2, d); + Py_INCREF(d); + } + resultobj = wrapper(a, tuple); + result = resultobj ? 0 : -1; + Py_DECREF(tuple); + Py_XDECREF(resultobj); + return result; +} + +#define SWIGPY_SSIZEARGFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_ssizeargfunc_closure(PyObject *a, Py_ssize_t b) { \ + return SwigPyBuiltin_funpack_ssizeargfunc_closure(wrapper, a, b); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_funpack_ssizeargfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a, Py_ssize_t b) { + PyObject *tuple, *result; + tuple = PyTuple_New(1); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); + result = wrapper(a, tuple); + Py_DECREF(tuple); + return result; +} + +#define SWIGPY_FUNPACK_SSIZEARGFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_ssizeargfunc_closure(PyObject *a, Py_ssize_t b) { \ + return SwigPyBuiltin_ssizeargfunc_closure(wrapper, a, b); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_ssizeargfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a, Py_ssize_t b) { + PyObject *arg, *result; + arg = _PyLong_FromSsize_t(b); + result = wrapper(a, arg); + Py_DECREF(arg); + return result; +} + +#define SWIGPY_SSIZEOBJARGPROC_CLOSURE(wrapper) \ +SWIGINTERN int \ +wrapper##_ssizeobjargproc_closure(PyObject *a, Py_ssize_t b, PyObject *c) { \ + return SwigPyBuiltin_ssizeobjargproc_closure(wrapper, a, b, c); \ +} +SWIGINTERN int +SwigPyBuiltin_ssizeobjargproc_closure(SwigPyWrapperFunction wrapper, PyObject *a, Py_ssize_t b, PyObject *c) { + PyObject *tuple, *resultobj; + int result; + tuple = PyTuple_New(2); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, _PyLong_FromSsize_t(b)); + PyTuple_SET_ITEM(tuple, 1, c); + Py_XINCREF(c); + resultobj = wrapper(a, tuple); + result = resultobj ? 0 : -1; + Py_XDECREF(resultobj); + Py_DECREF(tuple); + return result; +} + +#define SWIGPY_OBJOBJARGPROC_CLOSURE(wrapper) \ +SWIGINTERN int \ +wrapper##_objobjargproc_closure(PyObject *a, PyObject *b, PyObject *c) { \ + return SwigPyBuiltin_objobjargproc_closure(wrapper, a, b, c); \ +} +SWIGINTERN int +SwigPyBuiltin_objobjargproc_closure(SwigPyWrapperFunction wrapper, PyObject *a, PyObject *b, PyObject *c) { + PyObject *tuple, *resultobj; + int result; + tuple = PyTuple_New(c ? 2 : 1); + assert(tuple); + PyTuple_SET_ITEM(tuple, 0, b); + Py_XINCREF(b); + if (c) { + PyTuple_SET_ITEM(tuple, 1, c); + Py_XINCREF(c); + } + resultobj = wrapper(a, tuple); + result = resultobj ? 0 : -1; + Py_XDECREF(resultobj); + Py_DECREF(tuple); + return result; +} + +#define SWIGPY_REPRFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_reprfunc_closure(PyObject *a) { \ + return SwigPyBuiltin_reprfunc_closure(wrapper, a); \ +} +SWIGINTERN PyObject * +SwigPyBuiltin_reprfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + return wrapper(a, NULL); +} + +#define SWIGPY_HASHFUNC_CLOSURE(wrapper) \ +SWIGINTERN Py_hash_t \ +wrapper##_hashfunc_closure(PyObject *a) { \ + return SwigPyBuiltin_hashfunc_closure(wrapper, a); \ +} +SWIGINTERN Py_hash_t +SwigPyBuiltin_hashfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + PyObject *pyresult; + Py_hash_t result; + pyresult = wrapper(a, NULL); + if (!pyresult) + return -1; + result = SWIG_PyNumber_AsPyHash(pyresult); + Py_DECREF(pyresult); + return result; +} + +#define SWIGPY_ITERNEXTFUNC_CLOSURE(wrapper) \ +SWIGINTERN PyObject * \ +wrapper##_iternextfunc_closure(PyObject *a) { \ + return SwigPyBuiltin_iternextfunc_closure(wrapper, a);\ +} +SWIGINTERN PyObject * +SwigPyBuiltin_iternextfunc_closure(SwigPyWrapperFunction wrapper, PyObject *a) { + return wrapper(a, NULL); +} + +/* End of callback function macros for use in PyTypeObject */ + #ifdef __cplusplus } #endif diff --git a/Lib/python/embed.i b/Lib/python/embed.i index c29e8fd9f..efd048789 100644 --- a/Lib/python/embed.i +++ b/Lib/python/embed.i @@ -1,8 +1,8 @@ // // embed.i // SWIG file embedding the Python interpreter in something else. -// This file is based on Python-1.5. It will not work with -// earlier versions. +// This file is deprecated and no longer actively maintained, but it still +// seems to work with Python 2.7. Status with Python 3 is unknown. // // This file makes it possible to extend Python and all of its // built-in functions without having to hack its setup script. @@ -24,13 +24,8 @@ present in your current Python executable (including any special purpose modules you have enabled such as Tkinter). Thus, you may need to provide additional link libraries when compiling. -This library file only works with Python 1.5. A version -compatible with Python 1.4 is available as embed14.i and -a Python1.3 version is available as embed13.i. As far as -I know, this module is C++ safe. +As far as I know, this module is C++ safe. %} -#else -%echo "embed.i : Using Python 1.5" #endif %wrapper %{ @@ -51,12 +46,12 @@ extern "C" { #endif #include -#undef _PyImport_Inittab +#undef _PyImport_Inittab /* Now define our own version of it. Hopefully someone does not have more than 1000 built-in modules */ -struct _inittab SWIG_Import_Inittab[1000]; +struct _inittab SWIG_Import_Inittab[1000]; static int swig_num_modules = 0; @@ -68,18 +63,18 @@ static void swig_add_module(char *name, void (*initfunc)()) { swig_num_modules++; SWIG_Import_Inittab[swig_num_modules].name = (char *) 0; SWIG_Import_Inittab[swig_num_modules].initfunc = 0; -} +} -/* Function to add all of Python's build in modules to our interpreter */ +/* Function to add all of Python's built-in modules to our interpreter */ static void swig_add_builtin() { int i = 0; while (swig_inittab[i].name) { swig_add_module(swig_inittab[i].name, swig_inittab[i].initfunc); - i++; - } + i++; + } #ifdef SWIGMODINIT - SWIGMODINIT + SWIGMODINIT #endif /* Add SWIG builtin function */ swig_add_module(SWIG_name, SWIG_init); @@ -109,7 +104,3 @@ main(int argc, char **argv) { } %} - - - - diff --git a/Lib/python/embed15.i b/Lib/python/embed15.i deleted file mode 100644 index 3c419b9a3..000000000 --- a/Lib/python/embed15.i +++ /dev/null @@ -1,115 +0,0 @@ -/* ----------------------------------------------------------------------------- - * embed15.i - * - * SWIG file embedding the Python interpreter in something else. - * This file is based on Python-1.5. It will not work with - * earlier versions. - * - * This file makes it possible to extend Python and all of its - * built-in functions without having to hack its setup script. - * ----------------------------------------------------------------------------- */ - -#ifdef AUTODOC -%subsection "embed.i" -%text %{ -This module provides support for building a new version of the -Python executable. This will be necessary on systems that do -not support shared libraries and may be necessary with C++ -extensions. This file contains everything you need to build -a new version of Python from include files and libraries normally -installed with the Python language. - -This module will automatically grab all of the Python modules -present in your current Python executable (including any special -purpose modules you have enabled such as Tkinter). Thus, you -may need to provide additional link libraries when compiling. - -This library file only works with Python 1.5. A version -compatible with Python 1.4 is available as embed14.i and -a Python1.3 version is available as embed13.i. As far as -I know, this module is C++ safe. -%} -#else -%echo "embed.i : Using Python 1.5" -#endif - -%wrapper %{ - -#include - -#ifdef __cplusplus -extern "C" -#endif -void SWIG_init(); /* Forward reference */ - -#define _PyImport_Inittab swig_inittab - -/* Grab Python's inittab[] structure */ - -#ifdef __cplusplus -extern "C" { -#endif -#include - -#undef _PyImport_Inittab - -/* Now define our own version of it. - Hopefully someone does not have more than 1000 built-in modules */ - -struct _inittab SWIG_Import_Inittab[1000]; - -static int swig_num_modules = 0; - -/* Function for adding modules to Python */ - -static void swig_add_module(char *name, void (*initfunc)()) { - SWIG_Import_Inittab[swig_num_modules].name = name; - SWIG_Import_Inittab[swig_num_modules].initfunc = initfunc; - swig_num_modules++; - SWIG_Import_Inittab[swig_num_modules].name = (char *) 0; - SWIG_Import_Inittab[swig_num_modules].initfunc = 0; -} - -/* Function to add all of Python's build in modules to our interpreter */ - -static void swig_add_builtin() { - int i = 0; - while (swig_inittab[i].name) { - swig_add_module(swig_inittab[i].name, swig_inittab[i].initfunc); - i++; - } -#ifdef SWIGMODINIT - SWIGMODINIT -#endif - /* Add SWIG builtin function */ - swig_add_module(SWIG_name, SWIG_init); -} - -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -extern int Py_Main(int, char **); - -#ifdef __cplusplus -} -#endif - -extern struct _inittab *PyImport_Inittab; - -int -main(int argc, char **argv) { - swig_add_builtin(); - PyImport_Inittab = SWIG_Import_Inittab; - return Py_Main(argc,argv); -} - -%} - - - - diff --git a/Lib/python/pycomplex.swg b/Lib/python/pycomplex.swg index 74be5b970..087c50f90 100644 --- a/Lib/python/pycomplex.swg +++ b/Lib/python/pycomplex.swg @@ -4,7 +4,7 @@ the complex Constructor method, and the Real and Imag complex accessor methods. - See the std_complex.i and ccomplex.i for concret examples. + See the std_complex.i and ccomplex.i for concrete examples. */ /* the common from converter */ diff --git a/Lib/python/pycontainer.swg b/Lib/python/pycontainer.swg index 7168862f5..d697ffdac 100644 --- a/Lib/python/pycontainer.swg +++ b/Lib/python/pycontainer.swg @@ -206,7 +206,7 @@ namespace swig { if (step == 0) { throw std::invalid_argument("slice step cannot be zero"); } else if (step > 0) { - // Required range: 0 <= i < size, 0 <= j < size + // Required range: 0 <= i < size, 0 <= j < size, i <= j if (i < 0) { ii = 0; } else if (i < (Difference)size) { @@ -214,13 +214,15 @@ namespace swig { } else if (insert && (i >= (Difference)size)) { ii = (Difference)size; } - if ( j < 0 ) { + if (j < 0) { jj = 0; } else { jj = (j < (Difference)size) ? j : (Difference)size; } + if (jj < ii) + jj = ii; } else { - // Required range: -1 <= i < size-1, -1 <= j < size-1 + // Required range: -1 <= i < size-1, -1 <= j < size-1, i >= j if (i < -1) { ii = -1; } else if (i < (Difference) size) { @@ -233,6 +235,8 @@ namespace swig { } else { jj = (j < (Difference)size ) ? j : (Difference)(size-1); } + if (ii < jj) + ii = jj; } } @@ -252,6 +256,19 @@ namespace swig { return pos; } + template + inline void + erase(Sequence* seq, const typename Sequence::iterator& position) { + seq->erase(position); + } + + template + struct traits_reserve { + static void reserve(Sequence & /*seq*/, typename Sequence::size_type /*n*/) { + // This should be specialized for types that support reserve + } + }; + template inline Sequence* getslice(const Sequence* self, Difference i, Difference j, Py_ssize_t step) { @@ -269,6 +286,7 @@ namespace swig { return new Sequence(sb, se); } else { Sequence *sequence = new Sequence(); + swig::traits_reserve::reserve(*sequence, (jj - ii + step - 1) / step); typename Sequence::const_iterator it = sb; while (it!=se) { sequence->push_back(*it); @@ -279,17 +297,16 @@ namespace swig { } } else { Sequence *sequence = new Sequence(); - if (ii > jj) { - typename Sequence::const_reverse_iterator sb = self->rbegin(); - typename Sequence::const_reverse_iterator se = self->rbegin(); - std::advance(sb,size-ii-1); - std::advance(se,size-jj-1); - typename Sequence::const_reverse_iterator it = sb; - while (it!=se) { - sequence->push_back(*it); - for (Py_ssize_t c=0; c<-step && it!=se; ++c) - it++; - } + swig::traits_reserve::reserve(*sequence, (ii - jj - step - 1) / -step); + typename Sequence::const_reverse_iterator sb = self->rbegin(); + typename Sequence::const_reverse_iterator se = self->rbegin(); + std::advance(sb,size-ii-1); + std::advance(se,size-jj-1); + typename Sequence::const_reverse_iterator it = sb; + while (it!=se) { + sequence->push_back(*it); + for (Py_ssize_t c=0; c<-step && it!=se; ++c) + it++; } return sequence; } @@ -303,12 +320,11 @@ namespace swig { Difference jj = 0; swig::slice_adjust(i, j, step, size, ii, jj, true); if (step > 0) { - if (jj < ii) - jj = ii; if (step == 1) { size_t ssize = jj - ii; if (ssize <= is.size()) { // expanding/staying the same size + swig::traits_reserve::reserve(*self, self->size() - ssize + is.size()); typename Sequence::iterator sb = self->begin(); typename InputSeq::const_iterator isit = is.begin(); std::advance(sb,ii); @@ -342,8 +358,6 @@ namespace swig { } } } else { - if (jj > ii) - jj = ii; size_t replacecount = (ii - jj - step - 1) / -step; if (is.size() != replacecount) { char msg[1024]; @@ -369,37 +383,33 @@ namespace swig { Difference jj = 0; swig::slice_adjust(i, j, step, size, ii, jj, true); if (step > 0) { - if (jj > ii) { - typename Sequence::iterator sb = self->begin(); - std::advance(sb,ii); - if (step == 1) { - typename Sequence::iterator se = self->begin(); - std::advance(se,jj); - self->erase(sb,se); - } else { - typename Sequence::iterator it = sb; - size_t delcount = (jj - ii + step - 1) / step; - while (delcount) { - it = self->erase(it); - for (Py_ssize_t c=0; c<(step-1) && it != self->end(); ++c) - it++; - delcount--; - } - } - } - } else { - if (ii > jj) { - typename Sequence::reverse_iterator sb = self->rbegin(); - std::advance(sb,size-ii-1); - typename Sequence::reverse_iterator it = sb; - size_t delcount = (ii - jj - step - 1) / -step; + typename Sequence::iterator sb = self->begin(); + std::advance(sb,ii); + if (step == 1) { + typename Sequence::iterator se = self->begin(); + std::advance(se,jj); + self->erase(sb,se); + } else { + typename Sequence::iterator it = sb; + size_t delcount = (jj - ii + step - 1) / step; while (delcount) { - it = typename Sequence::reverse_iterator(self->erase((++it).base())); - for (Py_ssize_t c=0; c<(-step-1) && it != self->rend(); ++c) + it = self->erase(it); + for (Py_ssize_t c=0; c<(step-1) && it != self->end(); ++c) it++; delcount--; } } + } else { + typename Sequence::reverse_iterator sb = self->rbegin(); + std::advance(sb,size-ii-1); + typename Sequence::reverse_iterator it = sb; + size_t delcount = (ii - jj - step - 1) / -step; + while (delcount) { + it = typename Sequence::reverse_iterator(self->erase((++it).base())); + for (Py_ssize_t c=0; c<(-step-1) && it != self->rend(); ++c) + it++; + delcount--; + } } } } @@ -415,7 +425,7 @@ namespace swig template struct SwigPySequence_Ref { - SwigPySequence_Ref(PyObject* seq, int index) + SwigPySequence_Ref(PyObject* seq, Py_ssize_t index) : _seq(seq), _index(index) { } @@ -427,7 +437,7 @@ namespace swig return swig::as(item, true); } catch (std::exception& e) { char msg[1024]; - sprintf(msg, "in sequence element %d ", _index); + sprintf(msg, "in sequence element %d ", (int)_index); if (!PyErr_Occurred()) { ::%type_error(swig::type_name()); } @@ -445,7 +455,7 @@ namespace swig private: PyObject* _seq; - int _index; + Py_ssize_t _index; }; template @@ -466,13 +476,13 @@ namespace swig typedef Reference reference; typedef T value_type; typedef T* pointer; - typedef int difference_type; + typedef Py_ssize_t difference_type; SwigPySequence_InputIterator() { } - SwigPySequence_InputIterator(PyObject* seq, int index) + SwigPySequence_InputIterator(PyObject* seq, Py_ssize_t index) : _seq(seq), _index(index) { } @@ -552,6 +562,7 @@ namespace swig difference_type _index; }; + // STL container wrapper around a Python sequence template struct SwigPySequence_Cont { @@ -559,8 +570,8 @@ namespace swig typedef const SwigPySequence_Ref const_reference; typedef T value_type; typedef T* pointer; - typedef int difference_type; - typedef int size_type; + typedef Py_ssize_t difference_type; + typedef size_t size_type; typedef const pointer const_pointer; typedef SwigPySequence_InputIterator iterator; typedef SwigPySequence_InputIterator const_iterator; @@ -621,13 +632,13 @@ namespace swig bool check(bool set_err = true) const { - int s = size(); - for (int i = 0; i < s; ++i) { + Py_ssize_t s = size(); + for (Py_ssize_t i = 0; i < s; ++i) { swig::SwigVar_PyObject item = PySequence_GetItem(_seq, i); if (!swig::check(item)) { if (set_err) { char msg[1024]; - sprintf(msg, "in sequence element %d", i); + sprintf(msg, "in sequence element %d", (int)i); SWIG_Error(SWIG_RuntimeError, msg); } return false; @@ -748,7 +759,6 @@ namespace swig return self->size(); } } - %enddef @@ -756,7 +766,7 @@ namespace swig %define %swig_sequence_methods_common(Sequence...) %swig_sequence_iterator(%arg(Sequence)) %swig_container_methods(%arg(Sequence)) - + %fragment("SwigPySequence_Base"); #if defined(SWIGPYTHON_BUILTIN) @@ -769,14 +779,6 @@ namespace swig #endif // SWIGPYTHON_BUILTIN %extend { - value_type pop() throw (std::out_of_range) { - if (self->size() == 0) - throw std::out_of_range("pop from empty container"); - Sequence::value_type x = self->back(); - self->pop_back(); - return x; - } - /* typemap for slice object support */ %typemap(in) PySliceObject* { if (!PySlice_Check($input)) { @@ -794,7 +796,11 @@ namespace swig return swig::getslice(self, i, j, 1); } - void __setslice__(difference_type i, difference_type j, const Sequence& v = Sequence()) throw (std::out_of_range, std::invalid_argument) { + void __setslice__(difference_type i, difference_type j) throw (std::out_of_range, std::invalid_argument) { + swig::setslice(self, i, j, 1, Sequence()); + } + + void __setslice__(difference_type i, difference_type j, const Sequence& v) throw (std::out_of_range, std::invalid_argument) { swig::setslice(self, i, j, 1, v); } @@ -803,11 +809,10 @@ namespace swig } #endif - void __delitem__(difference_type i) throw (std::out_of_range) { - self->erase(swig::getpos(self,i)); + void __delitem__(difference_type i) throw (std::out_of_range, std::invalid_argument) { + swig::erase(self, swig::getpos(self, i)); } - /* Overloaded methods for Python 3 compatibility * (Also useful in Python 2.x) */ @@ -858,12 +863,11 @@ namespace swig Sequence::difference_type jd = j; swig::delslice(self, id, jd, step); } - - } + } %enddef -%define %swig_sequence_methods(Sequence...) +%define %swig_sequence_methods_non_resizable(Sequence...) %swig_sequence_methods_common(%arg(Sequence)) %extend { const value_type& __getitem__(difference_type i) const throw (std::out_of_range) { @@ -876,19 +880,32 @@ namespace swig #if defined(SWIGPYTHON_BUILTIN) // This will be called through the mp_ass_subscript slot to delete an entry. - void __setitem__(difference_type i) throw (std::out_of_range) { - self->erase(swig::getpos(self,i)); + void __setitem__(difference_type i) throw (std::out_of_range, std::invalid_argument) { + swig::erase(self, swig::getpos(self, i)); } #endif + } +%enddef + +%define %swig_sequence_methods(Sequence...) + %swig_sequence_methods_non_resizable(%arg(Sequence)) + %extend { + value_type pop() throw (std::out_of_range) { + if (self->size() == 0) + throw std::out_of_range("pop from empty container"); + Sequence::value_type x = self->back(); + self->pop_back(); + return x; + } + void append(const value_type& x) { self->push_back(x); } - } - + } %enddef -%define %swig_sequence_methods_val(Sequence...) +%define %swig_sequence_methods_non_resizable_val(Sequence...) %swig_sequence_methods_common(%arg(Sequence)) %extend { value_type __getitem__(difference_type i) throw (std::out_of_range) { @@ -901,16 +918,28 @@ namespace swig #if defined(SWIGPYTHON_BUILTIN) // This will be called through the mp_ass_subscript slot to delete an entry. - void __setitem__(difference_type i) throw (std::out_of_range) { - self->erase(swig::getpos(self,i)); + void __setitem__(difference_type i) throw (std::out_of_range, std::invalid_argument) { + swig::erase(self, swig::getpos(self, i)); } #endif + } +%enddef + +%define %swig_sequence_methods_val(Sequence...) + %swig_sequence_methods_non_resizable_val(%arg(Sequence)) + %extend { + value_type pop() throw (std::out_of_range) { + if (self->size() == 0) + throw std::out_of_range("pop from empty container"); + Sequence::value_type x = self->back(); + self->pop_back(); + return x; + } void append(value_type x) { self->push_back(x); } - } - + } %enddef @@ -943,8 +972,8 @@ namespace swig { static int asptr(PyObject *obj, sequence **seq) { if (obj == Py_None || SWIG_Python_GetSwigThis(obj)) { sequence *p; - if (::SWIG_ConvertPtr(obj,(void**)&p, - swig::type_info(),0) == SWIG_OK) { + swig_type_info *descriptor = swig::type_info(); + if (descriptor && SWIG_IsOK(::SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0))) { if (seq) *seq = p; return SWIG_OLDOBJ; } @@ -983,15 +1012,14 @@ namespace swig { %#ifdef SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS swig_type_info *desc = swig::type_info(); if (desc && desc->clientdata) { - return SWIG_NewPointerObj(new sequence(seq), desc, SWIG_POINTER_OWN); + return SWIG_InternalNewPointerObj(new sequence(seq), desc, SWIG_POINTER_OWN); } %#endif size_type size = seq.size(); if (size <= (size_type)INT_MAX) { - PyObject *obj = PyTuple_New((int)size); - int i = 0; - for (const_iterator it = seq.begin(); - it != seq.end(); ++it, ++i) { + PyObject *obj = PyTuple_New((Py_ssize_t)size); + Py_ssize_t i = 0; + for (const_iterator it = seq.begin(); it != seq.end(); ++it, ++i) { PyTuple_SetItem(obj,i,swig::from(*it)); } return obj; diff --git a/Lib/python/pyhead.swg b/Lib/python/pyhead.swg index cedd017a7..55eb95a6d 100644 --- a/Lib/python/pyhead.swg +++ b/Lib/python/pyhead.swg @@ -97,10 +97,6 @@ PyString_FromFormat(const char *fmt, ...) { } #endif -/* Add PyObject_Del for old Pythons */ -#if PY_VERSION_HEX < 0x01060000 -# define PyObject_Del(op) PyMem_DEL((op)) -#endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif @@ -215,4 +211,5 @@ typedef destructor freefunc; #if PY_VERSION_HEX < 0x03020000 #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) +#define Py_hash_t long #endif diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index e71c72b27..2cc582841 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -145,7 +145,6 @@ swig_varlink_type(void) { static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { - /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else @@ -183,10 +182,19 @@ swig_varlink_type(void) { 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 - 0, /* tp_version */ + 0, /* tp_version_tag */ +#endif +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ #endif #ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ +#if PY_VERSION_HEX >= 0x02050000 + 0, /* tp_prev */ +#endif + 0 /* tp_next */ #endif }; varlink_type = tmp; @@ -366,13 +374,13 @@ SWIG_init(void) { static PyGetSetDef thisown_getset_def = { (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure }; - PyObject *metatype_args; PyTypeObject *builtin_pytype; int builtin_base_count; swig_type_info *builtin_basetype; PyObject *tuple; PyGetSetDescrObject *static_getset; PyTypeObject *metatype; + PyTypeObject *swigpyobject; SwigPyClientData *cd; PyObject *public_interface, *public_symbol; PyObject *this_descr; @@ -387,14 +395,9 @@ SWIG_init(void) { (void)static_getset; (void)self; - /* metatype is used to implement static member variables. */ - metatype_args = Py_BuildValue("(s(O){})", "SwigPyObjectType", &PyType_Type); - assert(metatype_args); - metatype = (PyTypeObject *) PyType_Type.tp_call((PyObject *) &PyType_Type, metatype_args, NULL); + /* Metaclass is used to implement static member variables */ + metatype = SwigPyObjectType(); assert(metatype); - Py_DECREF(metatype_args); - metatype->tp_setattro = (setattrofunc) &SwigPyObjectType_setattro; - assert(PyType_Ready(metatype) >= 0); #endif /* Fix SwigMethods to carry the callback ptrs when needed */ @@ -412,13 +415,15 @@ SWIG_init(void) { SWIG_InitializeModule(0); #ifdef SWIGPYTHON_BUILTIN + swigpyobject = SwigPyObject_TypeOnce(); + SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; if (!cd) { SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; - SwigPyObject_clientdata.pytype = SwigPyObject_TypeOnce(); - } else if (SwigPyObject_TypeOnce()->tp_basicsize != cd->pytype->tp_basicsize) { + SwigPyObject_clientdata.pytype = swigpyobject; + } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 return NULL; diff --git a/Lib/python/pyopers.swg b/Lib/python/pyopers.swg index ecbe7834e..fd2fcc581 100644 --- a/Lib/python/pyopers.swg +++ b/Lib/python/pyopers.swg @@ -18,31 +18,35 @@ where is the name of a field in a PyTypeObject, PyNumberMethods, PyMappingMethods, PySequenceMethods, or PyBufferProcs. For example: - %{ - - static long myHashFunc (PyObject *pyobj) { - MyClass *cobj; - // Convert pyobj to cobj - return (cobj->field1 * (cobj->field2 << 7)); - } - - %} - %feature("python:tp_hash") MyClass "myHashFunc"; + class MyClass { + public: + ... + }; + + %{ + // Note: Py_hash_t was introduced in Python 3.2 + static Py_hash_t myHashFunc(PyObject *pyobj) { + MyClass *cobj; + // Convert pyobj to cobj + return (cobj->field1 * (cobj->field2 << 7)); + } + %} + NOTE: It is the responsibility of the programmer (that's you) to ensure that a statically defined slot function has the correct signature. If, instead, you want to dispatch to an instance method, you can use %feature("python:slot"). For example: + %feature("python:slot", "tp_hash", functype="hashfunc") MyClass::myHashFunc; + class MyClass { public: - long myHashFunc () const; + Py_hash_t myHashFunc () const; ... }; - - %feature("python:slot", "tp_hash", functype="hashfunc") MyClass::myHashFunc; NOTE: Some python slots use a method signature which does not match the signature of SWIG-wrapped methods. For those slots, @@ -58,20 +62,21 @@ operator overloads for comparison (operator==, operator<, etc.), they will be called from the generated rich compare function. If you want to explicitly choose a method to handle a certain comparison - operation, you may use %feature("python:slot") like this: + operation, you may use a different feature, %feature("python:compare") + like this: + + %feature("python:compare", "Py_LT") MyClass::lessThan; class MyClass { public: - bool lessThan (const MyClass& x) const; + bool lessThan(const MyClass& other) const; ... }; - %feature("python:slot", "Py_LT") MyClass::lessThan; - ... where "Py_LT" is one of the rich comparison opcodes defined in the python header file object.h. - If there's no method defined to handle a particular comparsion operation, + If there's no method defined to handle a particular comparison operation, the default behavior is to compare pointer values of the wrapped C++ objects. @@ -103,7 +108,6 @@ %pybinoperator(__neg__, *::operator-(), unaryfunc, nb_negative); %pybinoperator(__neg__, *::operator-() const, unaryfunc, nb_negative); %pybinoperator(__mul__, *::operator*, binaryfunc, nb_multiply); -%pybinoperator(__div__, *::operator/, binaryfunc, nb_div); %pybinoperator(__mod__, *::operator%, binaryfunc, nb_remainder); %pybinoperator(__lshift__, *::operator<<, binaryfunc, nb_lshift); %pybinoperator(__rshift__, *::operator>>, binaryfunc, nb_rshift); @@ -117,8 +121,6 @@ %pycompare(__eq__, *::operator==, Py_EQ); %pycompare(__ne__, *::operator!=, Py_NE); -%feature("python:slot", "nb_truediv", functype="binaryfunc") *::operator/; - /* Special cases */ %rename(__invert__) *::operator~; %feature("python:slot", "nb_invert", functype="unaryfunc") *::operator~; @@ -127,6 +129,7 @@ #if defined(SWIGPYTHON_BUILTIN) %pybinoperator(__nonzero__, *::operator bool, inquiry, nb_nonzero); +%pybinoperator(__truediv__, *::operator/ , binaryfunc, nb_divide); #else %feature("shadow") *::operator bool %{ def __nonzero__(self): @@ -134,6 +137,13 @@ def __nonzero__(self): __bool__ = __nonzero__ %}; %rename(__nonzero__) *::operator bool; +%feature("shadow") *::operator/ %{ +def __truediv__(self, *args): + return $action(self, *args) +__div__ = __truediv__ +%}; +%rename(__truediv__) *::operator/; +%pythonmaybecall *::operator/; #endif /* Ignored operators */ @@ -151,11 +161,11 @@ __bool__ = __nonzero__ They translate the inplace C++ operators (+=, -=, ...) into the corresponding python equivalents(__iadd__,__isub__), etc, - disabling the ownership of the input 'self' pointer, and assigning + disabling the ownership of the input 'this' pointer, and assigning it to the returning object: - %feature("del") *::Operator; - %feature("new") *::Operator; + %feature("del") *::Operator; // disables ownership by generating SWIG_POINTER_DISOWN + %feature("new") *::Operator; // claims ownership by generating SWIG_POINTER_OWN This makes the most common case safe, ie: @@ -174,8 +184,8 @@ __bool__ = __nonzero__ that never get deleted (maybe, not sure, it depends). But if that is the case, you could recover the old behaviour using - %feature("del","") A::operator+=; - %feature("new","") A::operator+=; + %feature("del","0") A::operator+=; + %feature("new","0") A::operator+=; which recovers the old behaviour for the class 'A', or if you are 100% sure your entire system works fine in the old way, use: @@ -183,6 +193,12 @@ __bool__ = __nonzero__ %feature("del","") *::operator+=; %feature("new","") *::operator+=; + The default behaviour assumes that the 'this' pointer's memory is + already owned by the SWIG object; it relinquishes ownership then + takes it back. This may not be the case though as the SWIG object + might be owned by memory managed elsewhere, eg after calling a + function that returns a C++ reference. In such case you will need + to use the features above to recover the old behaviour too. */ #if defined(SWIGPYTHON_BUILTIN) @@ -194,7 +210,6 @@ __bool__ = __nonzero__ %pyinplaceoper(__iadd__ , *::operator +=, binaryfunc, nb_inplace_add); %pyinplaceoper(__isub__ , *::operator -=, binaryfunc, nb_inplace_subtract); %pyinplaceoper(__imul__ , *::operator *=, binaryfunc, nb_inplace_multiply); -%pyinplaceoper(__idiv__ , *::operator /=, binaryfunc, nb_inplace_divide); %pyinplaceoper(__imod__ , *::operator %=, binaryfunc, nb_inplace_remainder); %pyinplaceoper(__iand__ , *::operator &=, binaryfunc, nb_inplace_and); %pyinplaceoper(__ior__ , *::operator |=, binaryfunc, nb_inplace_or); @@ -202,6 +217,19 @@ __bool__ = __nonzero__ %pyinplaceoper(__ilshift__, *::operator <<=, binaryfunc, nb_inplace_lshift); %pyinplaceoper(__irshift__, *::operator >>=, binaryfunc, nb_inplace_rshift); +/* Special cases */ +#if defined(SWIGPYTHON_BUILTIN) +%pyinplaceoper(__itruediv__ , *::operator /=, binaryfunc, nb_inplace_divide); +#else +%delobject *::operator /=; +%newobject *::operator /=; +%feature("shadow") *::operator /= %{ +def __itruediv__(self, *args): + return $action(self, *args) +__idiv__ = __itruediv__ +%}; +%rename(__itruediv__) *::operator /=; +#endif /* Finally, in python we need to mark the binary operations to fail as 'maybecall' methods */ @@ -216,6 +244,7 @@ __bool__ = __nonzero__ %pybinopermaybecall(neg); %pybinopermaybecall(mul); %pybinopermaybecall(div); +%pybinopermaybecall(truediv); %pybinopermaybecall(mod); %pybinopermaybecall(lshift); %pybinopermaybecall(rshift); diff --git a/Lib/python/pyprimtypes.swg b/Lib/python/pyprimtypes.swg index 30bb64f66..6a01af17c 100644 --- a/Lib/python/pyprimtypes.swg +++ b/Lib/python/pyprimtypes.swg @@ -67,7 +67,7 @@ SWIGINTERNINLINE PyObject* /* long */ %fragment(SWIG_From_frag(long),"header") { - %define_as(SWIG_From_dec(long), PyLong_FromLong) + %define_as(SWIG_From_dec(long), PyInt_FromLong) } %fragment(SWIG_AsVal_frag(long),"header", @@ -75,16 +75,20 @@ SWIGINTERNINLINE PyObject* SWIGINTERN int SWIG_AsVal_dec(long)(PyObject *obj, long* val) { +%#if PY_VERSION_HEX < 0x03000000 if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; - } else if (PyLong_Check(obj)) { + } else +%#endif + if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); + return SWIG_OverflowError; } } %#ifdef SWIG_PYTHON_CAST_MODE @@ -119,7 +123,7 @@ SWIGINTERNINLINE PyObject* SWIG_From_dec(unsigned long)(unsigned long value) { return (value > LONG_MAX) ? - PyLong_FromUnsignedLong(value) : PyLong_FromLong(%numeric_cast(value,long)); + PyLong_FromUnsignedLong(value) : PyInt_FromLong(%numeric_cast(value,long)); } } @@ -146,18 +150,7 @@ SWIG_AsVal_dec(unsigned long)(PyObject *obj, unsigned long *val) return SWIG_OK; } else { PyErr_Clear(); -%#if PY_VERSION_HEX >= 0x03000000 - { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (v < 0) { - return SWIG_OverflowError; - } - } else { - PyErr_Clear(); - } - } -%#endif + return SWIG_OverflowError; } } %#ifdef SWIG_PYTHON_CAST_MODE @@ -187,20 +180,22 @@ SWIG_AsVal_dec(unsigned long)(PyObject *obj, unsigned long *val) /* long long */ %fragment(SWIG_From_frag(long long),"header", - fragment=SWIG_From_frag(long), - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE PyObject* SWIG_From_dec(long long)(long long value) { return ((value < LONG_MIN) || (value > LONG_MAX)) ? - PyLong_FromLongLong(value) : PyLong_FromLong(%numeric_cast(value,long)); + PyLong_FromLongLong(value) : PyInt_FromLong(%numeric_cast(value,long)); } +%#endif } %fragment(SWIG_AsVal_frag(long long),"header", fragment=SWIG_AsVal_frag(long), fragment="SWIG_CanCastAsInteger", - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(long long)(PyObject *obj, long long *val) { @@ -212,6 +207,7 @@ SWIG_AsVal_dec(long long)(PyObject *obj, long long *val) return SWIG_OK; } else { PyErr_Clear(); + res = SWIG_OverflowError; } } else { long v; @@ -227,6 +223,8 @@ SWIG_AsVal_dec(long long)(PyObject *obj, long long *val) const double mant_min = -mant_max; double d; res = SWIG_AsVal(double)(obj,&d); + if (SWIG_IsOK(res) && !SWIG_CanCastAsInteger(&d, mant_min, mant_max)) + return SWIG_OverflowError; if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, mant_min, mant_max)) { if (val) *val = (long long)(d); return SWIG_AddCast(res); @@ -236,25 +234,28 @@ SWIG_AsVal_dec(long long)(PyObject *obj, long long *val) %#endif return res; } +%#endif } /* unsigned long long */ %fragment(SWIG_From_frag(unsigned long long),"header", - fragment=SWIG_From_frag(long long), - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE PyObject* SWIG_From_dec(unsigned long long)(unsigned long long value) { return (value > LONG_MAX) ? - PyLong_FromUnsignedLongLong(value) : PyLong_FromLong(%numeric_cast(value,long)); + PyLong_FromUnsignedLongLong(value) : PyInt_FromLong(%numeric_cast(value,long)); } +%#endif } %fragment(SWIG_AsVal_frag(unsigned long long),"header", fragment=SWIG_AsVal_frag(unsigned long), fragment="SWIG_CanCastAsInteger", - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(PyObject *obj, unsigned long long *val) { @@ -266,6 +267,7 @@ SWIG_AsVal_dec(unsigned long long)(PyObject *obj, unsigned long long *val) return SWIG_OK; } else { PyErr_Clear(); + res = SWIG_OverflowError; } } else { unsigned long v; @@ -280,6 +282,8 @@ SWIG_AsVal_dec(unsigned long long)(PyObject *obj, unsigned long long *val) const double mant_max = 1LL << DBL_MANT_DIG; double d; res = SWIG_AsVal(double)(obj,&d); + if (SWIG_IsOK(res) && !SWIG_CanCastAsInteger(&d, 0, mant_max)) + return SWIG_OverflowError; if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, mant_max)) { if (val) *val = (unsigned long long)(d); return SWIG_AddCast(res); @@ -289,6 +293,7 @@ SWIG_AsVal_dec(unsigned long long)(PyObject *obj, unsigned long long *val) %#endif return res; } +%#endif } /* double */ @@ -305,9 +310,11 @@ SWIG_AsVal_dec(double)(PyObject *obj, double *val) if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; +%#if PY_VERSION_HEX < 0x03000000 } else if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); + if (val) *val = (double) PyInt_AsLong(obj); return SWIG_OK; +%#endif } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { diff --git a/Lib/python/pyrun.swg b/Lib/python/pyrun.swg index 5eedca483..ab1237f62 100644 --- a/Lib/python/pyrun.swg +++ b/Lib/python/pyrun.swg @@ -161,7 +161,7 @@ SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { /* Unpack the argument tuple */ -SWIGINTERN int +SWIGINTERN Py_ssize_t SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { @@ -175,7 +175,7 @@ SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssi } if (!PyTuple_Check(args)) { if (min <= 1 && max >= 1) { - int i; + Py_ssize_t i; objs[0] = args; for (i = 1; i < max; ++i) { objs[i] = 0; @@ -195,7 +195,7 @@ SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssi name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { - int i; + Py_ssize_t i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } @@ -536,16 +536,32 @@ SwigPyObject_dealloc(PyObject *v) if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; + + /* PyObject_CallFunction() has the potential to silently drop + the active active exception. In cases of unnamed temporary + variable or where we just finished iterating over a generator + StopIteration will be active right now, and this needs to + remain true upon return from SwigPyObject_dealloc. So save + and restore. */ + + PyObject *val = NULL, *type = NULL, *tb = NULL; + PyErr_Fetch(&val, &type, &tb); + if (data->delargs) { - /* we need to create a temporary object to carry the destroy operation */ - PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); - res = SWIG_Python_CallFunctor(destroy, tmp); - Py_DECREF(tmp); + /* we need to create a temporary object to carry the destroy operation */ + PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); + res = SWIG_Python_CallFunctor(destroy, tmp); + Py_DECREF(tmp); } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); } + if (!res) + PyErr_WriteUnraisable(destroy); + + PyErr_Restore(val, type, tb); + Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) @@ -569,6 +585,7 @@ SwigPyObject_append(PyObject* v, PyObject* next) next = tmp; #endif if (!SwigPyObject_Check(next)) { + PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); return NULL; } sobj->next = next; @@ -724,7 +741,9 @@ SwigPyObject_TypeOnce(void) { (unaryfunc)SwigPyObject_oct, /*nb_oct*/ (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif -#if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ +#if PY_VERSION_HEX >= 0x03050000 /* 3.5 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ +#elif PY_VERSION_HEX >= 0x03000000 /* 3.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ @@ -739,7 +758,6 @@ SwigPyObject_TypeOnce(void) { static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { - /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else @@ -750,7 +768,7 @@ SwigPyObject_TypeOnce(void) { sizeof(SwigPyObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyObject_dealloc, /* tp_dealloc */ - 0, /* tp_print */ + 0, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ #else @@ -758,7 +776,7 @@ SwigPyObject_TypeOnce(void) { #endif (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX >= 0x03000000 - 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ #else (cmpfunc)SwigPyObject_compare, /* tp_compare */ #endif @@ -768,7 +786,7 @@ SwigPyObject_TypeOnce(void) { 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ - 0, /* tp_str */ + 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ @@ -804,10 +822,19 @@ SwigPyObject_TypeOnce(void) { 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 - 0, /* tp_version */ + 0, /* tp_version_tag */ +#endif +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ #endif #ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ +#if PY_VERSION_HEX >= 0x02050000 + 0, /* tp_prev */ +#endif + 0 /* tp_next */ #endif }; swigpyobject_type = tmp; @@ -922,7 +949,6 @@ SwigPyPacked_TypeOnce(void) { static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { - /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX>=0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else @@ -983,10 +1009,19 @@ SwigPyPacked_TypeOnce(void) { 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 - 0, /* tp_version */ + 0, /* tp_version_tag */ +#endif +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ #endif #ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ +#if PY_VERSION_HEX >= 0x02050000 + 0, /* tp_prev */ +#endif + 0 /* tp_next */ #endif }; swigpypacked_type = tmp; @@ -1514,13 +1549,11 @@ PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs module as first arg"); + PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs non-NULL value"); + PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } diff --git a/Lib/python/pystdcommon.swg b/Lib/python/pystdcommon.swg index 2af22e2a4..8372426a0 100644 --- a/Lib/python/pystdcommon.swg +++ b/Lib/python/pystdcommon.swg @@ -46,7 +46,8 @@ namespace swig { struct traits_asptr { static int asptr(PyObject *obj, Type **val) { Type *p; - int res = SWIG_ConvertPtr(obj, (void**)&p, type_info(), 0); + swig_type_info *descriptor = type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = p; } diff --git a/Lib/python/pystrings.swg b/Lib/python/pystrings.swg index 2b14547ad..fd37855eb 100644 --- a/Lib/python/pystrings.swg +++ b/Lib/python/pystrings.swg @@ -6,13 +6,18 @@ SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) { %#if PY_VERSION_HEX>=0x03000000 +%#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) + if (PyBytes_Check(obj)) +%#else if (PyUnicode_Check(obj)) +%#endif %#else if (PyString_Check(obj)) %#endif { char *cstr; Py_ssize_t len; %#if PY_VERSION_HEX>=0x03000000 +%#if !defined(SWIG_PYTHON_STRICT_BYTE_CHAR) if (!alloc && cptr) { /* We can't allow converting without allocation, since the internal representation of string in Python 3 is UCS-2/UCS-4 but we require @@ -21,8 +26,9 @@ SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) return SWIG_RuntimeError; } obj = PyUnicode_AsUTF8String(obj); - PyBytes_AsStringAndSize(obj, &cstr, &len); if(alloc) *alloc = SWIG_NEWOBJ; +%#endif + PyBytes_AsStringAndSize(obj, &cstr, &len); %#else PyString_AsStringAndSize(obj, &cstr, &len); %#endif @@ -42,27 +48,58 @@ SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) %#else if (*alloc == SWIG_NEWOBJ) %#endif - { - *cptr = %new_copy_array(cstr, len + 1, char); - *alloc = SWIG_NEWOBJ; - } - else { + { + *cptr = %new_copy_array(cstr, len + 1, char); + *alloc = SWIG_NEWOBJ; + } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } else { - %#if PY_VERSION_HEX>=0x03000000 - assert(0); /* Should never reach here in Python 3 */ - %#endif +%#if PY_VERSION_HEX>=0x03000000 +%#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) + *cptr = PyBytes_AsString(obj); +%#else + assert(0); /* Should never reach here with Unicode strings in Python 3 */ +%#endif +%#else *cptr = SWIG_Python_str_AsChar(obj); +%#endif } } if (psize) *psize = len + 1; -%#if PY_VERSION_HEX>=0x03000000 +%#if PY_VERSION_HEX>=0x03000000 && !defined(SWIG_PYTHON_STRICT_BYTE_CHAR) Py_XDECREF(obj); %#endif return SWIG_OK; } else { +%#if defined(SWIG_PYTHON_2_UNICODE) +%#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) +%#error "Cannot use both SWIG_PYTHON_2_UNICODE and SWIG_PYTHON_STRICT_BYTE_CHAR at once" +%#endif +%#if PY_VERSION_HEX<0x03000000 + if (PyUnicode_Check(obj)) { + char *cstr; Py_ssize_t len; + if (!alloc && cptr) { + return SWIG_RuntimeError; + } + obj = PyUnicode_AsUTF8String(obj); + if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { + if (cptr) { + if (alloc) *alloc = SWIG_NEWOBJ; + *cptr = %new_copy_array(cstr, len + 1, char); + } + if (psize) *psize = len + 1; + + Py_XDECREF(obj); + return SWIG_OK; + } else { + Py_XDECREF(obj); + } + } +%#endif +%#endif + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; @@ -89,13 +126,17 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); } else { %#if PY_VERSION_HEX >= 0x03000000 -%#if PY_VERSION_HEX >= 0x03010000 - return PyUnicode_DecodeUTF8(carray, %numeric_cast(size,int), "surrogateescape"); +%#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) + return PyBytes_FromStringAndSize(carray, %numeric_cast(size, Py_ssize_t)); %#else - return PyUnicode_FromStringAndSize(carray, %numeric_cast(size,int)); +%#if PY_VERSION_HEX >= 0x03010000 + return PyUnicode_DecodeUTF8(carray, %numeric_cast(size, Py_ssize_t), "surrogateescape"); +%#else + return PyUnicode_FromStringAndSize(carray, %numeric_cast(size, Py_ssize_t)); +%#endif %#endif %#else - return PyString_FromStringAndSize(carray, %numeric_cast(size,int)); + return PyString_FromStringAndSize(carray, %numeric_cast(size, Py_ssize_t)); %#endif } } else { @@ -104,4 +145,3 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) } } - diff --git a/Lib/python/pythonkw.swg b/Lib/python/pythonkw.swg index 2f76a664a..1a4329d20 100644 --- a/Lib/python/pythonkw.swg +++ b/Lib/python/pythonkw.swg @@ -8,10 +8,11 @@ /* Warnings for Python keywords - http://www.fnorb.org/docs/1.2/Fnorb-Guide/node62.html + https://docs.python.org/2/reference/lexical_analysis.html#keywords */ PYTHONKW(and); +PYTHONKW(as); PYTHONKW(assert); PYTHONKW(break); PYTHONKW(class); @@ -39,11 +40,12 @@ PYTHONKW(raise); PYTHONKW(return); PYTHONKW(try); PYTHONKW(while); +PYTHONKW(with); PYTHONKW(yield); /* built-in functions - http://www.zvon.org/other/python/doc21/lib/built-in-funcs.html + https://docs.python.org/2/library/functions.html */ PYTHONBN(abs); diff --git a/Lib/python/pytypemaps.swg b/Lib/python/pytypemaps.swg index 2341980f2..48b0bcdc8 100644 --- a/Lib/python/pytypemaps.swg +++ b/Lib/python/pytypemaps.swg @@ -79,10 +79,12 @@ /* Consttab, needed for callbacks, it should be removed later */ -%typemap(consttab) SWIGTYPE ((*)(ANY)) +%typemap(consttab) SWIGTYPE ((*)(ANY)) { SWIG_PY_POINTER, (char*)"$symname", 0, 0, (void *)($value), &$descriptor } +%typemap(consttab) SWIGTYPE ((* const)(ANY)) = SWIGTYPE ((*)(ANY)); %typemap(constcode) SWIGTYPE ((*)(ANY)) ""; +%typemap(constcode) SWIGTYPE ((* const)(ANY)) = SWIGTYPE ((*)(ANY)); /* Smart Pointers */ diff --git a/Lib/python/pywstrings.swg b/Lib/python/pywstrings.swg index 864376b01..e64618762 100644 --- a/Lib/python/pywstrings.swg +++ b/Lib/python/pywstrings.swg @@ -16,7 +16,7 @@ SWIG_AsWCharPtrAndSize(PyObject *obj, wchar_t **cptr, size_t *psize, int *alloc) { PyObject *tmp = 0; int isunicode = PyUnicode_Check(obj); -%#if PY_VERSION_HEX < 0x03000000 +%#if PY_VERSION_HEX < 0x03000000 && !defined(SWIG_PYTHON_STRICT_UNICODE_WCHAR) if (!isunicode && PyString_Check(obj)) { obj = tmp = PyUnicode_FromObject(obj); isunicode = 1; @@ -58,7 +58,7 @@ SWIG_FromWCharPtrAndSize(const wchar_t * carray, size_t size) return pwchar_descriptor ? SWIG_InternalNewPointerObj(%const_cast(carray,wchar_t *), pwchar_descriptor, 0) : SWIG_Py_Void(); } else { - return PyUnicode_FromWideChar(carray, %numeric_cast(size,int)); + return PyUnicode_FromWideChar(carray, %numeric_cast(size, Py_ssize_t)); } } else { return SWIG_Py_Void(); diff --git a/Lib/python/std_array.i b/Lib/python/std_array.i new file mode 100644 index 000000000..a3de3125b --- /dev/null +++ b/Lib/python/std_array.i @@ -0,0 +1,91 @@ +/* + std::array +*/ + +%fragment("StdArrayTraits","header",fragment="StdSequenceTraits") +%{ + namespace swig { + template + struct traits_asptr > { + static int asptr(PyObject *obj, std::array **vec) { + return traits_asptr_stdseq >::asptr(obj, vec); + } + }; + + template + struct traits_from > { + static PyObject *from(const std::array& vec) { + return traits_from_stdseq >::from(vec); + } + }; + + template + inline void + assign(const SwigPySeq& swigpyseq, std::array* seq) { + if (swigpyseq.size() < seq->size()) + throw std::invalid_argument("std::array cannot be expanded in size"); + else if (swigpyseq.size() > seq->size()) + throw std::invalid_argument("std::array cannot be reduced in size"); + std::copy(swigpyseq.begin(), swigpyseq.end(), seq->begin()); + } + + template + inline void + erase(std::array* SWIGUNUSEDPARM(seq), const typename std::array::iterator& SWIGUNUSEDPARM(position)) { + throw std::invalid_argument("std::array object does not support item deletion"); + } + + // Only limited slicing is supported as std::array is fixed in size + template + inline std::array* + getslice(const std::array* self, Difference i, Difference j, Py_ssize_t step) { + typedef std::array Sequence; + typename Sequence::size_type size = self->size(); + Difference ii = 0; + Difference jj = 0; + swig::slice_adjust(i, j, step, size, ii, jj); + + if (step == 1 && ii == 0 && static_cast(jj) == size) { + Sequence *sequence = new Sequence(); + std::copy(self->begin(), self->end(), sequence->begin()); + return sequence; + } else if (step == -1 && static_cast(ii) == (size - 1) && jj == -1) { + Sequence *sequence = new Sequence(); + std::copy(self->rbegin(), self->rend(), sequence->begin()); + return sequence; + } else { + throw std::invalid_argument("std::array object only supports getting a slice that is the size of the array"); + } + } + + template + inline void + setslice(std::array* self, Difference i, Difference j, Py_ssize_t step, const InputSeq& is = InputSeq()) { + typedef std::array Sequence; + typename Sequence::size_type size = self->size(); + Difference ii = 0; + Difference jj = 0; + swig::slice_adjust(i, j, step, size, ii, jj, true); + + if (step == 1 && ii == 0 && static_cast(jj) == size) { + std::copy(is.begin(), is.end(), self->begin()); + } else if (step == -1 && static_cast(ii) == (size - 1) && jj == -1) { + std::copy(is.rbegin(), is.rend(), self->begin()); + } else { + throw std::invalid_argument("std::array object only supports setting a slice that is the size of the array"); + } + } + + template + inline void + delslice(std::array* SWIGUNUSEDPARM(self), Difference SWIGUNUSEDPARM(i), Difference SWIGUNUSEDPARM(j), Py_ssize_t SWIGUNUSEDPARM(step)) { + throw std::invalid_argument("std::array object does not support item deletion"); + } + } +%} + +#define %swig_array_methods(Type...) %swig_sequence_methods_non_resizable(Type) +#define %swig_array_methods_val(Type...) %swig_sequence_methods_non_resizable_val(Type); + +%include + diff --git a/Lib/python/std_common.i b/Lib/python/std_common.i index 401bbde7f..605766238 100644 --- a/Lib/python/std_common.i +++ b/Lib/python/std_common.i @@ -13,17 +13,17 @@ fragment=SWIG_From_frag(Type), fragment="StdTraits") { namespace swig { - template <> struct traits { + template <> struct traits< Type > { typedef value_category category; static const char* type_name() { return #Type; } - }; - template <> struct traits_asval { + }; + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(PyObject *obj, value_type *val) { + static int asval(PyObject *obj, value_type *val) { return SWIG_AsVal(Type)(obj, val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static PyObject *from(const value_type& val) { return SWIG_From(Type)(val); @@ -46,13 +46,13 @@ namespace swig { fragment=SWIG_From_frag(int), fragment="StdTraits") { namespace swig { - template <> struct traits_asval { + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(PyObject *obj, value_type *val) { + static int asval(PyObject *obj, value_type *val) { return SWIG_AsVal(int)(obj, (int *)val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static PyObject *from(const value_type& val) { return SWIG_From(int)((int)val); diff --git a/Lib/python/std_map.i b/Lib/python/std_map.i index 454e821a5..f61f79c44 100644 --- a/Lib/python/std_map.i +++ b/Lib/python/std_map.i @@ -102,7 +102,8 @@ res = traits_asptr_stdseq >::asptr(items, val); } else { map_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } SWIG_PYTHON_THREAD_END_BLOCK; @@ -119,10 +120,9 @@ static PyObject *asdict(const map_type& map) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; size_type size = map.size(); - int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { - PyErr_SetString(PyExc_OverflowError, - "map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } @@ -211,17 +211,16 @@ PyObject* keys() { Map::size_type size = self->size(); - int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (Map::size_type) INT_MAX) ? (Py_ssize_t) size : -1; SWIG_PYTHON_THREAD_BEGIN_BLOCK; if (pysize < 0) { - PyErr_SetString(PyExc_OverflowError, - "map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } PyObject* keyList = PyList_New(pysize); Map::const_iterator i = self->begin(); - for (int j = 0; j < pysize; ++i, ++j) { + for (Py_ssize_t j = 0; j < pysize; ++i, ++j) { PyList_SET_ITEM(keyList, j, swig::from(i->first)); } SWIG_PYTHON_THREAD_END_BLOCK; @@ -230,17 +229,16 @@ PyObject* values() { Map::size_type size = self->size(); - int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (Map::size_type) INT_MAX) ? (Py_ssize_t) size : -1; SWIG_PYTHON_THREAD_BEGIN_BLOCK; if (pysize < 0) { - PyErr_SetString(PyExc_OverflowError, - "map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } PyObject* valList = PyList_New(pysize); Map::const_iterator i = self->begin(); - for (int j = 0; j < pysize; ++i, ++j) { + for (Py_ssize_t j = 0; j < pysize; ++i, ++j) { PyList_SET_ITEM(valList, j, swig::from(i->second)); } SWIG_PYTHON_THREAD_END_BLOCK; @@ -249,17 +247,16 @@ PyObject* items() { Map::size_type size = self->size(); - int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (Map::size_type) INT_MAX) ? (Py_ssize_t) size : -1; SWIG_PYTHON_THREAD_BEGIN_BLOCK; if (pysize < 0) { - PyErr_SetString(PyExc_OverflowError, - "map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } PyObject* itemList = PyList_New(pysize); Map::const_iterator i = self->begin(); - for (int j = 0; j < pysize; ++i, ++j) { + for (Py_ssize_t j = 0; j < pysize; ++i, ++j) { PyList_SET_ITEM(itemList, j, swig::from(*i)); } SWIG_PYTHON_THREAD_END_BLOCK; diff --git a/Lib/python/std_multimap.i b/Lib/python/std_multimap.i index c81e2ac5d..3209fb0f8 100644 --- a/Lib/python/std_multimap.i +++ b/Lib/python/std_multimap.i @@ -26,7 +26,8 @@ return traits_asptr_stdseq, std::pair >::asptr(items, val); } else { multimap_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; @@ -45,11 +46,10 @@ return SWIG_InternalNewPointerObj(new multimap_type(multimap), desc, SWIG_POINTER_OWN); } else { size_type size = multimap.size(); - int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(PyExc_OverflowError, - "multimap size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "multimap size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } diff --git a/Lib/python/std_pair.i b/Lib/python/std_pair.i index 5694e7e09..da31918c8 100644 --- a/Lib/python/std_pair.i +++ b/Lib/python/std_pair.i @@ -48,7 +48,8 @@ } } else { value_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = *p; } return res; @@ -98,7 +99,8 @@ } } else { value_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; diff --git a/Lib/python/std_unordered_map.i b/Lib/python/std_unordered_map.i index e58a4e927..894840c6c 100644 --- a/Lib/python/std_unordered_map.i +++ b/Lib/python/std_unordered_map.i @@ -15,6 +15,13 @@ } } + template + struct traits_reserve > { + static void reserve(std::unordered_map &seq, typename std::unordered_map::size_type n) { + seq.reserve(n); + } + }; + template struct traits_asptr > { typedef std::unordered_map unordered_map_type; @@ -29,7 +36,8 @@ res = traits_asptr_stdseq, std::pair >::asptr(items, val); } else { unordered_map_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; @@ -48,11 +56,10 @@ return SWIG_NewPointerObj(new unordered_map_type(unordered_map), desc, SWIG_POINTER_OWN); } else { size_type size = unordered_map.size(); - int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(PyExc_OverflowError, - "unordered_map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "unordered_map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } @@ -164,17 +171,16 @@ PyObject* keys() { Map::size_type size = self->size(); - int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (Map::size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(PyExc_OverflowError, - "unordered_map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "unordered_map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } PyObject* keyList = PyList_New(pysize); Map::const_iterator i = self->begin(); - for (int j = 0; j < pysize; ++i, ++j) { + for (Py_ssize_t j = 0; j < pysize; ++i, ++j) { PyList_SET_ITEM(keyList, j, swig::from(i->first)); } return keyList; @@ -182,17 +188,16 @@ PyObject* values() { Map::size_type size = self->size(); - int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (Map::size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(PyExc_OverflowError, - "unordered_map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "unordered_map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } PyObject* valList = PyList_New(pysize); Map::const_iterator i = self->begin(); - for (int j = 0; j < pysize; ++i, ++j) { + for (Py_ssize_t j = 0; j < pysize; ++i, ++j) { PyList_SET_ITEM(valList, j, swig::from(i->second)); } return valList; @@ -200,17 +205,16 @@ PyObject* items() { Map::size_type size = self->size(); - int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (Map::size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(PyExc_OverflowError, - "unordered_map size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "unordered_map size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } PyObject* itemList = PyList_New(pysize); Map::const_iterator i = self->begin(); - for (int j = 0; j < pysize; ++i, ++j) { + for (Py_ssize_t j = 0; j < pysize; ++i, ++j) { PyList_SET_ITEM(itemList, j, swig::from(*i)); } return itemList; diff --git a/Lib/python/std_unordered_multimap.i b/Lib/python/std_unordered_multimap.i index adf86f251..2410aa52b 100644 --- a/Lib/python/std_unordered_multimap.i +++ b/Lib/python/std_unordered_multimap.i @@ -16,6 +16,13 @@ } } + template + struct traits_reserve > { + static void reserve(std::unordered_multimap &seq, typename std::unordered_multimap::size_type n) { + seq.reserve(n); + } + }; + template struct traits_asptr > { typedef std::unordered_multimap unordered_multimap_type; @@ -26,7 +33,8 @@ return traits_asptr_stdseq, std::pair >::asptr(items, val); } else { unordered_multimap_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; @@ -45,11 +53,10 @@ return SWIG_NewPointerObj(new unordered_multimap_type(unordered_multimap), desc, SWIG_POINTER_OWN); } else { size_type size = unordered_multimap.size(); - int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1; + Py_ssize_t pysize = (size <= (size_type) INT_MAX) ? (Py_ssize_t) size : -1; if (pysize < 0) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(PyExc_OverflowError, - "unordered_multimap size not valid in python"); + PyErr_SetString(PyExc_OverflowError, "unordered_multimap size not valid in python"); SWIG_PYTHON_THREAD_END_BLOCK; return NULL; } diff --git a/Lib/python/std_unordered_multiset.i b/Lib/python/std_unordered_multiset.i index d5b9ff61c..0d9f3d9c6 100644 --- a/Lib/python/std_unordered_multiset.i +++ b/Lib/python/std_unordered_multiset.i @@ -18,6 +18,13 @@ } } + template + struct traits_reserve > { + static void reserve(std::unordered_multiset &seq, typename std::unordered_multiset::size_type n) { + seq.reserve(n); + } + }; + template struct traits_asptr > { static int asptr(PyObject *obj, std::unordered_multiset **m) { diff --git a/Lib/python/std_unordered_set.i b/Lib/python/std_unordered_set.i index a021cb4ed..855a28da5 100644 --- a/Lib/python/std_unordered_set.i +++ b/Lib/python/std_unordered_set.i @@ -16,6 +16,13 @@ } } + template + struct traits_reserve > { + static void reserve(std::unordered_set &seq, typename std::unordered_set::size_type n) { + seq.reserve(n); + } + }; + template struct traits_asptr > { static int asptr(PyObject *obj, std::unordered_set **s) { diff --git a/Lib/python/std_vector.i b/Lib/python/std_vector.i index 3f04a30c7..2ac41a54d 100644 --- a/Lib/python/std_vector.i +++ b/Lib/python/std_vector.i @@ -5,6 +5,13 @@ %fragment("StdVectorTraits","header",fragment="StdSequenceTraits") %{ namespace swig { + template + struct traits_reserve > { + static void reserve(std::vector &seq, typename std::vector::size_type n) { + seq.reserve(n); + } + }; + template struct traits_asptr > { static int asptr(PyObject *obj, std::vector **vec) { diff --git a/Lib/r/boost_shared_ptr.i b/Lib/r/boost_shared_ptr.i index 17e9cfe8a..8ef8d2ef2 100644 --- a/Lib/r/boost_shared_ptr.i +++ b/Lib/r/boost_shared_ptr.i @@ -40,7 +40,7 @@ %variable_fail(res, "$type", "$name"); } if (!argp) { - %argument_nullref("$type", $symname, $argnum); + %variable_nullref("$type", "$name"); } else { $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get()); if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); @@ -124,7 +124,9 @@ %variable_fail(res, "$type", "$name"); } SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared; - if (!argp) { %argument_nullref("$type", $symname, $argnum); } + if (!argp) { + %variable_nullref("$type", "$name"); + } if (newmem & SWIG_CAST_NEW_MEMORY) { tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); diff --git a/Lib/r/r.swg b/Lib/r/r.swg index a6014965e..cf1cfc8f9 100644 --- a/Lib/r/r.swg +++ b/Lib/r/r.swg @@ -264,8 +264,8 @@ x setAs('ExternalReference', 'character', function(from) {if (!is.null(from$"__str__")) from$"__str__"()}) -suppressWarnings(setMethod('print', 'ExternalReference', -function(x) {print(as(x, "character"))})) +suppressMessages(suppressWarnings(setMethod('print', 'ExternalReference', +function(x) {print(as(x, "character"))}))) %} diff --git a/Lib/r/rfragments.swg b/Lib/r/rfragments.swg index 2ec8f867f..b89212b05 100644 --- a/Lib/r/rfragments.swg +++ b/Lib/r/rfragments.swg @@ -44,21 +44,27 @@ SWIG_AsVal_dec(long)(SEXP obj, long *val) } -%fragment(SWIG_From_frag(long long),"header") { +%fragment(SWIG_From_frag(long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE SEXP SWIG_From_dec(long long)(long long value) { return Rf_ScalarInteger((int)value); } +%#endif } -%fragment(SWIG_AsVal_frag(long long),"header") { +%fragment(SWIG_AsVal_frag(long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE int SWIG_AsVal_dec(long long)(SEXP obj, long long *val) { if (val) *val = Rf_asInteger(obj); return SWIG_OK; } +%#endif } %fragment(SWIG_From_frag(unsigned long),"header") { @@ -80,22 +86,28 @@ SWIG_AsVal_dec(unsigned long)(SEXP obj, unsigned long *val) } -%fragment(SWIG_From_frag(unsigned long long),"header") { +%fragment(SWIG_From_frag(unsigned long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE SEXP SWIG_From_dec(unsigned long long)(unsigned long long value) { return Rf_ScalarInteger((int)value); } +%#endif } -%fragment(SWIG_AsVal_frag(unsigned long long),"header") { +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE int SWIG_AsVal_dec(unsigned long long)(SEXP obj, unsigned long long *val) { if (val) *val = Rf_asInteger(obj); return SWIG_OK; } +%#endif } %fragment(SWIG_From_frag(double),"header") { diff --git a/Lib/r/rrun.swg b/Lib/r/rrun.swg index 990443e23..81f6461d2 100644 --- a/Lib/r/rrun.swg +++ b/Lib/r/rrun.swg @@ -1,15 +1,4 @@ -#ifdef __cplusplus -#include -extern "C" { -#endif - -/* for raw pointer */ -#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_R_ConvertPtr(obj, pptr, type, flags) -#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_R_ConvertPtr(obj, pptr, type, flags) -#define SWIG_NewPointerObj(ptr, type, flags) SWIG_R_NewPointerObj(ptr, type, flags) - - /* Remove global namespace pollution */ #if !defined(SWIG_NO_R_NO_REMAP) # define R_NO_REMAP @@ -20,6 +9,18 @@ extern "C" { #include #include + +#ifdef __cplusplus +#include +extern "C" { +#endif + +/* for raw pointer */ +#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_R_ConvertPtr(obj, pptr, type, flags) +#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_R_ConvertPtr(obj, pptr, type, flags) +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_R_NewPointerObj(ptr, type, flags) + +#include #include #include @@ -218,10 +219,6 @@ SWIGRUNTIME SEXP SWIG_MakePtr(void *ptr, const char *typeName, R_SWIG_Owner owner) { SEXP external, r_obj; - const char *p = typeName; - - if(typeName[0] == '_') - p = typeName + 1; Rf_protect(external = R_MakeExternalPtr(ptr, Rf_install(typeName), R_NilValue)); Rf_protect(r_obj = NEW_OBJECT(MAKE_CLASS((char *) typeName))); diff --git a/Lib/r/rstdcommon.swg b/Lib/r/rstdcommon.swg index b11cf677b..e6c873a07 100644 --- a/Lib/r/rstdcommon.swg +++ b/Lib/r/rstdcommon.swg @@ -40,7 +40,8 @@ namespace swig { struct traits_asptr { static int asptr(SWIG_Object obj, Type **val) { Type *p; - int res = SWIG_ConvertPtr(obj, (void**)&p, type_info(), 0); + swig_type_info *descriptor = type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = p; } diff --git a/Lib/r/std_common.i b/Lib/r/std_common.i index 8e97521b0..cda262310 100644 --- a/Lib/r/std_common.i +++ b/Lib/r/std_common.i @@ -12,17 +12,17 @@ fragment=SWIG_From_frag(Type), fragment="StdTraits") { namespace swig { - template <> struct traits { + template <> struct traits< Type > { typedef value_category category; static const char* type_name() { return #Type; } - }; - template <> struct traits_asval { + }; + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(SEXP obj, value_type *val) { + static int asval(SEXP obj, value_type *val) { return SWIG_AsVal(Type)(obj, val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static SEXP from(const value_type& val) { return SWIG_From(Type)(val); @@ -45,13 +45,13 @@ namespace swig { fragment=SWIG_From_frag(int), fragment="StdTraits") { namespace swig { - template <> struct traits_asval { + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(SEXP obj, value_type *val) { + static int asval(SEXP obj, value_type *val) { return SWIG_AsVal(int)(obj, (int *)val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static SEXP from(const value_type& val) { return SWIG_From(int)((int)val); diff --git a/Lib/r/std_vector.i b/Lib/r/std_vector.i index 836c95b53..4ec51dc91 100644 --- a/Lib/r/std_vector.i +++ b/Lib/r/std_vector.i @@ -34,10 +34,10 @@ return(result); } }; - // vectors of unsigned int + // vectors of unsigned 8bit int template <> - struct traits_from_ptr > { - static SEXP from (std::vector *val, int owner = 0) { + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { SEXP result; PROTECT(result = Rf_allocVector(INTSXP, val->size())); for (unsigned pos = 0; pos < val->size(); pos++) @@ -48,7 +48,66 @@ return(result); } }; - // vectors of int + // vectors of 8bit int + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; + + // vectors of unsigned 16bit int + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; + // vectors of 16bit int + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; + + // vectors of 32 bit unsigned int + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; + + // vectors of 32bit int template <> struct traits_from_ptr > { static SEXP from (std::vector *val, int owner = 0) { @@ -63,6 +122,64 @@ } }; + // vectors of 64 bit unsigned int +#if defined(SWIGWORDSIZE64) + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; + // vectors of 64 bit int + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; +#else + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; + // vectors of 64 bit int + template <> + struct traits_from_ptr > { + static SEXP from (std::vector *val, int owner = 0) { + SEXP result; + PROTECT(result = Rf_allocVector(INTSXP, val->size())); + for (unsigned pos = 0; pos < val->size(); pos++) + { + INTEGER_POINTER(result)[pos] = ((*val)[pos]); + } + UNPROTECT(1); + return(result); + } + }; +#endif // vectors of bool template <> struct traits_from_ptr > { @@ -75,9 +192,9 @@ } UNPROTECT(1); return(result); - //return SWIG_R_NewPointerObj(val, type_info< std::vector >(), owner); } }; + // vectors of strings template <> struct traits_from_ptr > > { @@ -90,7 +207,6 @@ } UNPROTECT(1); return(result); - //return SWIG_R_NewPointerObj(val, type_info< std::vector >(), owner); } }; @@ -101,7 +217,7 @@ return SWIG_R_NewPointerObj(val, type_info< std::vector< T > >(), owner); } }; - + ///////////////////////////////////////////////// template <> struct traits_asptr < std::vector > { static int asptr(SEXP obj, std::vector **val) { @@ -142,6 +258,98 @@ } }; + // 8 bit integer types + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + unsigned int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + // not sure how to check the size of the SEXP obj is correct + int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + + // 16 bit integer types + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + unsigned int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + // not sure how to check the size of the SEXP obj is correct + int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + // 32 bit integer types template <> struct traits_asptr < std::vector > { static int asptr(SEXP obj, std::vector **val) { @@ -187,6 +395,102 @@ } }; +#if defined(SWIGWORDSIZE64) + // 64 bit integer types + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + unsigned int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + // not sure how to check the size of the SEXP obj is correct + int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + +#else + // 64 bit integer types + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + unsigned int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + + template <> + struct traits_asptr < std::vector > { + static int asptr(SEXP obj, std::vector **val) { + std::vector *p; + // not sure how to check the size of the SEXP obj is correct + int sexpsz = Rf_length(obj); + p = new std::vector(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, INTSXP)); + int *S = INTEGER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + (*p)[pos] = static_cast(S[pos]); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + +#endif + template <> struct traits_asptr < std::vector > { static int asptr(SEXP obj, std::vector **val) { @@ -210,13 +514,37 @@ } }; + template <> + struct traits_asptr < std::vector > > { + static int asptr(SEXP obj, std::vector > **val) { + std::vector > *p; + // R character vectors are STRSXP containing CHARSXP + // access a CHARSXP using STRING_ELT + int sexpsz = Rf_length(obj); + p = new std::vector >(sexpsz); + SEXP coerced; + PROTECT(coerced = Rf_coerceVector(obj, STRSXP)); + //SEXP *S = CHARACTER_POINTER(coerced); + for (unsigned pos = 0; pos < p->size(); pos++) + { + const char * thecstring = CHAR(STRING_ELT(coerced, pos)); + (*p)[pos] = std::basic_string(thecstring); + } + int res = SWIG_OK; + if (SWIG_IsOK(res)) { + if (val) *val = p; + } + UNPROTECT(1); + return res; + } + }; + // catchall for R to vector conversion template struct traits_asptr < std::vector > { static int asptr(SEXP obj, std::vector **val) { std::vector *p; - Rprintf("my asptr\n"); - int res = SWIG_R_ConvertPtr(obj, (void**)&p, type_info< std::vector >(), 0); + int res = SWIG_R_ConvertPtr(obj, (void**)&p, type_info< std::vector >(), 0); if (SWIG_IsOK(res)) { if (val) *val = p; } @@ -228,7 +556,7 @@ // catch all that does everything with vectors template <> struct traits_from_ptr > > { - static SEXP from (std::vector< std::vector > *val, int owner = 0) { + static SEXP from (std::vector< std::vector > *val, int owner = 0) { SEXP result; // allocate the R list PROTECT(result = Rf_allocVector(VECSXP, val->size())); @@ -247,6 +575,7 @@ } }; + template <> struct traits_from_ptr > > { static SEXP from (std::vector< std::vector > *val, int owner = 0) { @@ -338,6 +667,8 @@ } }; + ///////////////////////////////////////////////////////////////// + // R side template <> struct traits_asptr < std::vector< std::vector > > { @@ -507,86 +838,202 @@ %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector) %traits_type_name(std::vector) -%typemap("rtypecheck") std::vector, std::vector const, std::vector const& +%typemap("rtypecheck") std::vector, std::vector *, std::vector & %{ is.numeric($arg) %} %typemap("rtype") std::vector "numeric" -%typemap("scoercein") std::vector, std::vector const, std::vector const& ""; +%typemap("scoercein") std::vector, std::vector *, std::vector & "$input = as.numeric($input);"; %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector) %traits_type_name(std::vector) -%typemap("rtypecheck") std::vector, std::vector const, std::vector const& - %{ is.numeric($arg) %} -%typemap("rtype") std::vector "numeric" -%typemap("scoercein") std::vector, std::vector const, std::vector const& ""; + +// reuse these for float +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); %traits_type_name(std::vector); -%typemap("rtypecheck") std::vector , std::vector const, std::vector const& +%typemap("rtypecheck") std::vector, std::vector *, std::vector & %{ is.logical($arg) %} %typemap("rtype") std::vector "logical" -%typemap("scoercein") std::vector , std::vector const, std::vector const& "$input = as.logical($input);"; +%typemap("scoercein") std::vector , std::vector & "$input = as.logical($input);"; + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); %traits_type_name(std::vector); -%typemap("rtypecheck") std::vector , std::vector const, std::vector const& +%typemap("rtypecheck") std::vector, std::vector *, std::vector & %{ is.integer($arg) || is.numeric($arg) %} + %typemap("rtype") std::vector "integer" -%typemap("scoercein") std::vector , std::vector const, std::vector const& "$input = as.integer($input);"; +%typemap("scoercein") std::vector , std::vector *, std::vector & "$input = as.integer($input);"; + +// strings +%typemap("rtype") std::vector< std::basic_string >, +std::vector< std::basic_string > *, + std::vector< std::basic_string > & "character" + +%typemap("rtypecheck") std::vector< std::basic_string >, +std::vector< std::basic_string > *, + std::vector< std::basic_string > & + %{ is.character($arg) %} + +%typemap("scoercein") std::vector< std::basic_string >, +std::vector< std::basic_string > *, + std::vector< std::basic_string > & "$input = as.character($input);"; + +%typemap("scoerceout") std::vector< std::basic_string >, +std::vector< std::basic_string > *, + std::vector< std::basic_string > & +%{ %} + +%apply std::vector< std::basic_string > { std::vector< std::string> }; + +// all the related integer vectors +// signed +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); + +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); + +#if defined(SWIGWORDSIZE64) +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); +#else +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); +#endif + +// unsigned +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); + +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); %traits_type_name(std::vector); -%typemap("rtypecheck") std::vector, std::vector const, std::vector const& -%{ is.integer($arg) || is.numeric($arg) %} -%typemap("rtype") std::vector "integer" -%typemap("scoercein") std::vector, std::vector const, std::vector const& "$input = as.integer($input);"; -%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector >); -%traits_type_name(std::vector< std::vector >); -%typemap("rtypecheck") std::vector >, std::vector > const, std::vector >const& - %{ is.list($arg) && all(sapply($arg , is.integer) || sapply($arg, is.numeric)) %} -%typemap("rtype") std::vector > "list" -%typemap("scoercein") std::vector< std::vector >, std::vector > const, std::vector >const& "$input = lapply($input, as.integer);"; +#if defined(SWIGWORDSIZE64) +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); +#else +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); +%traits_type_name(std::vector); +#endif + +// These R side typemaps are common for integer types +// but we can't use %apply as it will copy the C side ones too +// Also note that we don't seem to be able to use types like +// int_least8_t here. +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; + +#if defined(SWIGWORDSIZE64) +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +#else +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtype") std::vector, std::vector *, std::vector & = std::vector; +#endif + + +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; + +#if defined(SWIGWORDSIZE64) +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +#else +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +%typemap("scoercein") std::vector, std::vector *, std::vector & = std::vector; +#endif + +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; + +#if defined(SWIGWORDSIZE64) +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +#else +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +%typemap("rtypecheck") std::vector, std::vector *, std::vector & = std::vector; +#endif + +/////////////////////////////////////////////////////////////// %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector >); %traits_type_name(std::vector< std::vector >); -%typemap("rtypecheck") std::vector >, std::vector > const, std::vector >const& +%typemap("rtypecheck") std::vector >, std::vector > *, std::vector > & %{ is.list($arg) && all(sapply($arg , is.integer) || sapply($arg, is.numeric)) %} -%typemap("rtype") std::vector > "list" -%typemap("scoercein") std::vector< std::vector >, std::vector > const, std::vector >const& "$input = lapply($input, as.integer);"; +%typemap("rtype") std::vector >, std::vector > *, std::vector > & "list" +%typemap("scoercein") std::vector< std::vector >, std::vector > *, std::vector > & "$input = lapply($input, as.integer);"; + +%typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector >); +%traits_type_name(std::vector< std::vector >); +%typemap("rtypecheck") std::vector >, std::vector > *, std::vector > & + %{ is.list($arg) && all(sapply($arg , is.integer) || sapply($arg, is.numeric)) %} +%typemap("rtype") std::vector >, std::vector > *, std::vector > & "list" +%typemap("scoercein") std::vector< std::vector >, std::vector > *, std::vector > & "$input = lapply($input, as.integer);"; %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector >); %traits_type_name(std::vector< std::vector >); -%typemap("rtypecheck") std::vector >, std::vector > const, std::vector >const& +%typemap("rtypecheck") std::vector >, std::vector > *, std::vector > & %{ is.list($arg) && all(sapply($arg , is.integer) || sapply($arg, is.numeric)) %} -%typemap("rtype") std::vector > "list" -%typemap("scoercein") std::vector< std::vector >, std::vector > const, std::vector >const& "$input = lapply($input, as.numeric);"; +%typemap("rtype") std::vector >, std::vector > *, std::vector > "list" +%typemap("scoercein") std::vector< std::vector >, std::vector > *, std::vector > & "$input = lapply($input, as.numeric);"; %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector >); %traits_type_name(std::vector< std::vector >); -%typemap("rtypecheck") std::vector >, std::vector > const, std::vector >const& +%typemap("rtypecheck") std::vector >, std::vector > *, std::vector > & %{ is.list($arg) && all(sapply($arg , is.integer) || sapply($arg, is.numeric)) %} -%typemap("rtype") std::vector > "list" -%typemap("scoercein") std::vector< std::vector >, std::vector > const, std::vector >const& +%typemap("rtype") std::vector >, std::vector > *, std::vector > & "list" +%typemap("scoercein") std::vector< std::vector >, std::vector > *, std::vector > & "$input = lapply($input, as.numeric);"; %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector >); %traits_type_name(std::vector< std::vector >); -%typemap("rtypecheck") std::vector >, std::vector > const, std::vector >const& +%typemap("rtypecheck") std::vector >, std::vector > *, std::vector > & %{ is.list($arg) && all(sapply($arg , is.integer) || sapply($arg, is.numeric)) %} -%typemap("rtype") std::vector > "list" -%typemap("scoercein") std::vector< std::vector >, std::vector > const, std::vector >const& "$input = lapply($input, as.logical);"; +%typemap("rtype") std::vector >, std::vector > *, std::vector > & "list" +%typemap("scoercein") std::vector< std::vector >, std::vector > *, std::vector > & "$input = lapply($input, as.logical);"; // we don't want these to be given R classes as they // have already been turned into R vectors. %typemap(scoerceout) std::vector, - std::vector *, - std::vector &, - std::vector, - std::vector *, - std::vector &, + std::vector*, + std::vector&, + std::vector , + std::vector*, + std::vector , + std::vector, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector&, std::vector, - std::vector *, - std::vector &, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector&, // vectors of vectors std::vector< std::vector >, std::vector< std::vector >*, @@ -603,6 +1050,24 @@ std::vector< std::vector >, std::vector< std::vector >*, std::vector< std::vector >& - - %{ %} + +#if defined(SWIGWORDSIZE64) +%typemap(scoerceout) std::vector, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector& + %{ %} +#else + +%typemap(scoerceout) std::vector, + std::vector*, + std::vector&, + std::vector, + std::vector*, + std::vector& + %{ %} + +#endif diff --git a/Lib/ruby/boost_shared_ptr.i b/Lib/ruby/boost_shared_ptr.i new file mode 100644 index 000000000..938074d81 --- /dev/null +++ b/Lib/ruby/boost_shared_ptr.i @@ -0,0 +1,323 @@ +%include + +// Set SHARED_PTR_DISOWN to $disown if required, for example +// #define SHARED_PTR_DISOWN $disown +#if !defined(SHARED_PTR_DISOWN) +#define SHARED_PTR_DISOWN 0 +#endif + +%fragment("SWIG_null_deleter_python", "header", fragment="SWIG_null_deleter") { +%#define SWIG_NO_NULL_DELETER_SWIG_BUILTIN_INIT +} + +// Language specific macro implementing all the customisations for handling the smart pointer +%define SWIG_SHARED_PTR_TYPEMAPS(CONST, TYPE...) + +// %naturalvar is as documented for member variables +%naturalvar TYPE; +%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; + +// destructor wrapper customisation +%feature("unref") TYPE + %{(void)arg1; + delete reinterpret_cast< SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > * >(self);%} + +// Typemap customisations... + +// plain value +%typemap(in) CONST TYPE (void *argp, int res = 0) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (!argp) { + %argument_nullref("$type", $symname, $argnum); + } else { + $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get()); + if (newmem.own & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + } +} +%typemap(out) CONST TYPE { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)); + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +%typemap(varin) CONST TYPE { + void *argp = 0; + swig_ruby_owntype newmem = {0, 0}; + int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %variable_fail(res, "$type", "$name"); + } + if (!argp) { + %variable_nullref("$type", "$name"); + } else { + $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get()); + if (newmem.own & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + } +} +%typemap(varout) CONST TYPE { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)); + %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +// plain pointer +// Note: $disown not implemented by default as it will lead to a memory leak of the shared_ptr instance +%typemap(in) CONST TYPE * (void *argp = 0, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SHARED_PTR_DISOWN | %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + $1 = %const_cast(tempshared.get(), $1_ltype); + } else { + smartarg = %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + $1 = %const_cast((smartarg ? smartarg->get() : 0), $1_ltype); + } +} + +%typemap(out, fragment="SWIG_null_deleter_python") CONST TYPE * { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0; + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), $owner | SWIG_POINTER_OWN)); +} + +%typemap(varin) CONST TYPE * { + void *argp = 0; + swig_ruby_owntype newmem = {0, 0}; + int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %variable_fail(res, "$type", "$name"); + } + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared; + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0; + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + $1 = %const_cast(tempshared.get(), $1_ltype); + } else { + smartarg = %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + $1 = %const_cast((smartarg ? smartarg->get() : 0), $1_ltype); + } +} +%typemap(varout, fragment="SWIG_null_deleter_python") CONST TYPE * { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0; + %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +// plain reference +%typemap(in) CONST TYPE & (void *argp = 0, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (!argp) { %argument_nullref("$type", $symname, $argnum); } + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + $1 = %const_cast(tempshared.get(), $1_ltype); + } else { + $1 = %const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $1_ltype); + } +} +%typemap(out, fragment="SWIG_null_deleter_python") CONST TYPE & { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner); + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +%typemap(varin) CONST TYPE & { + void *argp = 0; + swig_ruby_owntype newmem = {0, 0}; + int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %variable_fail(res, "$type", "$name"); + } + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared; + if (!argp) { + %variable_nullref("$type", "$name"); + } + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + $1 = *%const_cast(tempshared.get(), $1_ltype); + } else { + $1 = *%const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $1_ltype); + } +} +%typemap(varout, fragment="SWIG_null_deleter_python") CONST TYPE & { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(&$1 SWIG_NO_NULL_DELETER_0); + %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +// plain pointer by reference +// Note: $disown not implemented by default as it will lead to a memory leak of the shared_ptr instance +%typemap(in) TYPE *CONST& (void *argp = 0, int res = 0, $*1_ltype temp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SHARED_PTR_DISOWN | %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); + temp = %const_cast(tempshared.get(), $*1_ltype); + } else { + temp = %const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $*1_ltype); + } + $1 = &temp; +} +%typemap(out, fragment="SWIG_null_deleter_python") TYPE *CONST& { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner); + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +%typemap(varin) TYPE *CONST& %{ +#error "varin typemap not implemented" +%} +%typemap(varout) TYPE *CONST& %{ +#error "varout typemap not implemented" +%} + +// shared_ptr by value +%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > (void *argp, int res = 0) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (argp) $1 = *(%reinterpret_cast(argp, $<ype)); + if (newmem.own & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $<ype); +} +%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1) : 0; + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { + swig_ruby_owntype newmem = {0, 0}; + void *argp = 0; + int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %variable_fail(res, "$type", "$name"); + } + $1 = argp ? *(%reinterpret_cast(argp, $<ype)) : SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE >(); + if (newmem.own & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $<ype); +} +%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1) : 0; + %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +// shared_ptr by reference +%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & (void *argp, int res = 0, $*1_ltype tempshared) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + if (argp) tempshared = *%reinterpret_cast(argp, $ltype); + delete %reinterpret_cast(argp, $ltype); + $1 = &tempshared; + } else { + $1 = (argp) ? %reinterpret_cast(argp, $ltype) : &tempshared; + } +} +%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = *$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1) : 0; + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{ +#error "varin typemap not implemented" +%} +%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{ +#error "varout typemap not implemented" +%} + +// shared_ptr by pointer +%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * (void *argp, int res = 0, $*1_ltype tempshared) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (newmem.own & SWIG_CAST_NEW_MEMORY) { + if (argp) tempshared = *%reinterpret_cast(argp, $ltype); + delete %reinterpret_cast(argp, $ltype); + $1 = &tempshared; + } else { + $1 = (argp) ? %reinterpret_cast(argp, $ltype) : &tempshared; + } +} +%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 && *$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1) : 0; + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); + if ($owner) delete $1; +} + +%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{ +#error "varin typemap not implemented" +%} +%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{ +#error "varout typemap not implemented" +%} + +// shared_ptr by pointer reference +%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& (void *argp, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared, $*1_ltype temp = 0) { + swig_ruby_owntype newmem = {0, 0}; + res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem); + if (!SWIG_IsOK(res)) { + %argument_fail(res, "$type", $symname, $argnum); + } + if (argp) tempshared = *%reinterpret_cast(argp, $*ltype); + if (newmem.own & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $*ltype); + temp = &tempshared; + $1 = &temp; +} +%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& { + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = *$1 && **$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(**$1) : 0; + %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN)); +} + +%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& %{ +#error "varin typemap not implemented" +%} +%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& %{ +#error "varout typemap not implemented" +%} + +// Typecheck typemaps +// Note: SWIG_ConvertPtr with void ** parameter set to 0 instead of using SWIG_ConvertPtrAndOwn, so that the casting +// function is not called thereby avoiding a possible smart pointer copy constructor call when casting up the inheritance chain. +%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) + TYPE CONST, + TYPE CONST &, + TYPE CONST *, + TYPE *CONST&, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *, + SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& { + int res = SWIG_ConvertPtr($input, 0, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), 0); + $1 = SWIG_CheckState(res); +} + + +// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug +%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ +#error "typemaps for $1_type not available" +%} +%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{ +#error "typemaps for $1_type not available" +%} + + +%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >; + + +%enddef diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index 395dccc17..c6c53a343 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -29,8 +29,9 @@ namespace Swig { virtual ~GCItem() { } - virtual ruby_owntype get_own() const { - return 0; + virtual swig_ruby_owntype get_own() const { + swig_ruby_owntype own = {0, 0}; + return own; } }; @@ -72,18 +73,18 @@ namespace Swig { }; struct GCItem_Object : GCItem { - GCItem_Object(ruby_owntype own) : _own(own) { + GCItem_Object(swig_ruby_owntype own) : _own(own) { } virtual ~GCItem_Object() { } - ruby_owntype get_own() const { + swig_ruby_owntype get_own() const { return _own; } private: - ruby_owntype _own; + swig_ruby_owntype _own; }; template @@ -323,20 +324,20 @@ namespace Swig { } } - void swig_acquire_ownership_obj(void *vptr, ruby_owntype own) const { - if (vptr && own) { + void swig_acquire_ownership_obj(void *vptr, swig_ruby_owntype own) const { + if (vptr && own.datafree) { SWIG_GUARD(swig_mutex_own); swig_owner[vptr] = new GCItem_Object(own); } } - ruby_owntype swig_release_ownership(void *vptr) const { - ruby_owntype own = 0; + swig_ruby_owntype swig_release_ownership(void *vptr) const { + swig_ruby_owntype own = {0, 0}; if (vptr) { SWIG_GUARD(swig_mutex_own); swig_ownership_map::iterator iter = swig_owner.find(vptr); if (iter != swig_owner.end()) { - own = iter->second->get_own(); + own.datafree = iter->second->get_own().datafree; swig_owner.erase(iter); } } diff --git a/Lib/ruby/rubycontainer.swg b/Lib/ruby/rubycontainer.swg index 69db367d9..a6d8a59ef 100644 --- a/Lib/ruby/rubycontainer.swg +++ b/Lib/ruby/rubycontainer.swg @@ -91,11 +91,17 @@ namespace swig { return pos; } + template + inline void + resize(Sequence *seq, typename Sequence::size_type n, typename Sequence::value_type x) { + seq->resize(n, x); + } + template inline Sequence* getslice(const Sequence* self, Difference i, Difference j) { typename Sequence::size_type size = self->size(); - typename Sequence::size_type ii = swig::check_index(i, size); + typename Sequence::size_type ii = swig::check_index(i, size, (i == size && j == size)); typename Sequence::size_type jj = swig::slice_index(j, size); if (jj > ii) { @@ -164,7 +170,6 @@ namespace swig * of an element of a Ruby Array of stuff. * It can be used by RubySequence_InputIterator to make it work with STL * algorithms. - * */ template struct RubySequence_Ref @@ -210,7 +215,6 @@ namespace swig * RubySequence_Ref. * It can be used by RubySequence_InputIterator to make it work with STL * algorithms. - * */ template struct RubySequence_ArrowProxy @@ -225,7 +229,6 @@ namespace swig /** * Input Iterator. This adapator class is a random access iterator that * allows you to use STL algorithms with a Ruby class (a Ruby Array by default). - * */ template > struct RubySequence_InputIterator @@ -326,7 +329,6 @@ namespace swig /** * This adaptor class allows you to use a Ruby Array as if it was an STL * container, giving it begin(), end(), and iterators. - * */ template struct RubySequence_Cont @@ -419,7 +421,6 @@ namespace swig /** * Macros used to typemap an STL iterator -> SWIGIterator conversion. - * */ %define %swig_sequence_iterator(Sequence...) #if defined(SWIG_EXPORT_ITERATOR_METHODS) @@ -463,8 +464,7 @@ namespace swig %typemap(in,noblock=1,fragment="RubySequence_Cont") const_iterator(swig::ConstIterator *iter = 0, int res), const_reverse_iterator(swig::ConstIterator *iter = 0, int res) { - res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), - swig::ConstIterator::descriptor(), 0); + res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::ConstIterator::descriptor(), 0); if (!SWIG_IsOK(res) || !iter) { %argument_fail(SWIG_TypeError, "$type", $symname, $argnum); } else { @@ -496,16 +496,14 @@ namespace swig %typecheck(%checkcode(ITERATOR),noblock=1,fragment="RubySequence_Cont") const_iterator, const_reverse_iterator { swig::ConstIterator *iter = 0; - int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), - swig::ConstIterator::descriptor(), 0); + int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::ConstIterator::descriptor(), 0); $1 = (SWIG_IsOK(res) && iter && (dynamic_cast *>(iter) != 0)); } %typecheck(%checkcode(ITERATOR),noblock=1,fragment="RubySequence_Cont") iterator, reverse_iterator { swig::ConstIterator *iter = 0; - int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), - swig::Iterator::descriptor(), 0); + int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::Iterator::descriptor(), 0); $1 = (SWIG_IsOK(res) && iter && (dynamic_cast *>(iter) != 0)); } @@ -549,7 +547,6 @@ namespace swig /** * Macro used to define common Ruby printing methods for STL container - * */ %define %swig_sequence_printing_methods(Sequence...) @@ -609,9 +606,8 @@ namespace swig /** * Macro used to add common methods to all STL sequence-type containers - * */ -%define %swig_sequence_methods_common(Sequence...) +%define %swig_sequence_methods_non_resizable_common(Sequence...) %swig_container_methods(%arg(Sequence)) %swig_sequence_iterator(%arg(Sequence)) %swig_sequence_printing_methods(%arg(Sequence)) @@ -620,24 +616,28 @@ namespace swig %extend { - - VALUE slice( difference_type i, difference_type j ) - { - if ( j <= 0 ) return Qnil; - std::size_t len = $self->size(); - if ( i < 0 ) i = len - i; - j += i; - if ( static_cast(j) >= len ) j = len-1; - - VALUE r = Qnil; - try { - r = swig::from< const Sequence* >( swig::getslice(self, i, j) ); - } - catch( std::out_of_range ) - { - } - return r; + VALUE slice( difference_type i, difference_type length ) throw (std::invalid_argument) { + if ( length < 0 ) + return Qnil; + std::size_t len = $self->size(); + if ( i < 0 ) { + if ( i + static_cast(len) < 0 ) + return Qnil; + else + i = len + i; } + Sequence::difference_type j = length + i; + if ( j > static_cast(len) ) + j = len; + + VALUE r = Qnil; + try { + r = swig::from< const Sequence* >( swig::getslice(self, i, j) ); + } + catch( std::out_of_range ) { + } + return r; + } Sequence* each() @@ -657,12 +657,23 @@ namespace swig return self; } + VALUE __delete2__(const value_type& i) { + VALUE r = Qnil; + return r; + } + + } +%enddef + +%define %swig_sequence_methods_resizable_common(Sequence...) + %extend { + %newobject select; Sequence* select() { if ( !rb_block_given_p() ) rb_raise( rb_eArgError, "no block given" ); - Sequence* r = new Sequence; + Sequence* r = new Sequence(); Sequence::const_iterator i = $self->begin(); Sequence::const_iterator e = $self->end(); for ( ; i != e; ++i ) @@ -687,21 +698,17 @@ namespace swig } return r; } - - - VALUE __delete2__(const value_type& i) { - VALUE r = Qnil; - return r; - } - } %enddef +%define %swig_sequence_methods_common(Sequence...) + %swig_sequence_methods_non_resizable_common(%arg(Sequence)) + %swig_sequence_methods_resizable_common(%arg(Sequence)) +%enddef /** * Macro used to add functions for back insertion of values in - * STL Sequence containers - * + * STL sequence containers */ %define %swig_sequence_back_inserters( Sequence... ) %extend { @@ -724,7 +731,7 @@ namespace swig if ( !rb_block_given_p() ) rb_raise( rb_eArgError, "no block given" ); - Sequence* r = new Sequence; + Sequence* r = new Sequence(); std::remove_copy_if( $self->begin(), $self->end(), std::back_inserter(*r), swig::yield< Sequence::value_type >() ); @@ -748,15 +755,7 @@ namespace swig } %enddef -/** - * Macro used to add functions for Sequences - * - */ -%define %swig_sequence_methods(Sequence...) - %swig_sequence_methods_common(%arg(Sequence)); - %swig_sequence_methods_extra(%arg(Sequence)); - %swig_sequence_back_inserters(%arg(Sequence)); - +%define %swig_sequence_methods_non_resizable_accessors(Sequence...) %extend { VALUE at(difference_type i) const { @@ -764,25 +763,31 @@ namespace swig try { r = swig::from< Sequence::value_type >( *(swig::cgetpos(self, i)) ); } - catch( std::out_of_range ) - { - } + catch( std::out_of_range ) { + } return r; } - VALUE __getitem__(difference_type i, difference_type j) const { - if ( j <= 0 ) return Qnil; + VALUE __getitem__(difference_type i, difference_type length) const throw (std::invalid_argument) { + if ( length < 0 ) + return Qnil; std::size_t len = $self->size(); - if ( i < 0 ) i = len - i; - j += i; if ( static_cast(j) >= len ) j = len-1; + if ( i < 0 ) { + if ( i + static_cast(len) < 0 ) + return Qnil; + else + i = len + i; + } + Sequence::difference_type j = length + i; + if ( j > static_cast(len) ) + j = len; VALUE r = Qnil; try { r = swig::from< const Sequence* >( swig::getslice(self, i, j) ); } - catch( std::out_of_range ) - { - } + catch( std::out_of_range ) { + } return r; } @@ -791,17 +796,15 @@ namespace swig try { r = swig::from< Sequence::value_type >( *(swig::cgetpos(self, i)) ); } - catch( std::out_of_range ) - { - } + catch( std::out_of_range ) { + } return r; } - VALUE __getitem__(VALUE i) const { - if ( rb_obj_is_kind_of( i, rb_cRange ) == Qfalse ) - { - rb_raise( rb_eTypeError, "not a valid index or range" ); - } + VALUE __getitem__(VALUE i) const throw (std::invalid_argument) { + if ( rb_obj_is_kind_of( i, rb_cRange ) == Qfalse ) { + rb_raise( rb_eTypeError, "not a valid index or range" ); + } static ID id_end = rb_intern("end"); static ID id_start = rb_intern("begin"); @@ -814,53 +817,81 @@ namespace swig int len = $self->size(); int s = NUM2INT( start ); - if ( s < 0 ) s = len + s; - else if ( s >= len ) return Qnil; + if ( s < 0 ) { + s = len + s; + if ( s < 0 ) + return Qnil; + } else if ( s > len ) + return Qnil; int e = NUM2INT( end ); if ( e < 0 ) e = len + e; - - if ( e < s ) return Qnil; //std::swap( s, e ); - if ( noend ) e -= 1; + if ( e < 0 ) e = -1; if ( e >= len ) e = len - 1; + if ( s == len ) e = len - 1; return swig::from< Sequence* >( swig::getslice(self, s, e+1) ); } - VALUE __setitem__(difference_type i, const value_type& x) + VALUE __setitem__(difference_type i, const value_type& x) throw (std::invalid_argument, std::out_of_range) { - std::size_t len = $self->size(); - if ( i < 0 ) i = len - i; - else if ( static_cast(i) >= len ) - $self->resize( i+1, x ); - else - *(swig::getpos(self,i)) = x; + if ( i >= static_cast( $self->size()) ) + swig::resize( $self, i+1, x ); + else + *(swig::getpos($self, i)) = x; return swig::from< Sequence::value_type >( x ); } - VALUE __setitem__(difference_type i, difference_type j, const Sequence& v) - throw (std::invalid_argument) { + VALUE __setitem__(difference_type i, difference_type length, const Sequence& v) throw (std::invalid_argument) { - if ( j <= 0 ) return Qnil; + if ( length < 0 ) + return Qnil; std::size_t len = $self->size(); - if ( i < 0 ) i = len - i; - j += i; - if ( static_cast(j) >= len ) { - $self->resize( j+1, *(v.begin()) ); - j = len-1; + if ( i < 0 ) { + if ( i + static_cast(len) < 0 ) + return Qnil; + else + i = len + i; + } + Sequence::difference_type j = length + i; + if ( j > static_cast(len) ) { + swig::resize( $self, j, *(v.begin()) ); } VALUE r = Qnil; - swig::setslice(self, i, j, v); + swig::setslice($self, i, j, v); r = swig::from< const Sequence* >( &v ); return r; } - } %enddef +/** + * Macro used to add functions for non resizable sequences + */ +%define %swig_sequence_methods_non_resizable(Sequence...) + %swig_sequence_methods_non_resizable_common(%arg(Sequence)) + %swig_sequence_methods_non_resizable_accessors(%arg(Sequence)) +%enddef + + +/** + * Macro used to add functions for sequences + */ +%define %swig_sequence_methods(Sequence...) + %swig_sequence_methods_non_resizable_common(%arg(Sequence)) + %swig_sequence_methods_resizable_common(%arg(Sequence)) + %swig_sequence_methods_non_resizable_accessors(%arg(Sequence)) + %swig_sequence_methods_extra(%arg(Sequence)); + %swig_sequence_back_inserters(%arg(Sequence)); +%enddef + +%define %swig_sequence_methods_non_resizable_val(Sequence...) + %swig_sequence_methods_non_resizable(%arg(Sequence)) +%enddef + %define %swig_sequence_methods_val(Sequence...) %swig_sequence_methods(%arg(Sequence)) %enddef @@ -869,10 +900,8 @@ namespace swig /** * Macro used to add functions for front insertion of * elements in STL sequence containers that support it. - * */ %define %swig_sequence_front_inserters( Sequence... ) - %extend { VALUE shift() @@ -952,7 +981,6 @@ namespace swig return $self; } - } %enddef @@ -1006,8 +1034,8 @@ namespace swig { } } else { sequence *p; - if (SWIG_ConvertPtr(obj,(void**)&p, - swig::type_info(),0) == SWIG_OK) { + swig_type_info *descriptor = swig::type_info(); + if (descriptor && SWIG_IsOK(SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0))) { if (seq) *seq = p; return SWIG_OLDOBJ; } @@ -1046,8 +1074,8 @@ namespace swig { } } else { sequence *p; - if (SWIG_ConvertPtr(obj,(void**)&p, - swig::type_info(),0) == SWIG_OK) { + swig_type_info *descriptor = swig::type_info(); + if (descriptor && SWIG_IsOK(SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0))) { if (seq) *seq = p; return SWIG_OLDOBJ; } diff --git a/Lib/ruby/rubyprimtypes.swg b/Lib/ruby/rubyprimtypes.swg index aa4f7ad37..3a848191c 100644 --- a/Lib/ruby/rubyprimtypes.swg +++ b/Lib/ruby/rubyprimtypes.swg @@ -124,15 +124,20 @@ SWIG_AsVal_dec(unsigned long)(VALUE obj, unsigned long *val) %fragment(SWIG_From_frag(long long),"header", fragment=SWIG_From_frag(long), - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE VALUE SWIG_From_dec(long long)(long long value) { return LL2NUM(value); } +%#endif } -%fragment(SWIG_AsVal_frag(long long),"header",fragment="SWIG_ruby_failed") { +%fragment(SWIG_AsVal_frag(long long),"header", + fragment="SWIG_ruby_failed", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE %ruby_aux_method(long long, NUM2LL, type == T_FIXNUM ? NUM2LL(obj) : rb_big2ll(obj)) SWIGINTERN int @@ -151,21 +156,26 @@ SWIG_AsVal_dec(long long)(VALUE obj, long long *val) } return SWIG_TypeError; } +%#endif } /* unsigned long long */ %fragment(SWIG_From_frag(unsigned long long),"header", - fragment=SWIG_From_frag(long long), - fragment="") { + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE VALUE SWIG_From_dec(unsigned long long)(unsigned long long value) { return ULL2NUM(value); } +%#endif } -%fragment(SWIG_AsVal_frag(unsigned long long),"header",fragment="SWIG_ruby_failed") { +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment="SWIG_ruby_failed", + fragment="SWIG_LongLongAvailable") { +%#ifdef SWIG_LONG_LONG_AVAILABLE %ruby_aux_method(long long, NUM2ULL, type == T_FIXNUM ? NUM2ULL(obj) : rb_big2ull(obj)) SWIGINTERN int @@ -184,6 +194,7 @@ SWIG_AsVal_dec(unsigned long long)(VALUE obj, unsigned long long *val) } return SWIG_TypeError; } +%#endif } /* double */ diff --git a/Lib/ruby/rubyrun.swg b/Lib/ruby/rubyrun.swg index c3e0b749b..249494ab0 100644 --- a/Lib/ruby/rubyrun.swg +++ b/Lib/ruby/rubyrun.swg @@ -14,7 +14,7 @@ #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, own) #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Ruby_NewPointerObj(ptr, type, flags) #define SWIG_AcquirePtr(ptr, own) SWIG_Ruby_AcquirePtr(ptr, own) -#define swig_owntype ruby_owntype +#define swig_owntype swig_ruby_owntype /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty, flags) @@ -238,22 +238,24 @@ SWIG_Ruby_MangleStr(VALUE obj) } /* Acquire a pointer value */ -typedef void (*ruby_owntype)(void*); +typedef struct { + void (*datafree)(void *); + int own; +} swig_ruby_owntype; -SWIGRUNTIME ruby_owntype -SWIG_Ruby_AcquirePtr(VALUE obj, ruby_owntype own) { +SWIGRUNTIME swig_ruby_owntype +SWIG_Ruby_AcquirePtr(VALUE obj, swig_ruby_owntype own) { + swig_ruby_owntype oldown = {0, 0}; if (obj) { - ruby_owntype oldown = RDATA(obj)->dfree; - RDATA(obj)->dfree = own; - return oldown; - } else { - return 0; + oldown.datafree = RDATA(obj)->dfree; + RDATA(obj)->dfree = own.datafree; } + return oldown; } /* Convert a pointer value */ SWIGRUNTIME int -SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, ruby_owntype *own) +SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, swig_ruby_owntype *own) { char *c; swig_cast_info *tc; @@ -261,7 +263,8 @@ SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, /* Grab the pointer */ if (NIL_P(obj)) { - *ptr = 0; + if (ptr) + *ptr = 0; return SWIG_OK; } else { if (TYPE(obj) != T_DATA) { @@ -270,7 +273,10 @@ SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, Data_Get_Struct(obj, void, vptr); } - if (own) *own = RDATA(obj)->dfree; + if (own) { + own->datafree = RDATA(obj)->dfree; + own->own = 0; + } /* Check to see if the input object is giving up ownership of the underlying C struct or C++ object. If so then we @@ -305,8 +311,6 @@ SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, /* The object has already been deleted */ return SWIG_ObjectPreviouslyDeletedError; } - *ptr = vptr; - return SWIG_OK; } } if ((c = SWIG_MangleStr(obj)) == NULL) { @@ -316,12 +320,23 @@ SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, if (!tc) { return SWIG_ERROR; } else { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc, vptr, &newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ + if (ptr) { + if (tc->type == ty) { + *ptr = vptr; + } else { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, vptr, &newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + own->own = own->own | SWIG_CAST_NEW_MEMORY; + } + } + } } } else { - *ptr = vptr; + if (ptr) + *ptr = vptr; } return SWIG_OK; diff --git a/Lib/ruby/rubystdcommon.swg b/Lib/ruby/rubystdcommon.swg index b4ae3a3cc..f72745b56 100644 --- a/Lib/ruby/rubystdcommon.swg +++ b/Lib/ruby/rubystdcommon.swg @@ -53,7 +53,8 @@ namespace swig { struct traits_asptr { static int asptr(VALUE obj, Type **val) { Type *p; - int res = SWIG_ConvertPtr(obj, (void**)&p, type_info(), 0); + swig_type_info *descriptor = type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = p; } diff --git a/Lib/ruby/rubytracking.swg b/Lib/ruby/rubytracking.swg index 0a36f4a05..8f9f01be8 100644 --- a/Lib/ruby/rubytracking.swg +++ b/Lib/ruby/rubytracking.swg @@ -11,6 +11,11 @@ extern "C" { #endif +#if !defined(ST_DATA_T_DEFINED) +/* Needs to be explicitly included for Ruby 1.8 and earlier */ +#include +#endif + /* Ruby 1.8 actually assumes the first case. */ #if SIZEOF_VOIDP == SIZEOF_LONG # define SWIG2NUM(v) LONG2NUM((unsigned long)v) @@ -22,19 +27,19 @@ extern "C" { # error sizeof(void*) is not the same as long or long long #endif - -/* Global Ruby hash table to store Trackings from C/C++ +/* Global hash table to store Trackings from C/C++ structs to Ruby Objects. */ -static VALUE swig_ruby_trackings = Qnil; +static st_table* swig_ruby_trackings = NULL; -/* Global variable that stores a reference to the ruby - hash table delete function. */ -static ID swig_ruby_hash_delete; +static VALUE swig_ruby_trackings_count(ANYARGS) { + return SWIG2NUM(swig_ruby_trackings->num_entries); +} -/* Setup a Ruby hash table to store Trackings */ + +/* Setup a hash table to store Trackings */ SWIGRUNTIME void SWIG_RubyInitializeTrackings(void) { - /* Create a ruby hash table to store Trackings from C++ + /* Create a hash table to store Trackings from C++ objects to Ruby objects. */ /* Try to see if some other .so has already created a @@ -43,88 +48,46 @@ SWIGRUNTIME void SWIG_RubyInitializeTrackings(void) { This is done to allow multiple DSOs to share the same tracking table. */ - ID trackings_id = rb_intern( "@__trackings__" ); + VALUE trackings_value = Qnil; + /* change the variable name so that we can mix modules + compiled with older SWIG's - this used to be called "@__trackings__" */ + ID trackings_id = rb_intern( "@__safetrackings__" ); VALUE verbose = rb_gv_get("VERBOSE"); rb_gv_set("VERBOSE", Qfalse); - swig_ruby_trackings = rb_ivar_get( _mSWIG, trackings_id ); + trackings_value = rb_ivar_get( _mSWIG, trackings_id ); rb_gv_set("VERBOSE", verbose); - /* No, it hasn't. Create one ourselves */ - if ( swig_ruby_trackings == Qnil ) - { - swig_ruby_trackings = rb_hash_new(); - rb_ivar_set( _mSWIG, trackings_id, swig_ruby_trackings ); - } + /* The trick here is that we have to store the hash table + pointer in a Ruby variable. We do not want Ruby's GC to + treat this pointer as a Ruby object, so we convert it to + a Ruby numeric value. */ + if (trackings_value == Qnil) { + /* No, it hasn't. Create one ourselves */ + swig_ruby_trackings = st_init_numtable(); + rb_ivar_set( _mSWIG, trackings_id, SWIG2NUM(swig_ruby_trackings) ); + } else { + swig_ruby_trackings = (st_table*)NUM2SWIG(trackings_value); + } - /* Now store a reference to the hash table delete function - so that we only have to look it up once.*/ - swig_ruby_hash_delete = rb_intern("delete"); -} - -/* Get a Ruby number to reference a pointer */ -SWIGRUNTIME VALUE SWIG_RubyPtrToReference(void* ptr) { - /* We cast the pointer to an unsigned long - and then store a reference to it using - a Ruby number object. */ - - /* Convert the pointer to a Ruby number */ - return SWIG2NUM(ptr); -} - -/* Get a Ruby number to reference an object */ -SWIGRUNTIME VALUE SWIG_RubyObjectToReference(VALUE object) { - /* We cast the object to an unsigned long - and then store a reference to it using - a Ruby number object. */ - - /* Convert the Object to a Ruby number */ - return SWIG2NUM(object); -} - -/* Get a Ruby object from a previously stored reference */ -SWIGRUNTIME VALUE SWIG_RubyReferenceToObject(VALUE reference) { - /* The provided Ruby number object is a reference - to the Ruby object we want.*/ - - /* Convert the Ruby number to a Ruby object */ - return NUM2SWIG(reference); + rb_define_virtual_variable("SWIG_TRACKINGS_COUNT", swig_ruby_trackings_count, NULL); } /* Add a Tracking from a C/C++ struct to a Ruby object */ SWIGRUNTIME void SWIG_RubyAddTracking(void* ptr, VALUE object) { - /* In a Ruby hash table we store the pointer and - the associated Ruby object. The trick here is - that we cannot store the Ruby object directly - if - we do then it cannot be garbage collected. So - instead we typecast it as a unsigned long and - convert it to a Ruby number object.*/ - - /* Get a reference to the pointer as a Ruby number */ - VALUE key = SWIG_RubyPtrToReference(ptr); - - /* Get a reference to the Ruby object as a Ruby number */ - VALUE value = SWIG_RubyObjectToReference(object); - /* Store the mapping to the global hash table. */ - rb_hash_aset(swig_ruby_trackings, key, value); + st_insert(swig_ruby_trackings, (st_data_t)ptr, object); } /* Get the Ruby object that owns the specified C/C++ struct */ SWIGRUNTIME VALUE SWIG_RubyInstanceFor(void* ptr) { - /* Get a reference to the pointer as a Ruby number */ - VALUE key = SWIG_RubyPtrToReference(ptr); - /* Now lookup the value stored in the global hash table */ - VALUE value = rb_hash_aref(swig_ruby_trackings, key); - - if (value == Qnil) { - /* No object exists - return nil. */ + VALUE value; + + if (st_lookup(swig_ruby_trackings, (st_data_t)ptr, &value)) { + return value; + } else { return Qnil; } - else { - /* Convert this value to Ruby object */ - return SWIG_RubyReferenceToObject(value); - } } /* Remove a Tracking from a C/C++ struct to a Ruby object. It @@ -132,12 +95,8 @@ SWIGRUNTIME VALUE SWIG_RubyInstanceFor(void* ptr) { since the same memory address may be reused later to create a new object. */ SWIGRUNTIME void SWIG_RubyRemoveTracking(void* ptr) { - /* Get a reference to the pointer as a Ruby number */ - VALUE key = SWIG_RubyPtrToReference(ptr); - - /* Delete the object from the hash table by calling Ruby's - do this we need to call the Hash.delete method.*/ - rb_funcall(swig_ruby_trackings, swig_ruby_hash_delete, 1, key); + /* Delete the object from the hash table */ + st_delete(swig_ruby_trackings, (st_data_t *)&ptr, NULL); } /* This is a helper method that unlinks a Ruby object from its @@ -147,10 +106,25 @@ SWIGRUNTIME void SWIG_RubyUnlinkObjects(void* ptr) { VALUE object = SWIG_RubyInstanceFor(ptr); if (object != Qnil) { + if (TYPE(object) != T_DATA) + abort(); DATA_PTR(object) = 0; } } +/* This is a helper method that iterates over all the trackings + passing the C++ object pointer and its related Ruby object + to the passed callback function. */ + +/* Proxy method to abstract the internal trackings datatype */ +static int swig_ruby_internal_iterate_callback(void* ptr, VALUE obj, void(*meth)(void* ptr, VALUE obj)) { + (*meth)(ptr, obj); + return ST_CONTINUE; +} + +SWIGRUNTIME void SWIG_RubyIterateTrackings( void(*meth)(void* ptr, VALUE obj) ) { + st_foreach(swig_ruby_trackings, (int (*)(ANYARGS))&swig_ruby_internal_iterate_callback, (st_data_t)meth); +} #ifdef __cplusplus } diff --git a/Lib/ruby/std_array.i b/Lib/ruby/std_array.i new file mode 100644 index 000000000..a4d3ef54b --- /dev/null +++ b/Lib/ruby/std_array.i @@ -0,0 +1,102 @@ +/* + std::array +*/ + +%fragment("StdArrayTraits","header",fragment="StdSequenceTraits") +%{ + namespace swig { + template + struct traits_asptr > { + static int asptr(VALUE obj, std::array **vec) { + return traits_asptr_stdseq >::asptr(obj, vec); + } + }; + + template + struct traits_from > { + static VALUE from(const std::array& vec) { + return traits_from_stdseq >::from(vec); + } + }; + + template + inline void + assign(const RubySeq& rubyseq, std::array* seq) { + if (rubyseq.size() < seq->size()) + throw std::invalid_argument("std::array cannot be expanded in size"); + else if (rubyseq.size() > seq->size()) + throw std::invalid_argument("std::array cannot be reduced in size"); + std::copy(rubyseq.begin(), rubyseq.end(), seq->begin()); + } + + template + inline void + resize(std::array *seq, typename std::array::size_type n, typename std::array::value_type x) { + throw std::invalid_argument("std::array is a fixed size container and does not support resizing"); + } + + // Only limited slicing is supported as std::array is fixed in size + template + inline std::array* + getslice(const std::array* self, Difference i, Difference j) { + typedef std::array Sequence; + typename Sequence::size_type size = self->size(); + typename Sequence::size_type ii = swig::check_index(i, size, (i == size && j == size)); + typename Sequence::size_type jj = swig::slice_index(j, size); + + if (ii == 0 && jj == size) { + Sequence *sequence = new Sequence(); + std::copy(self->begin(), self->end(), sequence->begin()); + return sequence; + } else { + throw std::invalid_argument("std::array object only supports getting a slice that is the size of the array"); + } + } + + template + inline void + setslice(std::array* self, Difference i, Difference j, const InputSeq& v) { + typedef std::array Sequence; + typename Sequence::size_type size = self->size(); + typename Sequence::size_type ii = swig::check_index(i, size, true); + typename Sequence::size_type jj = swig::slice_index(j, size); + + if (ii == 0 && jj == size) { + std::copy(v.begin(), v.end(), self->begin()); + } else { + throw std::invalid_argument("std::array object only supports setting a slice that is the size of the array"); + } + } + + template + inline void + delslice(std::array* self, Difference i, Difference j) { + throw std::invalid_argument("std::array object does not support item deletion"); + } + } +%} + + +%define %swig_array_methods(Type...) + %swig_sequence_methods_non_resizable(Type) +%enddef + +%define %swig_array_methods_val(Type...) + %swig_sequence_methods_non_resizable_val(Type); +%enddef + + +%mixin std::array "Enumerable"; +%ignore std::array::push_back; +%ignore std::array::pop_back; + + +%rename("delete") std::array::__delete__; +%rename("reject!") std::array::reject_bang; +%rename("map!") std::array::map_bang; +%rename("empty?") std::array::empty; +%rename("include?" ) std::array::__contains__ const; +%rename("has_key?" ) std::array::has_key const; + +%include + diff --git a/Lib/ruby/std_common.i b/Lib/ruby/std_common.i index 14fba0df3..0cf9ce109 100644 --- a/Lib/ruby/std_common.i +++ b/Lib/ruby/std_common.i @@ -14,17 +14,17 @@ fragment=SWIG_From_frag(Type), fragment="StdTraits") { namespace swig { - template <> struct traits { + template <> struct traits< Type > { typedef value_category category; static const char* type_name() { return #Type; } - }; - template <> struct traits_asval { + }; + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(VALUE obj, value_type *val) { + static int asval(VALUE obj, value_type *val) { return SWIG_AsVal(Type)(obj, val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static VALUE from(const value_type& val) { return SWIG_From(Type)(val); @@ -47,13 +47,13 @@ namespace swig { fragment=SWIG_From_frag(int), fragment="StdTraits") { namespace swig { - template <> struct traits_asval { + template <> struct traits_asval< Type > { typedef Type value_type; - static int asval(VALUE obj, value_type *val) { + static int asval(VALUE obj, value_type *val) { return SWIG_AsVal(int)(obj, (int *)val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static VALUE from(const value_type& val) { return SWIG_From(int)((int)val); diff --git a/Lib/ruby/std_map.i b/Lib/ruby/std_map.i index f706ca873..7077fa104 100644 --- a/Lib/ruby/std_map.i +++ b/Lib/ruby/std_map.i @@ -100,7 +100,8 @@ res = traits_asptr_stdseq, std::pair >::asptr(items, val); } else { map_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; diff --git a/Lib/ruby/std_pair.i b/Lib/ruby/std_pair.i index 5b4c8baf2..5bea67c7c 100644 --- a/Lib/ruby/std_pair.i +++ b/Lib/ruby/std_pair.i @@ -44,8 +44,8 @@ } } else { value_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p, - swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = *p; } return res; @@ -90,8 +90,8 @@ } } else { value_type *p; - res = SWIG_ConvertPtr(obj,(void**)&p, - swig::type_info(),0); + swig_type_info *descriptor = swig::type_info(); + res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res) && val) *val = p; } return res; diff --git a/Lib/ruby/std_shared_ptr.i b/Lib/ruby/std_shared_ptr.i new file mode 100644 index 000000000..df873679c --- /dev/null +++ b/Lib/ruby/std_shared_ptr.i @@ -0,0 +1,2 @@ +#define SWIG_SHARED_PTR_NAMESPACE std +%include diff --git a/Lib/scilab/boost_shared_ptr.i b/Lib/scilab/boost_shared_ptr.i index 095b7fe43..b90422a66 100644 --- a/Lib/scilab/boost_shared_ptr.i +++ b/Lib/scilab/boost_shared_ptr.i @@ -47,7 +47,7 @@ %variable_fail(res, "$type", "$name"); } if (!argp) { - %argument_nullref("$type", $symname, $argnum); + %variable_nullref("$type", "$name"); } else { $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get()); if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); @@ -133,7 +133,9 @@ %variable_fail(res, "$type", "$name"); } SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared; - if (!argp) { %argument_nullref("$type", $symname, $argnum); } + if (!argp) { + %variable_nullref("$type", "$name"); + } if (newmem & SWIG_CAST_NEW_MEMORY) { tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *); diff --git a/Lib/scilab/scibool.swg b/Lib/scilab/scibool.swg index ea7938dc8..9aed88eca 100644 --- a/Lib/scilab/scibool.swg +++ b/Lib/scilab/scibool.swg @@ -125,7 +125,6 @@ SWIG_SciBoolean_AsIntArrayAndSize(void *pvApiCtx, int iVar, int *iRows, int *iCo } if (isBooleanType(pvApiCtx, piAddrVar)) { - int i; sciErr = getMatrixOfBoolean(pvApiCtx, piAddrVar, iRows, iCols, piValue); if (sciErr.iErr) { printError(&sciErr, 0); diff --git a/Lib/scilab/scicontainer.swg b/Lib/scilab/scicontainer.swg index 529d27888..2cc44b8e5 100644 --- a/Lib/scilab/scicontainer.swg +++ b/Lib/scilab/scicontainer.swg @@ -60,14 +60,7 @@ namespace swig operator T () const { - try - { - return traits_asval_sequenceitem::asval(_seq, piSeqAddr, _index); - } - catch (std::exception& e) - { - SWIG_exception(SWIG_RuntimeError, e.what()); - } + return traits_asval_sequenceitem::asval(_seq, piSeqAddr, _index); } SciSequence_Ref& operator=(const T& v) @@ -391,14 +384,19 @@ namespace swig { } else { - return true; + return SWIG_ERROR; } } catch (std::exception& e) { SWIG_exception(SWIG_RuntimeError, e.what()); + return SWIG_ERROR; } } + else + { + return SWIG_ERROR; + } } }; @@ -438,6 +436,7 @@ namespace swig { catch (std::exception& e) { SWIG_exception(SWIG_RuntimeError, e.what()); + return SWIG_ERROR; } } }; diff --git a/Lib/scilab/scimatrixbool.swg b/Lib/scilab/scimatrixbool.swg index 3b1f8cb77..a43886b4f 100644 --- a/Lib/scilab/scimatrixbool.swg +++ b/Lib/scilab/scimatrixbool.swg @@ -27,24 +27,24 @@ %typemap(in, noblock=1, fragment="SWIG_SciBoolean_AsBoolArrayAndSize") (bool *IN, int IN_SIZE) (int rowCount, int colCount) { - if (SWIG_SciBoolean_AsBoolArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$1, fname) == SWIG_OK) { - $2 = rowCount * colCount; - } - else { - return SWIG_ERROR; - } + if (SWIG_SciBoolean_AsBoolArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$1, fname) == SWIG_OK) { + $2 = rowCount * colCount; + } + else { + return SWIG_ERROR; + } } // in (int IN_SIZE, bool *IN) %typemap(in, noblock=1) (int IN_SIZE, bool *IN) (int rowCount, int colCount) { - if (SWIG_SciBoolean_AsBoolArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$2, fname) == SWIG_OK) { - $1 = rowCount * colCount; - } - else { - return SWIG_ERROR; - } + if (SWIG_SciBoolean_AsBoolArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$2, fname) == SWIG_OK) { + $1 = rowCount * colCount; + } + else { + return SWIG_ERROR; + } } // out (bool **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT) diff --git a/Lib/scilab/scimatrixdouble.swg b/Lib/scilab/scimatrixdouble.swg index b8272e9a6..9444a8078 100644 --- a/Lib/scilab/scimatrixdouble.swg +++ b/Lib/scilab/scimatrixdouble.swg @@ -27,24 +27,24 @@ %typemap(in, noblock=1, fragment="SWIG_SciDouble_AsDoubleArrayAndSize") (double *IN, int IN_SIZE) (int rowCount, int colCount) { - if (SWIG_SciDouble_AsDoubleArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$1, fname) == SWIG_OK) { - $2 = rowCount * colCount; - } - else { - return SWIG_ERROR; - } + if (SWIG_SciDouble_AsDoubleArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$1, fname) == SWIG_OK) { + $2 = rowCount * colCount; + } + else { + return SWIG_ERROR; + } } // in (int IN_SIZE, double *IN) %typemap(in, noblock=1, fragment="SWIG_SciDouble_AsDoubleArrayAndSize") (int IN_SIZE, double *IN) (int rowCount, int colCount) { - if (SWIG_SciDouble_AsDoubleArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$2, fname) == SWIG_OK) { - $1 = rowCount * colCount; - } - else { - return SWIG_ERROR; - } + if (SWIG_SciDouble_AsDoubleArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$2, fname) == SWIG_OK) { + $1 = rowCount * colCount; + } + else { + return SWIG_ERROR; + } } // out (double **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT) diff --git a/Lib/scilab/scimatrixint.swg b/Lib/scilab/scimatrixint.swg index b7270d5d5..e304d4f64 100644 --- a/Lib/scilab/scimatrixint.swg +++ b/Lib/scilab/scimatrixint.swg @@ -29,12 +29,12 @@ %typemap(in, noblock=1, fragment="SWIG_SciDoubleOrInt32_AsIntArrayAndSize") (int *IN, int IN_SIZE) (int rowCount, int colCount) { - if (SWIG_SciDoubleOrInt32_AsIntArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$1, fname) == SWIG_OK) { - $2 = rowCount * colCount; - } - else { - return SWIG_ERROR; - } + if (SWIG_SciDoubleOrInt32_AsIntArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$1, fname) == SWIG_OK) { + $2 = rowCount * colCount; + } + else { + return SWIG_ERROR; + } } @@ -42,12 +42,12 @@ %typemap(in, noblock=1, fragment="SWIG_SciDoubleOrInt32_AsIntArrayAndSize") (int IN_SIZE, int *IN) (int rowCount, int colCount) { - if (SWIG_SciDoubleOrInt32_AsIntArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$2, fname) == SWIG_OK) { - $1 = rowCount * colCount; - } - else { - return SWIG_ERROR; - } + if (SWIG_SciDoubleOrInt32_AsIntArrayAndSize(pvApiCtx, $input, &rowCount, &colCount, &$2, fname) == SWIG_OK) { + $1 = rowCount * colCount; + } + else { + return SWIG_ERROR; + } } // out (int **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT) diff --git a/Lib/scilab/scipointer.swg b/Lib/scilab/scipointer.swg index 8d0526d4d..94ca4ef37 100644 --- a/Lib/scilab/scipointer.swg +++ b/Lib/scilab/scipointer.swg @@ -6,7 +6,7 @@ } %fragment("SWIG_NewPointerObj", "header") { -#define SWIG_NewPointerObj(pointer, pointerDescriptor, flags) SwigScilabPtrFromObject(pvApiCtx, SWIG_Scilab_GetOutputPosition(), pointer, pointerDescriptor, flags) +#define SWIG_NewPointerObj(pointer, pointerDescriptor, flags) SwigScilabPtrFromObject(pvApiCtx, SWIG_Scilab_GetOutputPosition(), pointer, pointerDescriptor, flags, NULL) } /* @@ -17,7 +17,7 @@ } %fragment("SWIG_NewFunctionPtrObj", "header") { -#define SWIG_NewFunctionPtrObj(pointer, pointerDescriptor) SwigScilabPtrFromObject(pvApiCtx, SWIG_Scilab_GetOutputPosition(), pointer, pointerDescriptor, 0) +#define SWIG_NewFunctionPtrObj(pointer, pointerDescriptor) SwigScilabPtrFromObject(pvApiCtx, SWIG_Scilab_GetOutputPosition(), pointer, pointerDescriptor, 0, NULL) } // No fragment used here, the functions "SwigScilabPtrToObject" and "SwigScilabPtrFromObject" are defined in sciruntime.swg diff --git a/Lib/scilab/scirun.swg b/Lib/scilab/scirun.swg index 71641e074..ad3a7fa1f 100644 --- a/Lib/scilab/scirun.swg +++ b/Lib/scilab/scirun.swg @@ -17,7 +17,9 @@ extern "C" { #define __USE_DEPRECATED_STACK_FUNCTIONS__ #include "stack-c.h" #endif +#if SWIG_SCILAB_VERSION < 600 #include "MALLOC.h" +#endif #include "Scierror.h" #include "localization.h" #include "freeArrayOfString.h" @@ -98,14 +100,88 @@ SWIG_Scilab_SetOutput(void *pvApiCtx, SwigSciObject output) { return SWIG_OK; } +/* Error functions */ + +#define SCILAB_API_ARGUMENT_ERROR 999 + +SWIGINTERN const char* +SWIG_Scilab_ErrorType(int code) { + switch(code) { + case SWIG_MemoryError: + return "MemoryError"; + case SWIG_IOError: + return "IOError"; + case SWIG_RuntimeError: + return "RuntimeError"; + case SWIG_IndexError: + return "IndexError"; + case SWIG_TypeError: + return "TypeError"; + case SWIG_DivisionByZero: + return "ZeroDivisionError"; + case SWIG_OverflowError: + return "OverflowError"; + case SWIG_SyntaxError: + return "SyntaxError"; + case SWIG_ValueError: + return "ValueError"; + case SWIG_SystemError: + return "SystemError"; + case SWIG_AttributeError: + return "AttributeError"; + default: + return "RuntimeError"; + } +} +#define SWIG_ErrorType(code) SWIG_Scilab_ErrorType(code) + +#ifndef SWIG_SCILAB_ERROR +#define SWIG_SCILAB_ERROR 20000 +#endif + +SWIGINTERN void +SWIG_Scilab_Error(int code, const char *msg) { + Scierror(SWIG_SCILAB_ERROR - code, _("SWIG/Scilab: %s: %s\n"), SWIG_Scilab_ErrorType(code), msg); +} + +#define SWIG_Error(code, msg) SWIG_Scilab_Error(code, msg) + +#define SWIG_fail return SWIG_ERROR; + +SWIGRUNTIME void +SWIG_Scilab_Raise_Ex(const char *obj, const char *type, swig_type_info *descriptor) { + if (type) { + if (obj) + Scierror(SWIG_SCILAB_ERROR, "SWIG/Scilab: Exception (%s) occured: %s\n", type, obj); + else + Scierror(SWIG_SCILAB_ERROR, "SWIG/Scilab: Exception (%s) occured.\n", type); + } +} + +SWIGRUNTIME void +SWIG_Scilab_Raise(const int obj, const char *type, swig_type_info *descriptor) { + Scierror(SWIG_SCILAB_ERROR, "SWIG/Scilab: Exception (%s) occured.\n", type); +} + +/* Module initialization */ + +static int swig_module_initialized = 0; + +SWIGRUNTIME int +SWIG_Module_Initialized() { + return swig_module_initialized; +} /* Pointer conversion functions */ +SWIGRUNTIME swig_type_info * +SWIG_Scilab_TypeQuery(const char *name); + SWIGINTERN int -SwigScilabPtrToObject(void *pvApiCtx, int iVar, void **pObjValue, swig_type_info *descriptor, int flags, char *fname) { +SwigScilabCheckPtr(void *pvApiCtx, int iVar, swig_type_info *descriptor, char *fname) { SciErr sciErr; - int iType = 0; int *piAddrVar = NULL; + int iType = 0; sciErr = getVarAddressFromPosition(pvApiCtx, iVar, &piAddrVar); if (sciErr.iErr) { @@ -119,8 +195,99 @@ SwigScilabPtrToObject(void *pvApiCtx, int iVar, void **pObjValue, swig_type_info return SWIG_ERROR; } - if (iType == sci_pointer) { - sciErr = getPointer(pvApiCtx, piAddrVar, pObjValue); + if (iType == sci_mlist) { + int iItemCount = 0; + void *pvTypeinfo = NULL; + + sciErr = getListItemNumber(pvApiCtx, piAddrVar, &iItemCount); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + if (iItemCount < 3) { + return SWIG_ERROR; + } + + sciErr = getPointerInList(pvApiCtx, piAddrVar, 2, &pvTypeinfo); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + if (descriptor) { + swig_cast_info *cast = SWIG_TypeCheck(SWIG_TypeName((swig_type_info*)pvTypeinfo), descriptor); + return (cast != NULL); + } + else { + return SWIG_ERROR; + } + } + else { + return (iType == sci_pointer); + } +} + +SWIGINTERN int +SwigScilabPtrToObject(void *pvApiCtx, int iVar, void **pvObj, swig_type_info *descriptor, int flags, char *fname) { + SciErr sciErr; + int *piAddrVar = NULL; + int iType = 0; + void *pvPtr = NULL; + + sciErr = getVarAddressFromPosition(pvApiCtx, iVar, &piAddrVar); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + sciErr = getVarType(pvApiCtx, piAddrVar, &iType); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + if (iType == sci_mlist) { + int iItemCount = 0; + void *pvTypeinfo = NULL; + + sciErr = getListItemNumber(pvApiCtx, piAddrVar, &iItemCount); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return SWIG_ERROR; + } + if (iItemCount < 3) { + return SWIG_ERROR; + } + + sciErr = getPointerInList(pvApiCtx, piAddrVar, 2, &pvTypeinfo); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + sciErr = getPointerInList(pvApiCtx, piAddrVar, 3, &pvPtr); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + if (pvPtr) { + if (descriptor) { + swig_cast_info *cast = SWIG_TypeCheck(SWIG_TypeName((swig_type_info *)pvTypeinfo), descriptor); + if (cast) { + int newmemory = 0; + pvPtr = SWIG_TypeCast(cast, pvPtr, &newmemory); + // TODO newmemory + } + else { + return SWIG_ERROR; + } + } + } + } + else if (iType == sci_pointer) { + sciErr = getPointer(pvApiCtx, piAddrVar, &pvPtr); if (sciErr.iErr) { printError(&sciErr, 0); return SWIG_ERROR; @@ -130,22 +297,65 @@ SwigScilabPtrToObject(void *pvApiCtx, int iVar, void **pObjValue, swig_type_info return SWIG_ERROR; } - return SWIG_OK; + if (pvObj) { + *pvObj = pvPtr; + return SWIG_OK; + } + else { + return SWIG_ERROR; + } } SWIGRUNTIMEINLINE int -SwigScilabPtrFromObject(void *pvApiCtx, int iVarOut, void *obj, swig_type_info *descriptor, int flags) { +SwigScilabPtrFromObject(void *pvApiCtx, int iVarOut, void *pvObj, swig_type_info *descriptor, int flags, const char *pstTypeName) { SciErr sciErr; - sciErr = createPointer(pvApiCtx, SWIG_NbInputArgument(pvApiCtx) + iVarOut, (void *)obj); - if (sciErr.iErr) { - printError(&sciErr, 0); - return SWIG_ERROR; + if (descriptor) { + int *piMListAddr = NULL; + + sciErr = createMList(pvApiCtx, SWIG_NbInputArgument(pvApiCtx) + iVarOut, 3, &piMListAddr); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + if (pstTypeName == NULL) { + pstTypeName = SWIG_TypeName(descriptor); + } + + sciErr = createMatrixOfStringInList(pvApiCtx, SWIG_NbInputArgument(pvApiCtx) + iVarOut, piMListAddr, 1, 1, 1, &pstTypeName); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + sciErr = createPointerInList(pvApiCtx, SWIG_NbInputArgument(pvApiCtx) + iVarOut, piMListAddr, 2, descriptor); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + + sciErr = createPointerInList(pvApiCtx, SWIG_NbInputArgument(pvApiCtx) + iVarOut, piMListAddr, 3, pvObj); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } + } + else { + sciErr = createPointer(pvApiCtx, SWIG_NbInputArgument(pvApiCtx) + iVarOut, pvObj); + if (sciErr.iErr) { + printError(&sciErr, 0); + return SWIG_ERROR; + } } return SWIG_OK; } +/* Pointer argument conversions */ + + SWIGRUNTIME int SWIG_Scilab_ConvertPacked(void *pvApiCtx, int iVar, void *ptr, int sz, swig_type_info *ty, char *fname) { swig_cast_info *tc; @@ -209,69 +419,7 @@ SWIG_Scilab_NewMemberObj(void *pvApiCtx, int iVarOut, void *ptr, int sz, swig_ty } -/* Error functions */ -#define SCILAB_API_ARGUMENT_ERROR 999 - -SWIGINTERN const char* -SWIG_Scilab_ErrorType(int code) { - switch(code) { - case SWIG_MemoryError: - return "MemoryError"; - case SWIG_IOError: - return "IOError"; - case SWIG_RuntimeError: - return "RuntimeError"; - case SWIG_IndexError: - return "IndexError"; - case SWIG_TypeError: - return "TypeError"; - case SWIG_DivisionByZero: - return "ZeroDivisionError"; - case SWIG_OverflowError: - return "OverflowError"; - case SWIG_SyntaxError: - return "SyntaxError"; - case SWIG_ValueError: - return "ValueError"; - case SWIG_SystemError: - return "SystemError"; - case SWIG_AttributeError: - return "AttributeError"; - default: - return "RuntimeError"; - } -} -#define SWIG_ErrorType(code) SWIG_Scilab_ErrorType(code) - -#ifndef SWIG_SCILAB_ERROR -#define SWIG_SCILAB_ERROR 20000 -#endif - -SWIGINTERN void -SWIG_Scilab_Error(int code, const char *msg) -{ - Scierror(SWIG_SCILAB_ERROR - code, _("SWIG/Scilab: %s: %s\n"), SWIG_Scilab_ErrorType(code), msg); -} - -#define SWIG_Error(code, msg) SWIG_Scilab_Error(code, msg) - -#define SWIG_fail return SWIG_ERROR; - -SWIGRUNTIME void -SWIG_Scilab_Raise_Ex(const char *obj, const char *type, swig_type_info *descriptor) { - if (type) { - if (obj) - Scierror(SWIG_SCILAB_ERROR, "SWIG/Scilab: Exception (%s) occured: %s\n", type, obj); - else - Scierror(SWIG_SCILAB_ERROR, "SWIG/Scilab: Exception (%s) occured.\n", type); - } -} - -SWIGRUNTIME void -SWIG_Scilab_Raise(const int obj, const char *type, swig_type_info *descriptor) { - Scierror(SWIG_SCILAB_ERROR, "SWIG/Scilab: Exception (%s) occured.\n", type); -} /* * Pointer utility functions @@ -318,10 +466,9 @@ int SWIG_ptr(SWIG_GatewayParameters) { } SWIG_Scilab_SetOutputPosition(1); return SWIG_Scilab_SetOutput(pvApiCtx, - SwigScilabPtrFromObject(pvApiCtx, 1, (void *) (uintptr_t)dValue, NULL, 0)); + SwigScilabPtrFromObject(pvApiCtx, 1, (void *) (uintptr_t)dValue, NULL, 0, NULL)); } else { return SWIG_ERROR; } } - diff --git a/Lib/scilab/sciruntime.swg b/Lib/scilab/sciruntime.swg index 9832ed411..9abedfe3d 100644 --- a/Lib/scilab/sciruntime.swg +++ b/Lib/scilab/sciruntime.swg @@ -1,33 +1,45 @@ %insert(runtime) "swigrun.swg"; %insert(runtime) "swigerrors.swg"; -#define %scilabcode %insert("scilab") - %insert(runtime) "scirun.swg"; -%init %{ +%insert(init) %{ +/* Module management functions */ + #define SWIG_GetModule(clientdata) SWIG_Scilab_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Scilab_SetModule(pointer) SWIGRUNTIME swig_module_info* -SWIG_Scilab_GetModule(void) -{ +SWIG_Scilab_GetModule(void) { return NULL; } SWIGRUNTIME void -SWIG_Scilab_SetModule(swig_module_info *swig_module) -{ +SWIG_Scilab_SetModule(swig_module_info *swig_module) { } %} %insert(init) "swiginit.swg" -%init %{ +%insert(init) %{ +SWIGRUNTIME swig_type_info * +SWIG_Scilab_TypeQuery(const char *name) { + if (SWIG_Module_Initialized()) { + return SWIG_TypeQuery(name); + } + else { + SWIG_Error(SWIG_RuntimeError, "the module is not initialized"); + return NULL; + } +} +%} + +%insert(init) %{ #ifdef __cplusplus extern "C" #endif int _Init(SWIG_GatewayParameters) { SWIG_InitializeModule(NULL); SWIG_CreateScilabVariables(pvApiCtx); + swig_module_initialized = 1; %} diff --git a/Lib/scilab/scisequence.swg b/Lib/scilab/scisequence.swg index cc9da1fab..5fe0fdbe2 100644 --- a/Lib/scilab/scisequence.swg +++ b/Lib/scilab/scisequence.swg @@ -47,21 +47,21 @@ namespace swig { // Error returned for sequence containers of default item type template struct traits_as_sequence { static int check(SwigSciObject obj) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } static int get(SwigSciObject obj, void **sequence) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } static int size(SwigSciObject obj, int *size) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } }; template struct traits_from_sequence { static int create(int size, void **sequence) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } static SwigSciObject set(int size, void *sequence) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } }; @@ -136,12 +136,12 @@ namespace swig { // Error returned for sequence containers of default item type template struct traits_asval_sequenceitem { static T asval(SwigSciObject obj, void *pSequence, int iItemIndex) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } }; template struct traits_from_sequenceitem { static int from(void *pSequence, int iItemIndex, T itemValue) { - SWIG_Error(SWIG_TypeError, type_name()); + throw std::invalid_argument("The container data type is not supported."); } }; diff --git a/Lib/scilab/scisequencebool.swg b/Lib/scilab/scisequencebool.swg index 0430c3e39..b7d078448 100644 --- a/Lib/scilab/scisequencebool.swg +++ b/Lib/scilab/scisequencebool.swg @@ -84,7 +84,7 @@ SWIG_FromSet_Sequence_dec(bool)(int size, int *pSequence) { SWIGINTERN bool SWIG_AsVal_SequenceItem_dec(bool)(SwigSciObject obj, int *pSequence, int iItemIndex) { - return pSequence[iItemIndex]; + return (bool) pSequence[iItemIndex]; } } diff --git a/Lib/scilab/scisequencestring.swg b/Lib/scilab/scisequencestring.swg index 36f0927a8..d3c05e4f8 100644 --- a/Lib/scilab/scisequencestring.swg +++ b/Lib/scilab/scisequencestring.swg @@ -1,5 +1,5 @@ /* - *char + * * Scilab matrix of string <-> C++ std::string container * */ @@ -88,7 +88,7 @@ SWIG_AsVal_SequenceItem_dec(std::string)(SwigSciObject obj, char **pSequence, in SWIGINTERN int SWIG_From_SequenceItem_dec(std::string)(char **pSequence, int iItemIndex, std::string itemValue) { - char *pChar = new char(itemValue.size() + 1); + char *pChar = new char((int) itemValue.size() + 1); strcpy(pChar, itemValue.c_str()); pSequence[iItemIndex] = pChar; return SWIG_OK; diff --git a/Lib/scilab/scistdcommon.swg b/Lib/scilab/scistdcommon.swg index 7fdc72212..63f3ca164 100644 --- a/Lib/scilab/scistdcommon.swg +++ b/Lib/scilab/scistdcommon.swg @@ -42,7 +42,8 @@ namespace swig { struct traits_asptr { static int asptr(const SwigSciObject& obj, Type **val) { Type *p; - int res = SWIG_ConvertPtr(obj, (void**)&p, type_info(), 0); + swig_type_info *descriptor = type_info(); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = p; } diff --git a/Lib/scilab/scitypemaps.swg b/Lib/scilab/scitypemaps.swg index 62a819f35..175a41b51 100644 --- a/Lib/scilab/scitypemaps.swg +++ b/Lib/scilab/scitypemaps.swg @@ -147,11 +147,18 @@ } %enddef +%define %scilab_typecheck_pointer(PRECEDENCE, TYPE) +%typecheck(PRECEDENCE) TYPE { + $1 = SwigScilabCheckPtr(pvApiCtx, $input, $descriptor, SWIG_Scilab_GetFuncName()); +} +%enddef + + // Double (and Float) have priority over before Integer type. // Primitive types -%scilab_typecheck_generic(SWIG_TYPECHECK_VOIDPTR, isPointerType, SWIGTYPE *) -%scilab_typecheck_generic(SWIG_TYPECHECK_POINTER, isPointerType, SWIGTYPE *) +%scilab_typecheck_pointer(SWIG_TYPECHECK_VOIDPTR, SWIGTYPE *) +%scilab_typecheck_pointer(SWIG_TYPECHECK_POINTER, SWIGTYPE *) %scilab_typecheck_generic(SWIG_TYPECHECK_BOOL, isBooleanType, bool) %scilab_typecheck_generic(16, isDoubleType, double) %scilab_typecheck_generic(17, isDoubleType, float) diff --git a/Lib/scilab/std_basic_string.i b/Lib/scilab/std_basic_string.i index 4922abd35..43b660db6 100644 --- a/Lib/scilab/std_basic_string.i +++ b/Lib/scilab/std_basic_string.i @@ -16,7 +16,6 @@ SWIG_AsPtr_dec(std::basic_string)(int _iVar, std::basic_string **_ps if (buf) { if (_pstValue) { *_pstValue = new std::string(buf, len - 1); - sciprint("%s\n", (*_pstValue)->c_str()); } if (alloc == SWIG_NEWOBJ) { delete[] buf; diff --git a/Lib/scilab/std_common.i b/Lib/scilab/std_common.i index 4524ffd6b..97cfa7b07 100644 --- a/Lib/scilab/std_common.i +++ b/Lib/scilab/std_common.i @@ -11,17 +11,17 @@ fragment=SWIG_From_frag(Type), fragment="StdTraits") { namespace swig { - template <> struct traits { + template <> struct traits< Type > { typedef value_category category; static const char* type_name() { return #Type; } - }; - template <> struct traits_asval { + }; + template <> struct traits_asval< Type > { typedef Type value_type; static int asval(SwigSciObject obj, value_type *val) { return SWIG_AsVal(Type)(obj, val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static SwigSciObject from(const value_type& val) { return SWIG_From(Type)(val); @@ -44,13 +44,13 @@ namespace swig { fragment=SWIG_From_frag(int), fragment="StdTraits") { namespace swig { - template <> struct traits_asval { + template <> struct traits_asval< Type > { typedef Type value_type; static int asval(SwigSciObject obj, value_type *val) { return SWIG_AsVal(int)(obj, (int *)val); } }; - template <> struct traits_from { + template <> struct traits_from< Type > { typedef Type value_type; static SwigSciObject from(const value_type& val) { return SWIG_From(int)((int)val); diff --git a/Lib/shared_ptr.i b/Lib/shared_ptr.i index 450493db4..2975b0628 100644 --- a/Lib/shared_ptr.i +++ b/Lib/shared_ptr.i @@ -4,6 +4,13 @@ // to use a pointer to the smart pointer of the type, rather than the usual pointer to the underlying type. // So for some type T, shared_ptr * is used rather than T *. +// Another key part of the implementation is the smartptr feature: +// %feature("smartptr") T { shared_ptr } +// This feature marks the class T as having a smartptr to it (the shared_ptr type). This is then used to +// support smart pointers and inheritance. Say class D derives from base B, then shared_ptr is marked +// with a fake inheritance from shared_ptr in the type system if the "smartptr" feature is used on both +// B and D. This is to emulate the conversion of shared_ptr to shared_ptr in the target language. + // shared_ptr namespaces could be boost or std or std::tr1 // For example for std::tr1, use: // #define SWIG_SHARED_PTR_NAMESPACE std diff --git a/Lib/std/_std_deque.i b/Lib/std/_std_deque.i index 7dd3552db..af9db27f4 100644 --- a/Lib/std/_std_deque.i +++ b/Lib/std/_std_deque.i @@ -24,7 +24,7 @@ }; */ -%define %std_deque_methods_noempty(T) +%define %std_deque_methods_noempty(T...) typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T value_type; @@ -35,11 +35,11 @@ deque(); deque(unsigned int size, const T& value=T()); - deque(const deque &); + deque(const deque< T > &); ~deque(); void assign(unsigned int n, const T& value); - void swap(deque &x); + void swap(deque< T > &x); unsigned int size() const; unsigned int max_size() const; void resize(unsigned int n, T c = T()); @@ -78,17 +78,17 @@ throw std::out_of_range("deque index out of range"); } } - std::deque getslice(int i, int j) { + std::deque< T > getslice(int i, int j) { int size = int(self->size()); if (i<0) i = size+i; if (j<0) j = size+j; if (i<0) i = 0; if (j>size) j = size; - std::deque tmp(j-i); + std::deque< T > tmp(j-i); std::copy(self->begin()+i,self->begin()+j,tmp.begin()); return tmp; } - void setslice(int i, int j, const std::deque& v) { + void setslice(int i, int j, const std::deque< T >& v) { int size = int(self->size()); if (i<0) i = size+i; if (j<0) j = size+j; @@ -116,7 +116,7 @@ %enddef #ifdef SWIGPHP -%define %std_deque_methods(T) +%define %std_deque_methods(T...) %extend { bool is_empty() const { return self->empty(); @@ -125,7 +125,7 @@ %std_deque_methods_noempty(T) %enddef #else -%define %std_deque_methods(T) +%define %std_deque_methods(T...) bool empty() const; %std_deque_methods_noempty(T) %enddef diff --git a/Lib/std/std_array.i b/Lib/std/std_array.i new file mode 100644 index 000000000..aadc3b80c --- /dev/null +++ b/Lib/std/std_array.i @@ -0,0 +1,85 @@ +// +// std::array +// + +%include + +%define %std_array_methods(array...) + %std_sequence_methods_non_resizable(array) + void fill(const value_type& u); +%enddef + + +%define %std_array_methods_val(array...) + %std_sequence_methods_non_resizable_val(array) + void fill(const value_type& u); +%enddef + +// ------------------------------------------------------------------------ +// std::array +// +// The aim of all that follows would be to integrate std::array with +// as much as possible, namely, to allow the user to pass and +// be returned tuples or lists. +// const declarations are used to guess the intent of the function being +// exported; therefore, the following rationale is applied: +// +// -- f(std::array), f(const std::array&): +// the parameter being read-only, either a sequence or a +// previously wrapped std::array can be passed. +// -- f(std::array&), f(std::array*): +// the parameter may be modified; therefore, only a wrapped std::array +// can be passed. +// -- std::array f(), const std::array& f(): +// the array is returned by copy; therefore, a sequence of T:s +// is returned which is most easily used in other functions +// -- std::array& f(), std::array* f(): +// the array is returned by reference; therefore, a wrapped std::array +// is returned +// -- const std::array* f(), f(const std::array*): +// for consistency, they expect and return a plain array pointer. +// ------------------------------------------------------------------------ + + +// exported classes + +namespace std { + + template + class array { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Tp value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef _Tp& reference; + typedef const _Tp& const_reference; + + %traits_swigtype(_Tp); + %traits_enum(_Tp); + + %fragment(SWIG_Traits_frag(std::array< _Tp, _Nm >), "header", + fragment=SWIG_Traits_frag(_Tp), + fragment="StdArrayTraits") { + namespace swig { + template <> struct traits > { + typedef pointer_category category; + static const char* type_name() { + return "std::array<" #_Tp "," #_Nm " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_STDARRAY, std::array< _Tp, _Nm >); + +#ifdef %swig_array_methods + // Add swig/language extra methods + %swig_array_methods(std::array< _Tp, _Nm >); +#endif + + %std_array_methods(array); + }; +} + diff --git a/Lib/std/std_basic_string.i b/Lib/std/std_basic_string.i index 1aa5721c9..fb7afc1e6 100644 --- a/Lib/std/std_basic_string.i +++ b/Lib/std/std_basic_string.i @@ -200,7 +200,7 @@ namespace std { #ifdef %swig_basic_string // Add swig/language extra methods - %swig_basic_string(std::basic_string<_CharT, _Traits, _Alloc >); + %swig_basic_string(std::basic_string< _CharT, _Traits, _Alloc >); #endif #ifdef SWIG_EXPORT_ITERATOR_METHODS @@ -238,19 +238,19 @@ namespace std { %newobject __radd__; %extend { - std::basic_string<_CharT,_Traits,_Alloc >* __add__(const basic_string& v) { - std::basic_string<_CharT,_Traits,_Alloc >* res = new std::basic_string<_CharT,_Traits,_Alloc >(*self); + std::basic_string< _CharT,_Traits,_Alloc >* __add__(const basic_string& v) { + std::basic_string< _CharT,_Traits,_Alloc >* res = new std::basic_string< _CharT,_Traits,_Alloc >(*self); *res += v; return res; } - std::basic_string<_CharT,_Traits,_Alloc >* __radd__(const basic_string& v) { - std::basic_string<_CharT,_Traits,_Alloc >* res = new std::basic_string<_CharT,_Traits,_Alloc >(v); + std::basic_string< _CharT,_Traits,_Alloc >* __radd__(const basic_string& v) { + std::basic_string< _CharT,_Traits,_Alloc >* res = new std::basic_string< _CharT,_Traits,_Alloc >(v); *res += *self; return res; } - std::basic_string<_CharT,_Traits,_Alloc > __str__() { + std::basic_string< _CharT,_Traits,_Alloc > __str__() { return *self; } diff --git a/Lib/std/std_common.i b/Lib/std/std_common.i index 6e93e29f6..05bc4325a 100644 --- a/Lib/std/std_common.i +++ b/Lib/std/std_common.i @@ -72,7 +72,7 @@ namespace std { %} %fragment("StdTraitsCommon","header",fragment="") %{ -namespace swig { +namespace swig { template struct noconst_traits { typedef Type noconst_type; @@ -86,7 +86,7 @@ namespace swig { /* type categories */ - struct pointer_category { }; + struct pointer_category { }; struct value_category { }; /* @@ -99,12 +99,25 @@ namespace swig { return traits::noconst_type >::type_name(); } - template - struct traits_info { + template struct traits_info { static swig_type_info *type_query(std::string name) { name += " *"; return SWIG_TypeQuery(name.c_str()); - } + } + static swig_type_info *type_info() { + static swig_type_info *info = type_query(type_name()); + return info; + } + }; + + /* + Partial specialization for pointers (traits_info) + */ + template struct traits_info { + static swig_type_info *type_query(std::string name) { + name += " *"; + return SWIG_TypeQuery(name.c_str()); + } static swig_type_info *type_info() { static swig_type_info *info = type_query(type_name()); return info; @@ -117,7 +130,7 @@ namespace swig { } /* - Partial specialization for pointers + Partial specialization for pointers (traits) */ template struct traits { typedef pointer_category category; @@ -125,22 +138,22 @@ namespace swig { std::string ptrname = name; ptrname += " *"; return ptrname; - } + } static const char* type_name() { static std::string name = make_ptr_name(swig::type_name()); return name.c_str(); } }; - template + template struct traits_as { }; - - template + + template struct traits_check { }; } %} - + /* Generate the traits for a swigtype */ @@ -148,7 +161,7 @@ namespace swig { %define %traits_swigtype(Type...) %fragment(SWIG_Traits_frag(Type),"header",fragment="StdTraits") { namespace swig { - template <> struct traits { + template <> struct traits< Type > { typedef pointer_category category; static const char* type_name() { return #Type; } }; @@ -164,7 +177,7 @@ namespace swig { %define %typemap_traits(Code,Type...) %typemaps_asvalfrom(%arg(Code), - %arg(swig::asval), + %arg(swig::asval< Type >), %arg(swig::from), %arg(SWIG_Traits_frag(Type)), %arg(SWIG_Traits_frag(Type)), @@ -194,10 +207,10 @@ namespace swig { bool operator == (const Type& v) { return *self == v; } - + bool operator != (const Type& v) { return *self != v; - } + } } %enddef @@ -211,7 +224,7 @@ namespace swig { bool operator > (const Type& v) { return *self > v; } - + bool operator < (const Type& v) { return *self < v; } diff --git a/Lib/std/std_container.i b/Lib/std/std_container.i index 8ed327bbe..5fa085afa 100644 --- a/Lib/std/std_container.i +++ b/Lib/std/std_container.i @@ -6,20 +6,17 @@ #include %} -// Common container methods +// Common non-resizable container methods + +%define %std_container_methods_non_resizable(container...) -%define %std_container_methods(container...) container(); container(const container&); bool empty() const; size_type size() const; - void clear(); - void swap(container& v); - allocator_type get_allocator() const; - #ifdef SWIG_EXPORT_ITERATOR_METHODS class iterator; class reverse_iterator; @@ -34,17 +31,27 @@ %enddef +// Common container methods + +%define %std_container_methods(container...) + %std_container_methods_non_resizable(%arg(container)) + + void clear(); + allocator_type get_allocator() const; + +%enddef + // Common sequence %define %std_sequence_methods_common(sequence) - + %std_container_methods(%arg(sequence)); - + sequence(size_type size); void pop_back(); - + void resize(size_type new_size); - + #ifdef SWIG_EXPORT_ITERATOR_METHODS %extend { // %extend wrapper used for differing definitions of these methods introduced in C++11 @@ -52,24 +59,31 @@ iterator erase(iterator first, iterator last) { return $self->erase(first, last); } } #endif - + %enddef +%define %std_sequence_methods_non_resizable(sequence) -%define %std_sequence_methods(sequence) - - %std_sequence_methods_common(%arg(sequence)); - - sequence(size_type size, const value_type& value); - void push_back(const value_type& x); + %std_container_methods_non_resizable(%arg(sequence)) const value_type& front() const; const value_type& back() const; - - void assign(size_type n, const value_type& x); +%enddef + +%define %std_sequence_methods(sequence) + + %std_sequence_methods_common(%arg(sequence)); + + sequence(size_type size, const value_type& value); + void push_back(const value_type& x); + + const value_type& front() const; + const value_type& back() const; + + void assign(size_type n, const value_type& x); void resize(size_type new_size, const value_type& x); - + #ifdef SWIG_EXPORT_ITERATOR_METHODS %extend { // %extend wrapper used for differing definitions of these methods introduced in C++11 @@ -77,23 +91,33 @@ void insert(iterator pos, size_type n, const value_type& x) { $self->insert(pos, n, x); } } #endif - + %enddef -%define %std_sequence_methods_val(sequence...) - - %std_sequence_methods_common(%arg(sequence)); - - sequence(size_type size, value_type value); - void push_back(value_type x); +%define %std_sequence_methods_non_resizable_val(sequence...) + + %std_container_methods_non_resizable(%arg(sequence)) value_type front() const; value_type back() const; - - void assign(size_type n, value_type x); +#endif + +%enddef + +%define %std_sequence_methods_val(sequence...) + + %std_sequence_methods_common(%arg(sequence)); + + sequence(size_type size, value_type value); + void push_back(value_type x); + + value_type front() const; + value_type back() const; + + void assign(size_type n, value_type x); void resize(size_type new_size, value_type x); - + #ifdef SWIG_EXPORT_ITERATOR_METHODS %extend { // %extend wrapper used for differing definitions of these methods introduced in C++11 @@ -101,7 +125,7 @@ void insert(iterator pos, size_type n, value_type x) { $self->insert(pos, n, x); } } #endif - + %enddef @@ -109,10 +133,10 @@ // Ignore member methods for Type with no default constructor // %define %std_nodefconst_type(Type...) -%feature("ignore") std::vector::vector(size_type size); -%feature("ignore") std::vector::resize(size_type size); -%feature("ignore") std::deque::deque(size_type size); -%feature("ignore") std::deque::resize(size_type size); -%feature("ignore") std::list::list(size_type size); -%feature("ignore") std::list::resize(size_type size); +%feature("ignore") std::vector< Type >::vector(size_type size); +%feature("ignore") std::vector< Type >::resize(size_type size); +%feature("ignore") std::deque< Type >::deque(size_type size); +%feature("ignore") std::deque< Type >::resize(size_type size); +%feature("ignore") std::list< Type >::list(size_type size); +%feature("ignore") std::list< Type >::resize(size_type size); %enddef diff --git a/Lib/std/std_deque.i b/Lib/std/std_deque.i index a99763b79..aa5536bf6 100644 --- a/Lib/std/std_deque.i +++ b/Lib/std/std_deque.i @@ -49,7 +49,7 @@ namespace std { - template > + template > class deque { public: typedef size_t size_type; @@ -63,11 +63,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::deque<_Tp, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::deque< _Tp, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdDequeTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::deque<" #_Tp " >"; @@ -76,18 +76,18 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_DEQUE, std::deque<_Tp, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_DEQUE, std::deque< _Tp, _Alloc >); #ifdef %swig_deque_methods // Add swig/language extra methods - %swig_deque_methods(std::deque<_Tp, _Alloc >); + %swig_deque_methods(std::deque< _Tp, _Alloc >); #endif %std_deque_methods(deque); }; template - class deque<_Tp*, _Alloc > { + class deque< _Tp*, _Alloc > { public: typedef size_t size_type; typedef ptrdiff_t difference_type; @@ -100,11 +100,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::deque<_Tp*, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::deque< _Tp*, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdDequeTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::deque<" #_Tp " * >"; @@ -113,14 +113,14 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_DEQUE, std::deque<_Tp*, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_DEQUE, std::deque< _Tp*, _Alloc >); #ifdef %swig_deque_methods_val // Add swig/language extra methods - %swig_deque_methods_val(std::deque<_Tp*, _Alloc >); + %swig_deque_methods_val(std::deque< _Tp*, _Alloc >); #endif - %std_deque_methods_val(std::deque<_Tp*, _Alloc >); + %std_deque_methods_val(deque); }; } diff --git a/Lib/std/std_except.i b/Lib/std/std_except.i index 75b8d0fd6..728b9c8b5 100644 --- a/Lib/std/std_except.i +++ b/Lib/std/std_except.i @@ -3,6 +3,7 @@ #endif %{ +#include #include %} @@ -15,6 +16,10 @@ namespace std { virtual const char* what() const throw(); }; + struct bad_cast : exception + { + }; + struct bad_exception : exception { }; diff --git a/Lib/std/std_list.i b/Lib/std/std_list.i index e08935170..ebbafa22b 100644 --- a/Lib/std/std_list.i +++ b/Lib/std/std_list.i @@ -6,7 +6,7 @@ // List -%define %std_list_methods(list) +%define %std_list_methods(list...) %std_sequence_methods(list) void pop_front(); @@ -17,7 +17,7 @@ %enddef -%define %std_list_methods_val(list) +%define %std_list_methods_val(list...) %std_sequence_methods_val(list) void pop_front(); @@ -61,7 +61,7 @@ namespace std { - template > + template > class list { public: typedef size_t size_type; @@ -75,11 +75,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::list<_Tp, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::list< _Tp, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdListTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::list<" #_Tp ", " #_Alloc " >"; @@ -88,18 +88,18 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_LIST, std::list<_Tp, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_LIST, std::list< _Tp, _Alloc >); #ifdef %swig_list_methods // Add swig/language extra methods - %swig_list_methods(std::list<_Tp, _Alloc >); + %swig_list_methods(std::list< _Tp, _Alloc >); #endif %std_list_methods(list); }; template - class list<_Tp*, _Alloc> { + class list< _Tp*, _Alloc> { public: typedef size_t size_type; typedef ptrdiff_t difference_type; @@ -112,11 +112,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::list<_Tp*, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::list< _Tp*, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdListTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::list<" #_Tp " *," #_Alloc " >"; @@ -125,11 +125,11 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_LIST, std::list<_Tp*, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_LIST, std::list< _Tp*, _Alloc >); #ifdef %swig_list_methods_val // Add swig/language extra methods - %swig_list_methods_val(std::list<_Tp*, _Alloc >); + %swig_list_methods_val(std::list< _Tp*, _Alloc >); #endif %std_list_methods_val(list); @@ -138,9 +138,9 @@ namespace std { } %define %std_extequal_list(...) -%extend std::list<__VA_ARGS__ > { +%extend std::list< __VA_ARGS__ > { void remove(const value_type& x) { self->remove(x); } - void merge(std::list<__VA_ARGS__ >& x){ self->merge(x); } + void merge(std::list< __VA_ARGS__ >& x){ self->merge(x); } void unique() { self->unique(); } void sort() { self->sort(); } } diff --git a/Lib/std/std_map.i b/Lib/std/std_map.i index d1f6b3a16..8043f924c 100644 --- a/Lib/std/std_map.i +++ b/Lib/std/std_map.i @@ -66,14 +66,14 @@ namespace std { template, - class _Alloc = allocator > > + class _Alloc = allocator > > class map { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Key key_type; typedef _Tp mapped_type; - typedef std::pair value_type; + typedef std::pair< const _Key, _Tp > value_type; typedef value_type* pointer; typedef const value_type* const_pointer; @@ -98,11 +98,11 @@ namespace std { } } - %fragment(SWIG_Traits_frag(std::map<_Key, _Tp, _Compare, _Alloc >), "header", - fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >), + %fragment(SWIG_Traits_frag(std::map< _Key, _Tp, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(std::pair< _Key, _Tp >), fragment="StdMapTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::map<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >"; @@ -111,13 +111,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_MAP, std::map<_Key, _Tp, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_MAP, std::map< _Key, _Tp, _Compare, _Alloc >); map( const _Compare& ); #ifdef %swig_map_methods // Add swig/language extra methods - %swig_map_methods(std::map<_Key, _Tp, _Compare, _Alloc >); + %swig_map_methods(std::map< _Key, _Tp, _Compare, _Alloc >); #endif %std_map_methods(map); diff --git a/Lib/std/std_multimap.i b/Lib/std/std_multimap.i index 39f674da5..7aa949907 100644 --- a/Lib/std/std_multimap.i +++ b/Lib/std/std_multimap.i @@ -41,15 +41,15 @@ namespace std { - template, - class _Alloc = allocator > > + template, + class _Alloc = allocator > > class multimap { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Key key_type; typedef _Tp mapped_type; - typedef std::pair value_type; + typedef std::pair< const _Key, _Tp > value_type; typedef value_type* pointer; typedef const value_type* const_pointer; @@ -74,11 +74,11 @@ namespace std { } } - %fragment(SWIG_Traits_frag(std::multimap<_Key, _Tp, _Compare, _Alloc >), "header", - fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >), + %fragment(SWIG_Traits_frag(std::multimap< _Key, _Tp, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(std::pair< _Key, _Tp >), fragment="StdMultimapTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::multimap<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >"; @@ -87,13 +87,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_MULTIMAP, std::multimap<_Key, _Tp, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_MULTIMAP, std::multimap< _Key, _Tp, _Compare, _Alloc >); multimap( const _Compare& ); #ifdef %swig_multimap_methods // Add swig/language extra methods - %swig_multimap_methods(std::multimap<_Key, _Tp, _Compare, _Alloc >); + %swig_multimap_methods(std::multimap< _Key, _Tp, _Compare, _Alloc >); #endif %std_multimap_methods(multimap); diff --git a/Lib/std/std_multiset.i b/Lib/std/std_multiset.i index b63fb92b9..1aa7ccce8 100644 --- a/Lib/std/std_multiset.i +++ b/Lib/std/std_multiset.i @@ -40,8 +40,8 @@ namespace std { //multiset - template , - class _Alloc = allocator<_Key> > + template , + class _Alloc = allocator< _Key > > class multiset { public: typedef size_t size_type; @@ -56,11 +56,11 @@ namespace std { %traits_swigtype(_Key); - %fragment(SWIG_Traits_frag(std::multiset<_Key, _Compare, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::multiset< _Key, _Compare, _Alloc >), "header", fragment=SWIG_Traits_frag(_Key), fragment="StdMultisetTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::multiset<" #_Key "," #_Compare "," #_Alloc " >"; @@ -69,13 +69,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_MULTISET, std::multiset<_Key, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_MULTISET, std::multiset< _Key, _Compare, _Alloc >); multiset( const _Compare& ); #ifdef %swig_multiset_methods // Add swig/language extra methods - %swig_multiset_methods(std::multiset<_Key, _Compare, _Alloc >); + %swig_multiset_methods(std::multiset< _Key, _Compare, _Alloc >); #endif %std_multiset_methods(multiset); diff --git a/Lib/std/std_pair.i b/Lib/std/std_pair.i index 2743430e9..001cd6738 100644 --- a/Lib/std/std_pair.i +++ b/Lib/std/std_pair.i @@ -13,12 +13,12 @@ namespace std { %traits_swigtype(T); %traits_swigtype(U); - %fragment(SWIG_Traits_frag(std::pair), "header", + %fragment(SWIG_Traits_frag(std::pair< T, U >), "header", fragment=SWIG_Traits_frag(T), fragment=SWIG_Traits_frag(U), fragment="StdPairTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::pair<" #T "," #U " >"; @@ -28,23 +28,23 @@ namespace std { } #ifndef SWIG_STD_PAIR_ASVAL - %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair); + %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair< T, U >); #else - %typemap_traits(SWIG_TYPECHECK_PAIR, std::pair); + %typemap_traits(SWIG_TYPECHECK_PAIR, std::pair< T, U >); #endif pair(); pair(T first, U second); pair(const pair& p); - template pair(const pair &p); + template pair(const pair< U1, U2 > &p); T first; U second; #ifdef %swig_pair_methods // Add swig/language extra methods - %swig_pair_methods(std::pair) + %swig_pair_methods(std::pair< T, U >) #endif }; @@ -52,19 +52,19 @@ namespace std { // The following specializations should disappear or get // simplified when a 'const SWIGTYPE*&' can be defined // *** - template struct pair { + template struct pair< T, U* > { typedef T first_type; typedef U* second_type; %traits_swigtype(T); %traits_swigtype(U); - %fragment(SWIG_Traits_frag(std::pair), "header", + %fragment(SWIG_Traits_frag(std::pair< T, U* >), "header", fragment=SWIG_Traits_frag(T), fragment=SWIG_Traits_frag(U), fragment="StdPairTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::pair<" #T "," #U " * >"; @@ -73,7 +73,7 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair); + %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair< T, U* >); pair(); pair(T __a, U* __b); @@ -84,23 +84,23 @@ namespace std { #ifdef %swig_pair_methods // Add swig/language extra methods - %swig_pair_methods(std::pair) + %swig_pair_methods(std::pair< T, U* >) #endif }; - template struct pair { + template struct pair< T*, U > { typedef T* first_type; typedef U second_type; %traits_swigtype(T); %traits_swigtype(U); - %fragment(SWIG_Traits_frag(std::pair), "header", + %fragment(SWIG_Traits_frag(std::pair< T*, U >), "header", fragment=SWIG_Traits_frag(T), fragment=SWIG_Traits_frag(U), fragment="StdPairTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::pair<" #T " *," #U " >"; @@ -109,7 +109,7 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair); + %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair< T*, U >); pair(); pair(T* __a, U __b); @@ -120,23 +120,23 @@ namespace std { #ifdef %swig_pair_methods // Add swig/language extra methods - %swig_pair_methods(std::pair) + %swig_pair_methods(std::pair< T*, U >) #endif }; - template struct pair { + template struct pair< T*, U* > { typedef T* first_type; typedef U* second_type; %traits_swigtype(T); %traits_swigtype(U); - %fragment(SWIG_Traits_frag(std::pair), "header", + %fragment(SWIG_Traits_frag(std::pair< T*, U* >), "header", fragment=SWIG_Traits_frag(T), fragment=SWIG_Traits_frag(U), fragment="StdPairTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::pair<" #T " *," #U " * >"; @@ -145,7 +145,7 @@ namespace std { } } - %typemap_traits(SWIG_TYPECHECK_PAIR, std::pair); + %typemap_traits(SWIG_TYPECHECK_PAIR, std::pair< T*, U* >); pair(); pair(T* __a, U* __b); @@ -156,7 +156,7 @@ namespace std { #ifdef %swig_pair_methods // Add swig/language extra methods - %swig_pair_methods(std::pair) + %swig_pair_methods(std::pair< T*, U* >) #endif }; diff --git a/Lib/std/std_queue.i b/Lib/std/std_queue.i index 42273eee6..b2c8d8d33 100644 --- a/Lib/std/std_queue.i +++ b/Lib/std/std_queue.i @@ -57,7 +57,7 @@ namespace std { - template > + template > class queue { public: typedef size_t size_type; @@ -68,11 +68,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::queue<_Tp, _Sequence >), "header", + %fragment(SWIG_Traits_frag(std::queue< _Tp, _Sequence >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdQueueTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::queue<" #_Tp "," #_Sequence " >"; @@ -81,18 +81,18 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_QUEUE, std::queue<_Tp, _Sequence >); + %typemap_traits_ptr(SWIG_TYPECHECK_QUEUE, std::queue< _Tp, _Sequence >); #ifdef %swig_queue_methods // Add swig/language extra methods - %swig_queue_methods(std::queue<_Tp, _Sequence >); + %swig_queue_methods(std::queue< _Tp, _Sequence >); #endif %std_queue_methods(queue); }; template - class queue<_Tp*, _Sequence > { + class queue< _Tp*, _Sequence > { public: typedef size_t size_type; typedef _Tp value_type; @@ -102,11 +102,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::queue<_Tp*, _Sequence >), "header", + %fragment(SWIG_Traits_frag(std::queue< _Tp*, _Sequence >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdQueueTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::queue<" #_Tp "," #_Sequence " * >"; @@ -115,14 +115,14 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_QUEUE, std::queue<_Tp*, _Sequence >); + %typemap_traits_ptr(SWIG_TYPECHECK_QUEUE, std::queue< _Tp*, _Sequence >); #ifdef %swig_queue_methods_val // Add swig/language extra methods - %swig_queue_methods_val(std::queue<_Tp*, _Sequence >); + %swig_queue_methods_val(std::queue< _Tp*, _Sequence >); #endif - %std_queue_methods_val(std::queue<_Tp*, _Sequence >); + %std_queue_methods_val(queue); }; } diff --git a/Lib/std/std_set.i b/Lib/std/std_set.i index f96ddd9f1..107a23c71 100644 --- a/Lib/std/std_set.i +++ b/Lib/std/std_set.i @@ -79,8 +79,8 @@ namespace std { - template , - class _Alloc = allocator<_Key> > + template , + class _Alloc = allocator< _Key > > class set { public: typedef size_t size_type; @@ -95,11 +95,11 @@ namespace std { %traits_swigtype(_Key); - %fragment(SWIG_Traits_frag(std::set<_Key, _Compare, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::set< _Key, _Compare, _Alloc >), "header", fragment=SWIG_Traits_frag(_Key), fragment="StdSetTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::set<" #_Key "," #_Compare "," #_Alloc " >"; @@ -108,13 +108,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_SET, std::set<_Key, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_SET, std::set< _Key, _Compare, _Alloc >); set( const _Compare& ); #ifdef %swig_set_methods // Add swig/language extra methods - %swig_set_methods(std::set<_Key, _Compare, _Alloc >); + %swig_set_methods(std::set< _Key, _Compare, _Alloc >); #endif %std_set_methods(set); diff --git a/Lib/std/std_stack.i b/Lib/std/std_stack.i index fb900a57c..5b624b571 100644 --- a/Lib/std/std_stack.i +++ b/Lib/std/std_stack.i @@ -56,7 +56,7 @@ namespace std { - template > + template > class stack { public: typedef size_t size_type; @@ -67,11 +67,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::stack<_Tp, _Sequence >), "header", + %fragment(SWIG_Traits_frag(std::stack< _Tp, _Sequence >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdStackTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::stack<" #_Tp "," #_Sequence " >"; @@ -80,18 +80,18 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_STACK, std::stack<_Tp, _Sequence >); + %typemap_traits_ptr(SWIG_TYPECHECK_STACK, std::stack< _Tp, _Sequence >); #ifdef %swig_stack_methods // Add swig/language extra methods - %swig_stack_methods(std::stack<_Tp, _Sequence >); + %swig_stack_methods(std::stack< _Tp, _Sequence >); #endif %std_stack_methods(stack); }; template - class stack<_Tp*, _Sequence > { + class stack< _Tp*, _Sequence > { public: typedef size_t size_type; typedef _Sequence::value_type value_type; @@ -101,11 +101,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::stack<_Tp*, _Sequence >), "header", + %fragment(SWIG_Traits_frag(std::stack< _Tp*, _Sequence >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdStackTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::stack<" #_Tp "," #_Sequence " * >"; @@ -114,14 +114,14 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_STACK, std::stack<_Tp*, _Sequence >); + %typemap_traits_ptr(SWIG_TYPECHECK_STACK, std::stack< _Tp*, _Sequence >); #ifdef %swig_stack_methods_val // Add swig/language extra methods - %swig_stack_methods_val(std::stack<_Tp*, _Sequence >); + %swig_stack_methods_val(std::stack< _Tp*, _Sequence >); #endif - %std_stack_methods_val(std::stack<_Tp*, _Sequence >); + %std_stack_methods_val(stack); }; } diff --git a/Lib/std/std_unordered_map.i b/Lib/std/std_unordered_map.i index 8c276172a..1cb714821 100644 --- a/Lib/std/std_unordered_map.i +++ b/Lib/std/std_unordered_map.i @@ -68,15 +68,15 @@ namespace std { - template, - class _Alloc = allocator > > + template, + class _Alloc = allocator > > class unordered_map { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Key key_type; typedef _Tp mapped_type; - typedef std::pair value_type; + typedef std::pair< const _Key, _Tp > value_type; typedef value_type* pointer; typedef const value_type* const_pointer; @@ -101,11 +101,11 @@ namespace std { } } - %fragment(SWIG_Traits_frag(std::unordered_map<_Key, _Tp, _Compare, _Alloc >), "header", - fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >), + %fragment(SWIG_Traits_frag(std::unordered_map< _Key, _Tp, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(std::pair< _Key, _Tp >), fragment="StdMapTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::unordered_map<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >"; @@ -114,13 +114,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_MAP, std::unordered_map<_Key, _Tp, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_MAP, std::unordered_map< _Key, _Tp, _Compare, _Alloc >); unordered_map( const _Compare& ); #ifdef %swig_unordered_map_methods // Add swig/language extra methods - %swig_unordered_map_methods(std::unordered_map<_Key, _Tp, _Compare, _Alloc >); + %swig_unordered_map_methods(std::unordered_map< _Key, _Tp, _Compare, _Alloc >); #endif %std_unordered_map_methods(unordered_map); diff --git a/Lib/std/std_unordered_multimap.i b/Lib/std/std_unordered_multimap.i index 74efb2896..46b56d88a 100644 --- a/Lib/std/std_unordered_multimap.i +++ b/Lib/std/std_unordered_multimap.i @@ -44,15 +44,15 @@ namespace std { - template, - class _Alloc = allocator > > + template, + class _Alloc = allocator > > class unordered_multimap { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Key key_type; typedef _Tp mapped_type; - typedef std::pair value_type; + typedef std::pair< const _Key, _Tp > value_type; typedef value_type* pointer; typedef const value_type* const_pointer; @@ -63,11 +63,11 @@ namespace std { %traits_swigtype(_Key); %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::unordered_multimap<_Key, _Tp, _Compare, _Alloc >), "header", - fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >), + %fragment(SWIG_Traits_frag(std::unordered_multimap< _Key, _Tp, _Compare, _Alloc >), "header", + fragment=SWIG_Traits_frag(std::pair< _Key, _Tp >), fragment="StdMultimapTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::unordered_multimap<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >"; @@ -76,13 +76,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_MULTIMAP, std::unordered_multimap<_Key, _Tp, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_MULTIMAP, std::unordered_multimap< _Key, _Tp, _Compare, _Alloc >); unordered_multimap( const _Compare& ); #ifdef %swig_unordered_multimap_methods // Add swig/language extra methods - %swig_unordered_multimap_methods(std::unordered_multimap<_Key, _Tp, _Compare, _Alloc >); + %swig_unordered_multimap_methods(std::unordered_multimap< _Key, _Tp, _Compare, _Alloc >); #endif %std_unordered_multimap_methods(unordered_multimap); diff --git a/Lib/std/std_unordered_multiset.i b/Lib/std/std_unordered_multiset.i index 56b971011..725ca2fe7 100644 --- a/Lib/std/std_unordered_multiset.i +++ b/Lib/std/std_unordered_multiset.i @@ -43,8 +43,8 @@ namespace std { //unordered_multiset - template , - class _Alloc = allocator<_Key> > + template , + class _Alloc = allocator< _Key > > class unordered_multiset { public: typedef size_t size_type; @@ -59,11 +59,11 @@ namespace std { %traits_swigtype(_Key); - %fragment(SWIG_Traits_frag(std::unordered_multiset<_Key, _Compare, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::unordered_multiset< _Key, _Compare, _Alloc >), "header", fragment=SWIG_Traits_frag(_Key), fragment="StdMultisetTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::unordered_multiset<" #_Key "," #_Compare "," #_Alloc " >"; @@ -72,13 +72,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_MULTISET, std::unordered_multiset<_Key, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_MULTISET, std::unordered_multiset< _Key, _Compare, _Alloc >); unordered_multiset( const _Compare& ); #ifdef %swig_unordered_multiset_methods // Add swig/language extra methods - %swig_unordered_multiset_methods(std::unordered_multiset<_Key, _Compare, _Alloc >); + %swig_unordered_multiset_methods(std::unordered_multiset< _Key, _Compare, _Alloc >); #endif %std_unordered_multiset_methods(unordered_multiset); diff --git a/Lib/std/std_unordered_set.i b/Lib/std/std_unordered_set.i index ed8888eb4..98e792040 100644 --- a/Lib/std/std_unordered_set.i +++ b/Lib/std/std_unordered_set.i @@ -77,9 +77,9 @@ namespace std { - template , - class _Compare = std::equal_to<_Key>, - class _Alloc = allocator<_Key> > + template , + class _Compare = std::equal_to< _Key >, + class _Alloc = allocator< _Key > > class unordered_set { public: typedef size_t size_type; @@ -95,11 +95,11 @@ namespace std { %traits_swigtype(_Key); - %fragment(SWIG_Traits_frag(std::unordered_set<_Key, _Hash, _Compare, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::unordered_set< _Key, _Hash, _Compare, _Alloc >), "header", fragment=SWIG_Traits_frag(_Key), fragment="StdUnorderedSetTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::unordered_set<" #_Key "," #_Hash "," #_Compare "," #_Alloc " >"; @@ -108,13 +108,13 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_SET, std::unordered_set<_Key, _Hash, _Compare, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_SET, std::unordered_set< _Key, _Hash, _Compare, _Alloc >); unordered_set( const _Compare& ); #ifdef %swig_unordered_set_methods // Add swig/language extra methods - %swig_unordered_set_methods(std::unordered_set<_Key, _Hash, _Compare, _Alloc >); + %swig_unordered_set_methods(std::unordered_set< _Key, _Hash, _Compare, _Alloc >); #endif %std_unordered_set_methods(unordered_set); diff --git a/Lib/std/std_vector.i b/Lib/std/std_vector.i index baecf8507..fae759a36 100644 --- a/Lib/std/std_vector.i +++ b/Lib/std/std_vector.i @@ -71,11 +71,11 @@ namespace std { %traits_swigtype(_Tp); %traits_enum(_Tp); - %fragment(SWIG_Traits_frag(std::vector<_Tp, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::vector< _Tp, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdVectorTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::vector<" #_Tp "," #_Alloc " >"; @@ -84,11 +84,11 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector< _Tp, _Alloc >); #ifdef %swig_vector_methods // Add swig/language extra methods - %swig_vector_methods(std::vector<_Tp, _Alloc >); + %swig_vector_methods(std::vector< _Tp, _Alloc >); #endif %std_vector_methods(vector); @@ -99,7 +99,7 @@ namespace std { // a 'const SWIGTYPE*&' can be defined // *** template - class vector<_Tp*, _Alloc > { + class vector< _Tp*, _Alloc > { public: typedef size_t size_type; typedef ptrdiff_t difference_type; @@ -112,11 +112,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::vector<_Tp*, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::vector< _Tp*, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdVectorTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::vector<" #_Tp " *," #_Alloc " >"; @@ -125,11 +125,11 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp*, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector< _Tp*, _Alloc >); #ifdef %swig_vector_methods_val // Add swig/language extra methods - %swig_vector_methods_val(std::vector<_Tp*, _Alloc >); + %swig_vector_methods_val(std::vector< _Tp*, _Alloc >); #endif %std_vector_methods_val(vector); @@ -139,7 +139,7 @@ namespace std { // const pointer specialization // *** template - class vector<_Tp const *, _Alloc > { + class vector< _Tp const *, _Alloc > { public: typedef size_t size_type; typedef ptrdiff_t difference_type; @@ -152,11 +152,11 @@ namespace std { %traits_swigtype(_Tp); - %fragment(SWIG_Traits_frag(std::vector<_Tp const*, _Alloc >), "header", + %fragment(SWIG_Traits_frag(std::vector< _Tp const*, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdVectorTraits") { namespace swig { - template <> struct traits > { + template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::vector<" #_Tp " const*," #_Alloc " >"; @@ -165,11 +165,11 @@ namespace std { } } - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp const*, _Alloc >); + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector< _Tp const*, _Alloc >); #ifdef %swig_vector_methods_val // Add swig/language extra methods - %swig_vector_methods_val(std::vector<_Tp const*, _Alloc >); + %swig_vector_methods_val(std::vector< _Tp const*, _Alloc >); #endif %std_vector_methods_val(vector); diff --git a/Lib/std_except.i b/Lib/std_except.i index a4a7a85ac..50b5a88a2 100644 --- a/Lib/std_except.i +++ b/Lib/std_except.i @@ -24,6 +24,7 @@ #endif %{ +#include #include %} @@ -40,6 +41,7 @@ %enddef namespace std { + %std_exception_map(bad_cast, SWIG_TypeError); %std_exception_map(bad_exception, SWIG_SystemError); %std_exception_map(domain_error, SWIG_ValueError); %std_exception_map(exception, SWIG_SystemError); diff --git a/Lib/swig.swg b/Lib/swig.swg index c33ae3854..6f48f0d20 100644 --- a/Lib/swig.swg +++ b/Lib/swig.swg @@ -359,6 +359,7 @@ static int NAME(TYPE x) { %define SWIG_TYPECHECK_STDSTRING 135 %enddef %define SWIG_TYPECHECK_STRING 140 %enddef %define SWIG_TYPECHECK_PAIR 150 %enddef +%define SWIG_TYPECHECK_STDARRAY 155 %enddef %define SWIG_TYPECHECK_VECTOR 160 %enddef %define SWIG_TYPECHECK_DEQUE 170 %enddef %define SWIG_TYPECHECK_LIST 180 %enddef diff --git a/Lib/swiglabels.swg b/Lib/swiglabels.swg index e73e63a57..b3855665e 100644 --- a/Lib/swiglabels.swg +++ b/Lib/swiglabels.swg @@ -65,9 +65,11 @@ #endif /* exporting methods */ -#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -# ifndef GCC_HASCLASSVISIBILITY -# define GCC_HASCLASSVISIBILITY +#if defined(__GNUC__) +# if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) +# ifndef GCC_HASCLASSVISIBILITY +# define GCC_HASCLASSVISIBILITY +# endif # endif #endif diff --git a/Lib/swigrun.swg b/Lib/swigrun.swg index a314bf239..1ef676187 100644 --- a/Lib/swigrun.swg +++ b/Lib/swigrun.swg @@ -495,16 +495,16 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { char d = *(c++); unsigned char uu; if ((d >= '0') && (d <= '9')) - uu = ((d - '0') << 4); + uu = (unsigned char)((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); + uu = (unsigned char)((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) - uu |= (d - '0'); + uu |= (unsigned char)(d - '0'); else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); + uu |= (unsigned char)(d - ('a'-10)); else return (char *) 0; *u = uu; diff --git a/Lib/tcl/tclprimtypes.swg b/Lib/tcl/tclprimtypes.swg index e781798e0..3b6d04f59 100644 --- a/Lib/tcl/tclprimtypes.swg +++ b/Lib/tcl/tclprimtypes.swg @@ -112,8 +112,9 @@ SWIG_AsVal_dec(unsigned long)(Tcl_Obj *obj, unsigned long *val) { %fragment(SWIG_From_frag(long long),"header", fragment=SWIG_From_frag(long), - fragment="", + fragment="SWIG_LongLongAvailable", fragment="") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE Tcl_Obj* SWIG_From_dec(long long)(long long value) { @@ -125,11 +126,13 @@ SWIG_From_dec(long long)(long long value) return Tcl_NewStringObj(temp,-1); } } +%#endif } %fragment(SWIG_AsVal_frag(long long),"header", - fragment="", + fragment="SWIG_LongLongAvailable", fragment="") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(long long)(Tcl_Obj *obj, long long *val) { @@ -160,14 +163,16 @@ SWIG_AsVal_dec(long long)(Tcl_Obj *obj, long long *val) } return SWIG_TypeError; } +%#endif } /* unsigned long long */ %fragment(SWIG_From_frag(unsigned long long),"header", fragment=SWIG_From_frag(long long), - fragment="", + fragment="SWIG_LongLongAvailable", fragment="") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERNINLINE Tcl_Obj* SWIG_From_dec(unsigned long long)(unsigned long long value) { @@ -179,12 +184,14 @@ SWIG_From_dec(unsigned long long)(unsigned long long value) return Tcl_NewStringObj(temp,-1); } } +%#endif } %fragment(SWIG_AsVal_frag(unsigned long long),"header", fragment=SWIG_AsVal_frag(unsigned long), - fragment="", + fragment="SWIG_LongLongAvailable", fragment="") { +%#ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(Tcl_Obj *obj, unsigned long long *val) { @@ -216,6 +223,7 @@ SWIG_AsVal_dec(unsigned long long)(Tcl_Obj *obj, unsigned long long *val) } return SWIG_TypeError; } +%#endif } /* double */ diff --git a/Lib/tcl/tclrun.swg b/Lib/tcl/tclrun.swg index c91a7e511..fd1052a28 100644 --- a/Lib/tcl/tclrun.swg +++ b/Lib/tcl/tclrun.swg @@ -67,6 +67,12 @@ #define SWIG_GetConstant SWIG_GetConstantObj #define SWIG_Tcl_GetConstant SWIG_Tcl_GetConstantObj +#if TCL_MAJOR_VERSION >= 8 && TCL_MINOR_VERSION >= 5 +#define SWIG_TCL_HASHTABLE_INIT {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#else +#define SWIG_TCL_HASHTABLE_INIT {0} +#endif + #include "assert.h" #ifdef __cplusplus diff --git a/Lib/typemaps/cstrings.swg b/Lib/typemaps/cstrings.swg index 7fe6a3f8f..0aca61101 100644 --- a/Lib/typemaps/cstrings.swg +++ b/Lib/typemaps/cstrings.swg @@ -203,7 +203,7 @@ * This macro is used to return Character data along with a size * parameter. * - * %cstring_output_maxsize(Char *outx, int *max) { + * %cstring_output_withsize(Char *outx, int *max) { * void foo(Char *outx, int *max) { * sprintf(outx,"blah blah\n"); * *max = strlen(outx); @@ -236,7 +236,7 @@ * This macro is used to return Character data that was * allocated with new or malloc. * - * %cstring_output_allocated(Char **outx, free($1)); + * %cstring_output_allocate(Char **outx, free($1)); * void foo(Char **outx) { * *outx = (Char *) malloc(512); * sprintf(outx,"blah blah\n"); @@ -263,7 +263,7 @@ * This macro is used to return Character data that was * allocated with new or malloc. * - * %cstring_output_allocated(Char **outx, int *sz, free($1)); + * %cstring_output_allocate_size(Char **outx, int *sz, free($1)); * void foo(Char **outx, int *sz) { * *outx = (Char *) malloc(512); * sprintf(outx,"blah blah\n"); diff --git a/Lib/typemaps/fragments.swg b/Lib/typemaps/fragments.swg index 447df6e2e..048fd34d3 100644 --- a/Lib/typemaps/fragments.swg +++ b/Lib/typemaps/fragments.swg @@ -168,8 +168,11 @@ %fragment("SWIG_isfinite","header",fragment=",") %{ /* Getting isfinite working pre C99 across multiple platforms is non-trivial. Users can provide SWIG_isfinite on older platforms. */ #ifndef SWIG_isfinite +/* isfinite() is a macro for C99, but a function in namespace std for C++11. */ # if defined(isfinite) # define SWIG_isfinite(X) (isfinite(X)) +# elif defined __cplusplus && __cplusplus >= 201103L +# define SWIG_isfinite(X) (std::isfinite(X)) # elif defined(_MSC_VER) # define SWIG_isfinite(X) (_finite(X)) # elif defined(__sun) && defined(__SVR4) diff --git a/Lib/typemaps/implicit.swg b/Lib/typemaps/implicit.swg index 702fb52b8..2fc3108e7 100644 --- a/Lib/typemaps/implicit.swg +++ b/Lib/typemaps/implicit.swg @@ -73,8 +73,8 @@ namespace swig { typedef Type value_type; static int asptr(SWIG_Object obj, value_type **val) { Type *vptr; - static swig_type_info* desc = SWIG_TypeQuery("Type *"); - int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0); + static swig_type_info* descriptor = SWIG_TypeQuery("Type *"); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&vptr, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = vptr; return res; @@ -109,8 +109,8 @@ namespace swig { typedef Type value_type; static int asptr(SWIG_Object obj, value_type **val) { Type *vptr; - static swig_type_info* desc = SWIG_TypeQuery("Type *"); - int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0); + static swig_type_info* descriptor = SWIG_TypeQuery("Type *"); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&vptr, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = vptr; return res; @@ -147,8 +147,8 @@ namespace swig { typedef Type value_type; static int asptr(SWIG_Object obj, value_type **val) { Type *vptr; - static swig_type_info* desc = SWIG_TypeQuery("Type *"); - int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0); + static swig_type_info* descriptor = SWIG_TypeQuery("Type *"); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&vptr, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = vptr; return SWIG_OLDOBJ; @@ -188,8 +188,8 @@ namespace swig { typedef Type value_type; static int asptr(SWIG_Object obj, value_type **val) { Type *vptr; - static swig_type_info* desc = SWIG_TypeQuery("Type *"); - int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0); + static swig_type_info* descriptor = SWIG_TypeQuery("Type *"); + int res = descriptor ? SWIG_ConvertPtr(obj, (void **)&vptr, descriptor, 0) : SWIG_ERROR; if (SWIG_IsOK(res)) { if (val) *val = vptr; return res; diff --git a/Lib/typemaps/primtypes.swg b/Lib/typemaps/primtypes.swg index 45632c31f..dd80eb775 100644 --- a/Lib/typemaps/primtypes.swg +++ b/Lib/typemaps/primtypes.swg @@ -148,6 +148,12 @@ SWIG_AsVal_dec(bool)(SWIG_Object obj, bool *val) /* long long/unsigned long long */ +%fragment("SWIG_LongLongAvailable","header", fragment="") %{ +#if defined(LLONG_MAX) && !defined(SWIG_LONG_LONG_AVAILABLE) +# define SWIG_LONG_LONG_AVAILABLE +#endif +%} + %ensure_type_fragments(long long) %ensure_type_fragments(unsigned long long) @@ -157,42 +163,82 @@ SWIG_AsVal_dec(bool)(SWIG_Object obj, bool *val) /* size_t */ -%fragment(SWIG_From_frag(size_t),"header",fragment=SWIG_From_frag(unsigned long)) { +%fragment(SWIG_From_frag(size_t),"header",fragment=SWIG_From_frag(unsigned long),fragment=SWIG_From_frag(unsigned long long)) { SWIGINTERNINLINE SWIG_Object SWIG_From_dec(size_t)(size_t value) { - return SWIG_From(unsigned long)(%numeric_cast(value, unsigned long)); +%#ifdef SWIG_LONG_LONG_AVAILABLE + if (sizeof(size_t) <= sizeof(unsigned long)) { +%#endif + return SWIG_From(unsigned long)(%numeric_cast(value, unsigned long)); +%#ifdef SWIG_LONG_LONG_AVAILABLE + } else { + /* assume sizeof(size_t) <= sizeof(unsigned long long) */ + return SWIG_From(unsigned long long)(%numeric_cast(value, unsigned long long)); + } +%#endif } } -%fragment(SWIG_AsVal_frag(size_t),"header",fragment=SWIG_AsVal_frag(unsigned long)) { +%fragment(SWIG_AsVal_frag(size_t),"header",fragment=SWIG_AsVal_frag(unsigned long),fragment=SWIG_AsVal_frag(unsigned long long)) { SWIGINTERNINLINE int SWIG_AsVal_dec(size_t)(SWIG_Object obj, size_t *val) { - unsigned long v; - int res = SWIG_AsVal(unsigned long)(obj, val ? &v : 0); - if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, size_t); + int res = SWIG_TypeError; +%#ifdef SWIG_LONG_LONG_AVAILABLE + if (sizeof(size_t) <= sizeof(unsigned long)) { +%#endif + unsigned long v; + res = SWIG_AsVal(unsigned long)(obj, val ? &v : 0); + if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, size_t); +%#ifdef SWIG_LONG_LONG_AVAILABLE + } else if (sizeof(size_t) <= sizeof(unsigned long long)) { + unsigned long long v; + res = SWIG_AsVal(unsigned long long)(obj, val ? &v : 0); + if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, size_t); + } +%#endif return res; } } /* ptrdiff_t */ -%fragment(SWIG_From_frag(ptrdiff_t),"header",fragment=SWIG_From_frag(long)) { +%fragment(SWIG_From_frag(ptrdiff_t),"header",fragment=SWIG_From_frag(long),fragment=SWIG_From_frag(long long)) { SWIGINTERNINLINE SWIG_Object SWIG_From_dec(ptrdiff_t)(ptrdiff_t value) { - return SWIG_From(long)(%numeric_cast(value,long)); +%#ifdef SWIG_LONG_LONG_AVAILABLE + if (sizeof(ptrdiff_t) <= sizeof(long)) { +%#endif + return SWIG_From(long)(%numeric_cast(value, long)); +%#ifdef SWIG_LONG_LONG_AVAILABLE + } else { + /* assume sizeof(ptrdiff_t) <= sizeof(long long) */ + return SWIG_From(long long)(%numeric_cast(value, long long)); + } +%#endif } } -%fragment(SWIG_AsVal_frag(ptrdiff_t),"header",fragment=SWIG_AsVal_frag(long)) { +%fragment(SWIG_AsVal_frag(ptrdiff_t),"header",fragment=SWIG_AsVal_frag(long),fragment=SWIG_AsVal_frag(long long)) { SWIGINTERNINLINE int SWIG_AsVal_dec(ptrdiff_t)(SWIG_Object obj, ptrdiff_t *val) { - long v; - int res = SWIG_AsVal(long)(obj, val ? &v : 0); - if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, ptrdiff_t); + int res = SWIG_TypeError; +%#ifdef SWIG_LONG_LONG_AVAILABLE + if (sizeof(ptrdiff_t) <= sizeof(long)) { +%#endif + long v; + res = SWIG_AsVal(long)(obj, val ? &v : 0); + if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, ptrdiff_t); +%#ifdef SWIG_LONG_LONG_AVAILABLE + } else if (sizeof(ptrdiff_t) <= sizeof(long long)) { + long long v; + res = SWIG_AsVal(long long)(obj, val ? &v : 0); + if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, ptrdiff_t); + } +%#endif return res; } } diff --git a/Lib/typemaps/std_except.swg b/Lib/typemaps/std_except.swg index cb5ed3050..75d066490 100644 --- a/Lib/typemaps/std_except.swg +++ b/Lib/typemaps/std_except.swg @@ -20,6 +20,7 @@ %enddef namespace std { + %std_exception_map(bad_cast, SWIG_TypeError); %std_exception_map(bad_exception, SWIG_SystemError); %std_exception_map(domain_error, SWIG_ValueError); %std_exception_map(exception, SWIG_SystemError); diff --git a/Lib/typemaps/swigtype.swg b/Lib/typemaps/swigtype.swg index e8124df9c..d3633eb49 100644 --- a/Lib/typemaps/swigtype.swg +++ b/Lib/typemaps/swigtype.swg @@ -415,7 +415,7 @@ } %typemap(directorin,noblock=1) SWIGTYPE { - $input = SWIG_NewPointerObj(%as_voidptr(&$1), $&descriptor, %newpointer_flags); + $input = SWIG_NewPointerObj(%as_voidptr(new $1_ltype((const $1_ltype &)$1)), $&descriptor, SWIG_POINTER_OWN | %newpointer_flags); } %typemap(directorin,noblock=1) SWIGTYPE & { @@ -625,6 +625,7 @@ %typemap(constcode, noblock=1) SWIGTYPE ((*)(ANY)){ %set_constant("$symname", SWIG_NewFunctionPtrObj((void *)$value, $descriptor)); } +%typemap(constcode) SWIGTYPE ((* const)(ANY)) = SWIGTYPE ((*)(ANY)); #if defined(SWIG_DIRECTOR_TYPEMAPS) diff --git a/Lib/typemaps/traits.swg b/Lib/typemaps/traits.swg deleted file mode 100644 index 406f16066..000000000 --- a/Lib/typemaps/traits.swg +++ /dev/null @@ -1,305 +0,0 @@ -// -// Use the following macro with modern STL implementations -// -//#define SWIG_STD_MODERN_STL -// -// Use this to deactive the previous definition, when using gcc-2.95 -// or similar old compilers. -// -//#define SWIG_STD_NOMODERN_STL - -// Here, we identify compilers we now have problems with STL. -%{ -#if defined(__GNUC__) -# if __GNUC__ == 2 && __GNUC_MINOR <= 96 -# define SWIG_STD_NOMODERN_STL -# endif -#endif -%} - -// -// Common code for supporting the STD C++ namespace -// - -%fragment(""); -%fragment(""); - -%fragment("Traits","header",fragment="") -{ -namespace swig { - /* - type categories - */ - struct pointer_category { }; - struct value_category { }; - - /* - General traits that provides type_name and type_info - */ - template struct traits { }; - - template - inline const char* type_name() { - return traits::type_name(); - } - - template - struct traits_info { - static swig_type_info *type_query(std::string name) { - name += " *"; - return SWIG_TypeQuery(name.c_str()); - } - static swig_type_info *type_info() { - static swig_type_info *info = type_query(type_name()); - return info; - } - }; - - template - inline swig_type_info *type_info() { - return traits_info::type_info(); - } - - /* - Partial specialization for pointers - */ - template struct traits { - typedef pointer_category category; - static std::string make_ptr_name(const char* name) { - std::string ptrname = name; - ptrname += " *"; - return ptrname; - } - static const char* type_name() { - static std::string name = make_ptr_name(swig::type_name()); - return name.c_str(); - } - }; - - - template ::category > - struct traits_check { }; - - /* - Traits that provides the from method for an unknown type - */ - template struct traits_from_ptr { - static SWIG_Object from SWIG_FROM_DECL_ARGS(Type *val) { - return SWIG_NewPointerObj(val, type_info(), flags); - } - }; - - template struct traits_from { - static SWIG_Object from SWIG_FROM_DECL_ARGS(const Type& val) { - return traits_from_ptr::from(new Type(val)); - } - }; - - template struct traits_from { - static SWIG_Object from SWIG_FROM_DECL_ARGS(Type* val) { - return traits_from_ptr<0, Type>::from(val); - } - }; - - template - inline SWIG_Object from SWIG_FROM_DECL_ARGS(const Type& val) { - return traits_from::from(val); - } - - /* - Traits that provides the asptr/asval method for an unknown type - */ - template - struct traits_asptr { - static int asptr SWIG_AS_DECL_ARGS (SWIG_Object obj, Type **val) { - Type *p; - int res = SWIG_ConvertPtr(obj, %as_voidptrptr(&p), type_info(), 0); - if (SWIG_IsOK(res) && val) *val = p; - return res; - } - }; - - template - inline int asptr SWIG_AS_DECL_ARGS(SWIG_Object obj, Type **vptr) { - return traits_asptr::asptr SWIG_AS_CALL_ARGS(obj, vptr); - } - - template - struct traits_asval { - static int asval SWIG_AS_DECL_ARGS(SWIG_Object obj, Type *val) { - if (val) { - Type *p = 0; - int res = traits_asptr::asptr SWIG_AS_CALL_ARGS(obj, &p); - if (SWIG_IsOK(res) && p) { - *val = *p; - if (SWIG_IsNewObj(res)) { - %delete(p); - res = SWIG_DelNewMask(res); - } - } - return res; - } else { - return traits_asptr::asptr SWIG_AS_CALL_ARGS(obj, (Type **)(0)); - } - } - }; - - template - inline int asval SWIG_AS_DECL_ARGS (SWIG_Object obj, Type *val) { - return traits_asval::asval SWIG_AS_CALL_ARGS(obj, val); - } - - /* - Traits that provides the check method for an unknown type - */ -#define SWIG_CHECK_DECL_ARGS(obj) SWIG_AS_DECL_ARGS(obj, void * = 0) -#define SWIG_CHECK_CALL_ARGS(obj) SWIG_AS_CALL_ARGS(obj, 0) - - template - struct traits_checkval { - static int check SWIG_CHECK_DECL_ARGS(SWIG_Object obj) { - if (obj) { - int res = asval SWIG_AS_CALL_ARGS(obj, (Type *)(0)); - return SWIG_CheckState(res); - } else { - return 0; - } - } - }; - - template - struct traits_checkptr { - static int check SWIG_CHECK_DECL_ARGS(SWIG_Object obj) { - if (obj) { - int res = asptr SWIG_AS_CALL_ARGS(obj, (Type **)(0)); - return SWIG_CheckState(res); - } else { - return 0; - } - } - }; - - template - struct traits_check : traits_checkval { - }; - - template - struct traits_check : traits_checkptr { - }; - - template - inline int check SWIG_CHECK_DECL_ARGS(SWIG_Object obj) { - return traits_check::check SWIG_CHECK_CALL_ARGS(obj); - } - -} -} - -/* - Generate the traits for an unknown SWIGTYPE -*/ - -%define %traits_swigtype(Type...) -%fragment(SWIG_Traits_frag(Type),"header",fragment="Traits") { - namespace swig { - template <> struct traits { - typedef pointer_category category; - static const char* type_name() { return #Type; } - }; - } -} -%enddef - - -/* - Generate the traits for a 'value' type, such as 'double', - for which the SWIG_AsVal and SWIG_From methods are already defined. -*/ - -%define %traits_value(Type...) -%fragment(SWIG_Traits_frag(Type),"header", - fragment=SWIG_AsVal_frag(Type), - fragment=SWIG_From_frag(Type), - fragment="Traits") { -namespace swig { - template <> struct traits { - typedef value_category category; - static const char* type_name() { return #Type; } - }; - - template <> struct traits_asval { - typedef Type value_type; - static int asval SWIG_AS_DECL_ARGS (SWIG_Object obj, value_type *val) { - return SWIG_AsVal(Type)(obj, val); - } - }; - - template <> struct traits_from { - typedef Type value_type; - static SWIG_Object from SWIG_FROM_DECL_ARGS (const value_type& val) { - return SWIG_From(Type)(val); - } - }; -} -} -%enddef - -/* - Generate the traits for a 'pointer' type, such as 'std::string', - for which the SWIG_AsPtr and SWIG_From methods are already defined. -*/ - -%define %traits_pointer(Type...) -%fragment(SWIG_Traits_frag(Type),"header", - fragment=SWIG_AsVal_frag(Type), - fragment=SWIG_From_frag(Type), - fragment="Traits") { -namespace swig { - template <> struct traits { - typedef pointer_category category; - static const char* type_name() { return #Type; } - }; - - template <> struct traits_asptr { - typedef Type value_type; - static int asptr SWIG_AS_DECL_ARGS (SWIG_Object obj, value_type **val) { - return SWIG_AsPtr(Type)(obj, val); - } - }; - - template <> struct traits_from { - typedef Type value_type; - static SWIG_Object from SWIG_FROM_DECL_ARGS (const value_type& val) { - return SWIG_From(Type)(val); - } - }; -} -} -%enddef - -/* - Generate the typemaps for a class that has 'value' traits -*/ - -%define %typemap_traits_value(Code,Type...) - %typemaps_asvalfrom(%arg(Code), - %arg(swig::asval), - %arg(swig::from), - %arg(SWIG_Traits_frag(Type)), - %arg(SWIG_Traits_frag(Type)), - Type); -%enddef - -/* - Generate the typemaps for a class that has 'pointer' traits -*/ - -%define %typemap_traits_pointer(Code,Type...) - %typemaps_asptrfrom(%arg(Code), - %arg(swig::asptr), - %arg(swig::from), - %arg(SWIG_Traits_frag(Type)), - %arg(SWIG_Traits_frag(Type)), - Type); -%enddef - diff --git a/Makefile.in b/Makefile.in index e8e08a994..df882ce34 100644 --- a/Makefile.in +++ b/Makefile.in @@ -21,7 +21,7 @@ FLAGS = -k -s ##################################################################### SHELL = /bin/sh -SWIG_LIB = @swig_lib@ +SWIG_LIB_INSTALL = @SWIG_LIB_INSTALL@ BIN_DIR = @bindir@ ENABLE_CCACHE = @ENABLE_CCACHE@ TARGET_NOEXE= swig @@ -49,15 +49,12 @@ maintainer: libfiles # Documentation ##################################################################### -docs: docs-main docs-ccache +docs: docs-main docs-main: @echo making docs @test -d $(DOCS) || exit 0; cd $(DOCS) && $(MAKE) all clean-baks -docs-ccache: - test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) docs) - ##################################################################### # All the languages SWIG speaks (when it wants to) ##################################################################### @@ -70,6 +67,7 @@ skip-guile = test -n "@SKIP_GUILE@" skip-mzscheme = test -n "@SKIP_MZSCHEME@" skip-ruby = test -n "@SKIP_RUBY@" skip-php = test -n "@SKIP_PHP@" +skip-php5 = test -n "@SKIP_PHP5@" skip-ocaml = test -n "@SKIP_OCAML@" skip-octave = test -n "@SKIP_OCTAVE@" skip-pike = test -n "@SKIP_PIKE@" @@ -94,6 +92,12 @@ skip-android = test -n "@SKIP_ANDROID@" # Special errors test-case skip-errors = test -n "" +check-%-enabled: + @if $(skip-$*); then \ + echo skipping $* version; \ + exit 1; \ + fi + ##################################################################### # CHECK ##################################################################### @@ -101,10 +105,6 @@ skip-errors = test -n "" ACTION = check NOSKIP = -chk-set-swiglib = SWIG_LIB=@ROOT_DIR@/$(srcdir)/Lib -chk-set-swig = SWIG=@ROOT_DIR@/$(TARGET) -chk-set-env = $(chk-set-swiglib) $(chk-set-swig) - check-aliveness: test -x ./$(TARGET) ./$(TARGET) -version @@ -118,7 +118,8 @@ check-aliveness: @$(skip-ruby) || ./$(TARGET) -ruby -help @$(skip-ocaml) || ./$(TARGET) -ocaml -help @$(skip-octave) || ./$(TARGET) -octave -help - @$(skip-php) || ./$(TARGET) -php -help + @$(skip-php) || ./$(TARGET) -php7 -help + @$(skip-php5) || ./$(TARGET) -php5 -help @$(skip-pike) || ./$(TARGET) -pike -help @$(skip-chicken) || ./$(TARGET) -chicken -help @$(skip-csharp) || ./$(TARGET) -csharp -help @@ -151,6 +152,7 @@ check-versions: \ check-ocaml-version \ check-octave-version \ check-php-version \ + check-php5-version \ check-pike-version \ check-chicken-version \ check-csharp-version \ @@ -191,6 +193,7 @@ check-examples: \ check-ocaml-examples \ check-octave-examples \ check-php-examples \ + check-php5-examples \ check-pike-examples \ check-chicken-examples \ check-csharp-examples \ @@ -217,6 +220,7 @@ ruby_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/ruby/check.list) ocaml_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/ocaml/check.list) octave_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/octave/check.list) php_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/php/check.list) +php5_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/php5/check.list) pike_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/pike/check.list) chicken_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/chicken/check.list) csharp_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/csharp/check.list) @@ -250,7 +254,7 @@ check-%-examples : %.actionexample: @cd Examples && $(MAKE) Makefile @echo $(ACTION)ing Examples/$(LANGUAGE)/$* - @(cd Examples/$(LANGUAGE)/$* && $(MAKE) $(FLAGS) $(chk-set-env) $(ACTION) RUNPIPE=$(RUNPIPE)) + @(cd Examples/$(LANGUAGE)/$* && $(MAKE) $(FLAGS) $(ACTION) RUNPIPE=$(RUNPIPE)) # gcj individual example java.actionexample: @@ -259,7 +263,7 @@ java.actionexample: echo "skipping Examples/$(LANGUAGE)/java $(ACTION) (gcj test)"; \ else \ echo $(ACTION)ing Examples/$(LANGUAGE)/java; \ - (cd Examples/$(LANGUAGE)/java && $(MAKE) $(FLAGS) $(chk-set-env) $(ACTION) RUNPIPE=$(RUNPIPE)) \ + (cd Examples/$(LANGUAGE)/java && $(MAKE) $(FLAGS) $(ACTION) RUNPIPE=$(RUNPIPE)) \ fi # Checks testcases in the test-suite excluding those which are known to be broken @@ -275,6 +279,7 @@ check-test-suite: \ check-ocaml-test-suite \ check-octave-test-suite \ check-php-test-suite \ + check-php5-test-suite \ check-pike-test-suite \ check-csharp-test-suite \ check-modula3-test-suite \ @@ -329,6 +334,7 @@ all-test-suite: \ all-ocaml-test-suite \ all-octave-test-suite \ all-php-test-suite \ + all-php5-test-suite \ all-pike-test-suite \ all-csharp-test-suite \ all-modula3-test-suite \ @@ -359,6 +365,7 @@ broken-test-suite: \ broken-ocaml-test-suite \ broken-octave-test-suite \ broken-php-test-suite \ + broken-php5-test-suite \ broken-pike-test-suite \ broken-csharp-test-suite \ broken-modula3-test-suite \ @@ -503,7 +510,7 @@ install-main: @echo "Installing $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@" @$(INSTALL_PROGRAM) $(TARGET) $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@ -lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php ocaml octave \ +lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php php5 ocaml octave \ pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc \ javascript/v8 scilab @@ -512,16 +519,16 @@ lib-modules = std install-lib: @echo "Installing the SWIG library" - @$(MKINSTDIRS) $(DESTDIR)$(SWIG_LIB) + @$(MKINSTDIRS) $(DESTDIR)$(SWIG_LIB_INSTALL) @for file in $(srcdir)/Lib/*.i $(srcdir)/Lib/*.swg ; do \ i=`basename $$file` ; \ - echo "Installing $(DESTDIR)$(SWIG_LIB)/$$i"; \ - $(INSTALL_DATA) $$file $(DESTDIR)$(SWIG_LIB)/$$i; \ + echo "Installing $(DESTDIR)$(SWIG_LIB_INSTALL)/$$i"; \ + $(INSTALL_DATA) $$file $(DESTDIR)$(SWIG_LIB_INSTALL)/$$i; \ done; @for lang in $(lib-languages) $(lib-modules); \ do \ echo "Installing language specific files for $$lang"; \ - dst=$(DESTDIR)$(SWIG_LIB)/$$lang; \ + dst=$(DESTDIR)$(SWIG_LIB_INSTALL)/$$lang; \ $(MKINSTDIRS) $$dst; \ (doti="`cd $(srcdir)/Lib/$$lang && ls *.i 2>/dev/null || echo ''`"; \ dotswg="`cd $(srcdir)/Lib/$$lang && ls *.swg 2>/dev/null || echo ''`"; \ @@ -556,7 +563,7 @@ uninstall-main: uninstall-lib: @echo "Uninstalling the SWIG library" - rm -rf $(DESTDIR)$(SWIG_LIB)/ + rm -rf $(DESTDIR)$(SWIG_LIB_INSTALL)/ uninstall-ccache: test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) uninstall) diff --git a/README b/README index a02c56ea9..3421b72bf 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 3.0.7 (in progress) +Version: 3.0.11 (in progress) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, C#, D, Go, Lua, @@ -68,9 +68,13 @@ than one version of SWIG. Installation ============ Please read the Doc/Manual/Preface.html#Preface_installation for -full installation instructions for Windows, Unix and Mac OS X. -The INSTALL file has generic build and installation instructions for -Unix users. +full installation instructions for Windows, Unix and Mac OS X +using the release tarball/zip file. The INSTALL file has generic +build and installation instructions for Unix users. +Users wishing to build and install code from Github should +visit http://swig.org/svn.html to obtain the more detailed +instructions required for building code obtained from Github - extra +steps are required compared to building from the release tarball. Testing ======= diff --git a/RELEASENOTES b/RELEASENOTES index bb1d82bb9..080bb6066 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -4,6 +4,32 @@ and CHANGES files. 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. + +SWIG-3.0.10 summary: +- Regression fixes for smart pointers and importing Python modules. + +SWIG-3.0.9 summary: +- Add support for Python's implicit namespace packages. +- Fixes to support Go 1.6. +- C++11 std::array support added for Java. +- Improved C++ multiple inheritance support for Java/C# wrappers. +- Various other minor fixes and improvements for C#, D, Go, Java, + Javascript, Lua, Python, R, Ruby, Scilab. + +SWIG-3.0.8 summary: +- pdf documentation enhancements. +- Various Python 3.5 issues fixed. +- std::array support added for Ruby and Python. +- shared_ptr support added for Ruby. +- Minor improvements for CFFI, Go, Java, Perl, Python, Ruby. + +SWIG-3.0.7 summary: +- Add support for Octave-4.0.0. +- Remove potential Android security exploit in generated Java classes. +- Minor new features and bug fixes. + SWIG-3.0.6 summary: - Stability and regression fixes. - Fixed parsing of C++ corner cases. diff --git a/Source/CParse/cparse.h b/Source/CParse/cparse.h index 0681c65dd..ed0cfdb38 100644 --- a/Source/CParse/cparse.h +++ b/Source/CParse/cparse.h @@ -58,6 +58,7 @@ extern "C" { /* util.c */ extern void Swig_cparse_replace_descriptor(String *s); + extern SwigType *Swig_cparse_smartptr(Node *n); extern void cparse_normalize_void(Node *); extern Parm *Swig_cparse_parm(String *s); extern ParmList *Swig_cparse_parms(String *s, Node *file_line_node); @@ -77,4 +78,7 @@ extern "C" { #define SWIG_WARN_NODE_END(Node) \ if (wrnfilter) Swig_warnfilter(wrnfilter,0); \ } + +#define COMPOUND_EXPR_VAL(dtype) \ + ((dtype).type == T_CHAR || (dtype).type == T_WCHAR ? (dtype).rawval : (dtype).val) #endif diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 8ef9af198..60f6599f7 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -13,11 +13,14 @@ * some point. Beware. * ----------------------------------------------------------------------------- */ -/* -Removed until we know more about the min versions of Bison and Yacc required for this -to work, see Byacc man page: http://invisible-island.net/byacc/manpage/yacc.html +/* There are 6 known shift-reduce conflicts in this file, fail compilation if any + more are introduced. + + Please don't increase the number of the conflicts if at all possible. And if + you really have no choice but to do it, make sure you clearly document each + new conflict in this file. + */ %expect 6 -*/ %{ #define yylex yylex @@ -160,6 +163,11 @@ static Node *copy_node(Node *n) { Setattr(nn, key, k.item); continue; } + /* defaultargs will be patched back in later in update_defaultargs() */ + if (strcmp(ckey,"defaultargs") == 0) { + Setattr(nn, "needs_defaultargs", "1"); + continue; + } /* Looks okay. Just copy the data using Copy */ ci = Copy(k.item); Setattr(nn, key, ci); @@ -511,18 +519,24 @@ static void add_symbols(Node *n) { SetFlag(n,"feature:ignore"); } } - if (only_csymbol || GetFlag(n,"feature:ignore")) { + if (only_csymbol || GetFlag(n,"feature:ignore") || strncmp(Char(symname),"$ignore",7) == 0) { /* Only add to C symbol table and continue */ Swig_symbol_add(0, n); - } else if (strncmp(Char(symname),"$ignore",7) == 0) { - char *c = Char(symname)+7; - SetFlag(n,"feature:ignore"); - if (strlen(c)) { - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(0,Getfile(n), Getline(n), "%s\n",c+1); - SWIG_WARN_NODE_END(n); + if (!only_csymbol && !GetFlag(n, "feature:ignore")) { + /* Print the warning attached to $ignore name, if any */ + char *c = Char(symname) + 7; + if (strlen(c)) { + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(0,Getfile(n), Getline(n), "%s\n",c+1); + SWIG_WARN_NODE_END(n); + } + /* If the symbol was ignored via "rename" and is visible, set also feature:ignore*/ + SetFlag(n, "feature:ignore"); + } + if (!GetFlag(n, "feature:ignore") && Strcmp(symname,"$ignore") == 0) { + /* Add feature:ignore if the symbol was explicitely ignored, regardless of visibility */ + SetFlag(n, "feature:ignore"); } - Swig_symbol_add(0, n); } else { Node *c; if ((wrn) && (Len(wrn))) { @@ -694,6 +708,32 @@ static void add_symbols_copy(Node *n) { } } +/* Add in the "defaultargs" attribute for functions in instantiated templates. + * n should be any instantiated template (class or start of linked list of functions). */ +static void update_defaultargs(Node *n) { + if (n) { + Node *firstdefaultargs = n; + update_defaultargs(firstChild(n)); + n = nextSibling(n); + /* recursively loop through nodes of all types, but all we really need are the overloaded functions */ + while (n) { + update_defaultargs(firstChild(n)); + if (!Getattr(n, "defaultargs")) { + if (Getattr(n, "needs_defaultargs")) { + Setattr(n, "defaultargs", firstdefaultargs); + Delattr(n, "needs_defaultargs"); + } else { + firstdefaultargs = n; + } + } else { + /* Functions added in with %extend (for specialized template classes) will already have default args patched up */ + assert(Getattr(n, "defaultargs") == firstdefaultargs); + } + n = nextSibling(n); + } + } +} + /* Check a set of declarations to see if any are pure-abstract */ static List *pure_abstracts(Node *n) { @@ -2632,6 +2672,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va { Node *nn = n; Node *linklistend = 0; + Node *linkliststart = 0; while (nn) { Node *templnode = 0; if (Strcmp(nodeType(nn),"template") == 0) { @@ -2713,7 +2754,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } templnode = copy_node(nn); - update_nested_classes(templnode); /* update classes nested withing template */ + update_nested_classes(templnode); /* update classes nested within template */ /* We need to set the node name based on name used to instantiate */ Setattr(templnode,"name",tname); Delete(tname); @@ -2787,7 +2828,11 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va Swig_symbol_setscope(csyms); } - /* Merge in %extend methods for this class */ + /* Merge in %extend methods for this class. + This only merges methods within %extend for a template specialized class such as + template class K {}; %extend K { ... } + The copy_node() call above has already added in the generic %extend methods such as + template class K {}; %extend K { ... } */ /* !!! This may be broken. We may have to add the %extend methods at the beginning of the class */ @@ -2830,6 +2875,8 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } /* all the overloaded templated functions are added into a linked list */ + if (!linkliststart) + linkliststart = templnode; if (nscope_inner) { /* non-global namespace */ if (templnode) { @@ -2850,6 +2897,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } nn = Getattr(nn,"sym:nextSibling"); /* repeat for overloaded templated functions. If a templated class there will never be a sibling. */ } + update_defaultargs(linkliststart); } Swig_symbol_setscope(tscope); Delete(Namespaceprefix); @@ -2916,28 +2964,26 @@ c_declaration : c_decl { SWIG_WARN_NODE_END($$); } | USING idcolon EQUAL type plain_declarator SEMI { - $$ = new_node("using"); + /* Convert using statement to a typedef statement */ + $$ = new_node("cdecl"); + Setattr($$,"type",$4); + Setattr($$,"storage","typedef"); Setattr($$,"name",$2); - SwigType_push($4,$5.type); - Setattr($$,"uname",$4); + Setattr($$,"decl",$5.type); + SetFlag($$,"typealias"); add_symbols($$); - SWIG_WARN_NODE_BEGIN($$); - Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line, "The 'using' keyword in type aliasing is not fully supported yet.\n"); - SWIG_WARN_NODE_END($$); - - $$ = 0; /* TODO - ignored for now */ } | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL type plain_declarator SEMI { - $$ = new_node("using"); + /* Convert alias template to a "template" typedef statement */ + $$ = new_node("template"); + Setattr($$,"type",$8); + Setattr($$,"storage","typedef"); Setattr($$,"name",$6); - SwigType_push($8,$9.type); - Setattr($$,"uname",$8); + Setattr($$,"decl",$9.type); + Setattr($$,"templateparms",$3); + Setattr($$,"templatetype","cdecl"); + SetFlag($$,"aliastemplate"); add_symbols($$); - SWIG_WARN_NODE_BEGIN($$); - Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line, "The 'using' keyword in template aliasing is not fully supported yet.\n"); - SWIG_WARN_NODE_END($$); - - $$ = 0; /* TODO - ignored for now */ } ; @@ -2957,6 +3003,14 @@ c_decl : storage_class type declarator initializer c_decl_tail { Setattr($$,"throws",$4.throws); Setattr($$,"throw",$4.throwf); Setattr($$,"noexcept",$4.nexcept); + if ($4.val && $4.type) { + /* store initializer type as it might be different to the declared type */ + SwigType *valuetype = NewSwigType($4.type); + if (Len(valuetype) > 0) + Setattr($$,"valuetype",valuetype); + else + Delete(valuetype); + } if (!$5) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); @@ -2984,8 +3038,8 @@ c_decl : storage_class type declarator initializer c_decl_tail { matches that of the declaration, then we will allow it. Otherwise, delete. */ String *p = Swig_scopename_prefix($3.id); if (p) { - if ((Namespaceprefix && Strcmp(p,Namespaceprefix) == 0) || - (inclass && Strcmp(p,Classprefix) == 0)) { + if ((Namespaceprefix && Strcmp(p, Namespaceprefix) == 0) || + (Classprefix && Strcmp(p, Classprefix) == 0)) { String *lstr = Swig_scopename_last($3.id); Setattr($$,"name",lstr); Delete(lstr); @@ -3040,8 +3094,8 @@ c_decl : storage_class type declarator initializer c_decl_tail { if (Strstr($3.id,"::")) { String *p = Swig_scopename_prefix($3.id); if (p) { - if ((Namespaceprefix && Strcmp(p,Namespaceprefix) == 0) || - (inclass && Strcmp(p,Classprefix) == 0)) { + if ((Namespaceprefix && Strcmp(p, Namespaceprefix) == 0) || + (Classprefix && Strcmp(p, Classprefix) == 0)) { String *lstr = Swig_scopename_last($3.id); Setattr($$,"name",lstr); Delete(lstr); @@ -3677,6 +3731,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); + Classprefix = currentOuterClass ? Getattr(currentOuterClass, "Classprefix") : 0; } /* An unnamed struct, possibly with a typedef */ @@ -3713,7 +3768,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { cparse_start_line = cparse_line; currentOuterClass = $$; inclass = 1; - Classprefix = NewStringEmpty(); + Classprefix = 0; Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); /* save the structure declaration to make a typedef for it later*/ @@ -3726,6 +3781,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { String *name = 0; Node *n; Classprefix = 0; + (void)$5; $$ = currentOuterClass; currentOuterClass = Getattr($$, "nested:outer"); if (!currentOuterClass) @@ -3823,6 +3879,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Delete($$); $$ = $6; /* pass member list to outer class/namespace (instead of self)*/ } + Classprefix = currentOuterClass ? Getattr(currentOuterClass, "Classprefix") : 0; } ; @@ -5871,7 +5928,7 @@ definetype : { /* scanner_check_typedef(); */ } expr { if ($$.type == T_STRING) { $$.rawval = NewStringf("\"%(escape)s\"",$$.val); } else if ($$.type != T_CHAR && $$.type != T_WSTRING && $$.type != T_WCHAR) { - $$.rawval = 0; + $$.rawval = NewStringf("%s", $$.val); } $$.qualifier = 0; $$.bitfield = 0; @@ -6180,81 +6237,81 @@ exprnum : NUM_INT { $$ = $1; } ; exprcompound : expr PLUS expr { - $$.val = NewStringf("%s+%s",$1.val,$3.val); + $$.val = NewStringf("%s+%s", COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr MINUS expr { - $$.val = NewStringf("%s-%s",$1.val,$3.val); + $$.val = NewStringf("%s-%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr STAR expr { - $$.val = NewStringf("%s*%s",$1.val,$3.val); + $$.val = NewStringf("%s*%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr SLASH expr { - $$.val = NewStringf("%s/%s",$1.val,$3.val); + $$.val = NewStringf("%s/%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr MODULO expr { - $$.val = NewStringf("%s%%%s",$1.val,$3.val); + $$.val = NewStringf("%s%%%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr AND expr { - $$.val = NewStringf("%s&%s",$1.val,$3.val); + $$.val = NewStringf("%s&%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr OR expr { - $$.val = NewStringf("%s|%s",$1.val,$3.val); + $$.val = NewStringf("%s|%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr XOR expr { - $$.val = NewStringf("%s^%s",$1.val,$3.val); + $$.val = NewStringf("%s^%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote($1.type,$3.type); } | expr LSHIFT expr { - $$.val = NewStringf("%s << %s",$1.val,$3.val); + $$.val = NewStringf("%s << %s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote_type($1.type); } | expr RSHIFT expr { - $$.val = NewStringf("%s >> %s",$1.val,$3.val); + $$.val = NewStringf("%s >> %s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = promote_type($1.type); } | expr LAND expr { - $$.val = NewStringf("%s&&%s",$1.val,$3.val); + $$.val = NewStringf("%s&&%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } | expr LOR expr { - $$.val = NewStringf("%s||%s",$1.val,$3.val); + $$.val = NewStringf("%s||%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } | expr EQUALTO expr { - $$.val = NewStringf("%s==%s",$1.val,$3.val); + $$.val = NewStringf("%s==%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } | expr NOTEQUALTO expr { - $$.val = NewStringf("%s!=%s",$1.val,$3.val); + $$.val = NewStringf("%s!=%s",COMPOUND_EXPR_VAL($1),COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } /* Sadly this causes 2 reduce-reduce conflicts with templates. FIXME resolve these. | expr GREATERTHAN expr { - $$.val = NewStringf("%s < %s", $1.val, $3.val); + $$.val = NewStringf("%s > %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } | expr LESSTHAN expr { - $$.val = NewStringf("%s > %s", $1.val, $3.val); + $$.val = NewStringf("%s < %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } */ | expr GREATERTHANOREQUALTO expr { - $$.val = NewStringf("%s >= %s", $1.val, $3.val); + $$.val = NewStringf("%s >= %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } | expr LESSTHANOREQUALTO expr { - $$.val = NewStringf("%s <= %s", $1.val, $3.val); + $$.val = NewStringf("%s <= %s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3)); $$.type = cparse_cplusplus ? T_BOOL : T_INT; } | expr QUESTIONMARK expr COLON expr %prec QUESTIONMARK { - $$.val = NewStringf("%s?%s:%s", $1.val, $3.val, $5.val); + $$.val = NewStringf("%s?%s:%s", COMPOUND_EXPR_VAL($1), COMPOUND_EXPR_VAL($3), COMPOUND_EXPR_VAL($5)); /* This may not be exactly right, but is probably good enough * for the purposes of parsing constant expressions. */ $$.type = promote($3.type, $5.type); @@ -6272,7 +6329,7 @@ exprcompound : expr PLUS expr { $$.type = $2.type; } | LNOT expr { - $$.val = NewStringf("!%s",$2.val); + $$.val = NewStringf("!%s",COMPOUND_EXPR_VAL($2)); $$.type = T_INT; } | type LPAREN { diff --git a/Source/CParse/util.c b/Source/CParse/util.c index aab536c52..6bf20efc4 100644 --- a/Source/CParse/util.c +++ b/Source/CParse/util.c @@ -70,6 +70,28 @@ void Swig_cparse_replace_descriptor(String *s) { } } +/* ----------------------------------------------------------------------------- + * Swig_cparse_smartptr() + * + * Parse the type in smartptr feature and convert into a SwigType. + * Error out if the parsing fails as this is like a parser syntax error. + * ----------------------------------------------------------------------------- */ + +SwigType *Swig_cparse_smartptr(Node *n) { + SwigType *smart = 0; + String *smartptr = Getattr(n, "feature:smartptr"); + if (smartptr) { + SwigType *cpt = Swig_cparse_type(smartptr); + if (cpt) { + smart = SwigType_typedef_resolve_all(cpt); + Delete(cpt); + } else { + Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, SwigType_namestr(Getattr(n, "name"))); + } + } + return smart; +} + /* ----------------------------------------------------------------------------- * cparse_normalize_void() * diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index a9acbb2cd..2d90001b2 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -93,8 +93,8 @@ #define WARN_PARSE_EXTEND_NAME 326 #define WARN_CPP11_LAMBDA 340 -#define WARN_CPP11_ALIAS_DECLARATION 341 -#define WARN_CPP11_ALIAS_TEMPLATE 342 +#define WARN_CPP11_ALIAS_DECLARATION 341 /* redundant now */ +#define WARN_CPP11_ALIAS_TEMPLATE 342 /* redundant now */ #define WARN_CPP11_VARIADIC_TEMPLATE 343 #define WARN_IGNORE_OPERATOR_NEW 350 /* new */ @@ -215,9 +215,9 @@ /* Feel free to claim any number in this space that's not currently being used. Just make sure you add an entry here */ -#define WARN_D_TYPEMAP_CTYPE_UNDEF 700 +#define WARN_D_TYPEMAP_CTYPE_UNDEF 700 #define WARN_D_TYPEMAP_IMTYPE_UNDEF 701 -#define WARN_D_TYPEMAP_DTYPE_UNDEF 702 +#define WARN_D_TYPEMAP_DTYPE_UNDEF 702 #define WARN_D_MULTIPLE_INHERITANCE 703 #define WARN_D_TYPEMAP_CLASSMOD_UNDEF 704 #define WARN_D_TYPEMAP_DBODY_UNDEF 705 @@ -264,6 +264,7 @@ #define WARN_JAVA_TYPEMAP_JAVAIN_UNDEF 818 #define WARN_JAVA_TYPEMAP_JAVADIRECTORIN_UNDEF 819 #define WARN_JAVA_TYPEMAP_JAVADIRECTOROUT_UNDEF 820 +#define WARN_JAVA_TYPEMAP_INTERFACECODE_UNDEF 821 #define WARN_JAVA_COVARIANT_RET 822 #define WARN_JAVA_TYPEMAP_JAVACONSTRUCT_UNDEF 823 #define WARN_JAVA_TYPEMAP_DIRECTORIN_NODESC 824 @@ -283,6 +284,7 @@ #define WARN_CSHARP_TYPEMAP_CSIN_UNDEF 838 #define WARN_CSHARP_TYPEMAP_CSDIRECTORIN_UNDEF 839 #define WARN_CSHARP_TYPEMAP_CSDIRECTOROUT_UNDEF 840 +#define WARN_CSHARP_TYPEMAP_INTERFACECODE_UNDEF 841 #define WARN_CSHARP_COVARIANT_RET 842 #define WARN_CSHARP_TYPEMAP_CSCONSTRUCT_UNDEF 843 #define WARN_CSHARP_EXCODE 844 diff --git a/Source/Makefile.am b/Source/Makefile.am index 84dc05458..b1d6359b0 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -47,6 +47,7 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/emit.cxx \ Modules/go.cxx \ Modules/guile.cxx \ + Modules/interface.cxx \ Modules/java.cxx \ Modules/javascript.cxx \ Modules/lang.cxx \ @@ -61,6 +62,7 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/overload.cxx \ Modules/perl5.cxx \ Modules/php.cxx \ + Modules/php5.cxx \ Modules/pike.cxx \ Modules/python.cxx \ Modules/r.cxx \ diff --git a/Source/Modules/allegrocl.cxx b/Source/Modules/allegrocl.cxx index 4b2f325ba..77f1319c7 100644 --- a/Source/Modules/allegrocl.cxx +++ b/Source/Modules/allegrocl.cxx @@ -1635,9 +1635,7 @@ int ALLEGROCL::top(Node *n) { Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGALLEGROCL\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGALLEGROCL\n#define SWIGALLEGROCL\n#endif\n\n"); Swig_banner_target_lang(f_cl, ";;"); @@ -1895,11 +1893,12 @@ static List *Swig_overload_rank(Node *n, bool script_lang_wrapping) { Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[i].n), Getline(nodes[i].n), "using non-const method %s instead.\n", Swig_name_decl(nodes[i].n)); } else { - if (!Getattr(nodes[j].n, "overload:ignore")) + if (!Getattr(nodes[j].n, "overload:ignore")) { Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n), "Overloaded method %s ignored,\n", Swig_name_decl(nodes[j].n)); Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[i].n), Getline(nodes[i].n), "using %s instead.\n", Swig_name_decl(nodes[i].n)); + } } } nodes[j].error = 1; @@ -1912,11 +1911,12 @@ static List *Swig_overload_rank(Node *n, bool script_lang_wrapping) { Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[i].n), Getline(nodes[i].n), "using non-const method %s instead.\n", Swig_name_decl(nodes[i].n)); } else { - if (!Getattr(nodes[j].n, "overload:ignore")) + if (!Getattr(nodes[j].n, "overload:ignore")) { Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n), "Overloaded method %s ignored,\n", Swig_name_decl(nodes[j].n)); Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[i].n), Getline(nodes[i].n), "using %s instead.\n", Swig_name_decl(nodes[i].n)); + } } } nodes[j].error = 1; @@ -1934,11 +1934,12 @@ static List *Swig_overload_rank(Node *n, bool script_lang_wrapping) { Swig_warning(WARN_LANG_OVERLOAD_SHADOW, Getfile(nodes[i].n), Getline(nodes[i].n), "as it is shadowed by %s.\n", Swig_name_decl(nodes[i].n)); } else { - if (!Getattr(nodes[j].n, "overload:ignore")) + if (!Getattr(nodes[j].n, "overload:ignore")) { Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n), "Overloaded method %s ignored,\n", Swig_name_decl(nodes[j].n)); Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[i].n), Getline(nodes[i].n), "using %s instead.\n", Swig_name_decl(nodes[i].n)); + } } nodes[j].error = 1; } @@ -2721,6 +2722,13 @@ int ALLEGROCL::functionWrapper(Node *n) { } } + /* See if there is any return cleanup code */ + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); + Delete(tm); + } + emit_return_variable(n, t, f); if (CPlusPlus) { @@ -3168,6 +3176,9 @@ int ALLEGROCL::enumDeclaration(Node *n) { Printf(stderr, "enumDeclaration %s\n", Getattr(n, "name")); #endif + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + if (Getattr(n, "sym:name")) { add_defined_foreign_type(n); } diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index f79373d18..3d382b378 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -729,6 +729,8 @@ Allocate(): } } + Swig_interface_propagate_methods(n); + /* Only care about default behavior. Remove temporary values */ Setattr(n, "allocate:visit", "1"); Swig_symbol_setscope(symtab); diff --git a/Source/Modules/cffi.cxx b/Source/Modules/cffi.cxx index 8f718e653..bf3338813 100644 --- a/Source/Modules/cffi.cxx +++ b/Source/Modules/cffi.cxx @@ -61,6 +61,11 @@ public: virtual int classHandler(Node *n); private: + static void checkConstraints(ParmList *parms, Wrapper *f); + static void argout(ParmList *parms, Wrapper *f); + static String *freearg(ParmList *parms); + static void cleanupFunction(Node *n, Wrapper *f, ParmList *parms); + void emit_defun(Node *n, String *name); void emit_defmethod(Node *n); void emit_initialize_instance(Node *n); @@ -169,9 +174,7 @@ int CFFI::top(Node *n) { Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGCFFI\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGCFFI\n#define SWIGCFFI\n#endif\n\n"); Swig_banner_target_lang(f_lisp, ";;;"); @@ -364,6 +367,77 @@ int CFFI::membervariableHandler(Node *n) { return Language::membervariableHandler(n); } + +void CFFI::checkConstraints(ParmList *parms, Wrapper *f) { + Parm *p = parms; + while (p) { + String *tm = Getattr(p, "tmap:check"); + if (!tm) { + p = nextSibling(p); + } else { + tm = Copy(tm); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(f->code, tm, "\n\n", NULL); + Delete(tm); + p = Getattr(p, "tmap:check:next"); + } + } +} + +void CFFI::argout(ParmList *parms, Wrapper *f) { + Parm *p = parms; + while (p) { + String *tm = Getattr(p, "tmap:argout"); + if (!tm) { + p = nextSibling(p); + } else { + tm = Copy(tm); + Replaceall(tm, "$result", Swig_cresult_name()); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(f->code, tm, "\n", NULL); + Delete(tm); + p = Getattr(p, "tmap:argout:next"); + } + } +} + +String *CFFI::freearg(ParmList *parms) { + String *ret = NewString(""); + Parm *p = parms; + while (p) { + String *tm = Getattr(p, "tmap:freearg"); + if (!tm) { + p = nextSibling(p); + } else { + tm = Copy(tm); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(ret, tm, "\n", NULL); + Delete(tm); + p = Getattr(p, "tmap:freearg:next"); + } + } + return ret; +} + +void CFFI::cleanupFunction(Node *n, Wrapper *f, ParmList *parms) { + String *cleanup = freearg(parms); + Printv(f->code, cleanup, NULL); + + if (GetFlag(n, "feature:new")) { + String *tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); + if (tm) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printv(f->code, tm, "\n", NULL); + Delete(tm); + } + } + + Replaceall(f->code, "$cleanup", cleanup); + Delete(cleanup); + + Replaceall(f->code, "$symname", Getattr(n, "sym:name")); +} + int CFFI::functionWrapper(Node *n) { ParmList *parms = Getattr(n, "parms"); @@ -451,6 +525,9 @@ int CFFI::functionWrapper(Node *n) { // Emit the function definition String *signature = SwigType_str(return_type, name_and_parms); Printf(f->def, "EXPORT %s {", signature); + + checkConstraints(parms, f); + Printf(f->code, " try {\n"); String *actioncode = emit_action(n); @@ -459,9 +536,25 @@ int CFFI::functionWrapper(Node *n) { if (result_convert) { Replaceall(result_convert, "$result", "lresult"); Printf(f->code, "%s\n", result_convert); - if(!is_void_return) Printf(f->code, " return lresult;\n"); - Delete(result_convert); } + Delete(result_convert); + + argout(parms, f); + + cleanupFunction(n, f, parms); + + /* See if there is any return cleanup code */ + String *tm = 0; + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); + Delete(tm); + } + + if (!is_void_return) { + Printf(f->code, " return lresult;\n"); + } + emit_return_variable(n, Getattr(n, "type"), f); Printf(f->code, " } catch (...) {\n"); @@ -603,6 +696,9 @@ int CFFI::typedefHandler(Node *n) { } int CFFI::enumDeclaration(Node *n) { + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + String *name = Getattr(n, "sym:name"); bool slot_name_keywords; String *lisp_name = 0; @@ -860,8 +956,11 @@ void CFFI::emit_struct_union(Node *n, bool un = false) { } void CFFI::emit_export(Node *n, String *name) { - if (GetInt(n, "feature:export")) - Printf(f_cl, "\n(cl:export '%s)\n", name); + if (GetInt(n, "feature:export")) { + String* package = Getattr(n, "feature:export:package"); + Printf(f_cl, "\n(cl:export '%s%s%s)\n", name, package ? " " : "", + package ? package : ""); + } } void CFFI::emit_inline(Node *n, String *name) { @@ -1019,7 +1118,7 @@ String *CFFI::convert_literal(String *literal, String *type, bool try_to_split) return num; } else if (SwigType_type(type) == T_CHAR) { /* Use CL syntax for character literals */ - String* result = NewStringf("#\\%c", s[0]); + String* result = NewStringf("#\\%s", s); Delete(num); return result; } else if (SwigType_type(type) == T_STRING) { diff --git a/Source/Modules/chicken.cxx b/Source/Modules/chicken.cxx index 986638cf3..68a42a29b 100644 --- a/Source/Modules/chicken.cxx +++ b/Source/Modules/chicken.cxx @@ -222,8 +222,7 @@ int CHICKEN::top(Node *n) { Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGCHICKEN\n"); + Printf(f_runtime, "\n\n#ifndef SWIGCHICKEN\n#define SWIGCHICKEN\n#endif\n\n"); if (no_collection) Printf(f_runtime, "#define SWIG_CHICKEN_NO_COLLECTION 1\n"); diff --git a/Source/Modules/clisp.cxx b/Source/Modules/clisp.cxx index 7d7c69a50..d7f197197 100644 --- a/Source/Modules/clisp.cxx +++ b/Source/Modules/clisp.cxx @@ -242,6 +242,9 @@ int CLISP::typedefHandler(Node *n) { } int CLISP::enumDeclaration(Node *n) { + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + is_function = 0; String *name = Getattr(n, "sym:name"); diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 9193cd34b..01fd5435b 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -52,6 +52,7 @@ class CSHARP:public Language { String *imclass_class_code; // intermediary class code String *proxy_class_def; String *proxy_class_code; + String *interface_class_code; // if %feature("interface") was declared for a class, here goes the interface declaration String *module_class_code; String *proxy_class_name; // proxy class name String *full_imclass_name; // fully qualified intermediary class name when using nspace feature, otherwise same as imclass_name @@ -126,6 +127,7 @@ public: imclass_class_code(NULL), proxy_class_def(NULL), proxy_class_code(NULL), + interface_class_code(NULL), module_class_code(NULL), proxy_class_name(NULL), full_imclass_name(NULL), @@ -186,8 +188,12 @@ public: String *symname = Copy(Getattr(n, "sym:name")); if (symname && !GetFlag(n, "feature:flatnested")) { for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { - Push(symname, "."); - Push(symname, Getattr(outer_class, "sym:name")); + if (String* name = Getattr(outer_class, "sym:name")) { + Push(symname, "."); + Push(symname, name); + } + else + return NULL; } } if (nspace) { @@ -272,6 +278,7 @@ public: SWIG_config_file("csharp.swg"); allow_overloading(); + Swig_interface_feature_enable(); } /* --------------------------------------------------------------------- @@ -392,8 +399,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGCSHARP\n"); + Printf(f_runtime, "\n\n#ifndef SWIGCSHARP\n#define SWIGCSHARP\n#endif\n\n"); if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); @@ -416,8 +422,16 @@ public: } Printf(f_runtime, "\n"); + if (namespce) { + String *wrapper_name = NewStringf(""); + Printf(wrapper_name, "CSharp_%s_%%f", namespce); + Swig_name_register("wrapper", wrapper_name); + Delete(wrapper_name); + } + else { + Swig_name_register("wrapper", "CSharp_%f"); + } - Swig_name_register("wrapper", "CSharp_%f"); if (old_variable_names) { Swig_name_register("set", "set_%n%v"); Swig_name_register("get", "get_%n%v"); @@ -1310,7 +1324,7 @@ public: const char *val = Equal(Getattr(n, "enumvalue"), "true") ? "1" : "0"; Setattr(n, "enumvalue", val); } else if (swigtype == T_CHAR) { - String *val = NewStringf("'%s'", Getattr(n, "enumvalue")); + String *val = NewStringf("'%(hexescape)s'", Getattr(n, "enumvalue")); Setattr(n, "enumvalue", val); Delete(val); } @@ -1434,6 +1448,7 @@ public: virtual int constantWrapper(Node *n) { String *symname = Getattr(n, "sym:name"); SwigType *t = Getattr(n, "type"); + SwigType *valuetype = Getattr(n, "valuetype"); ParmList *l = Getattr(n, "parms"); String *tm; String *return_type = NewString(""); @@ -1486,13 +1501,15 @@ public: Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(t, 0)); } + // Default (octal) escaping is no good - change to hex escaped value + String *hexescaped_value = Getattr(n, "rawvalue") ? NewStringf("%(hexescape)s", Getattr(n, "rawvalue")) : 0; // Add the stripped quotes back in String *new_value = NewString(""); if (SwigType_type(t) == T_STRING) { - Printf(new_value, "\"%s\"", Copy(Getattr(n, "value"))); + Printf(new_value, "\"%s\"", hexescaped_value ? hexescaped_value : Copy(Getattr(n, "value"))); Setattr(n, "value", new_value); } else if (SwigType_type(t) == T_CHAR) { - Printf(new_value, "\'%s\'", Copy(Getattr(n, "value"))); + Printf(new_value, "\'%s\'", hexescaped_value ? hexescaped_value : Copy(Getattr(n, "value"))); Setattr(n, "value", new_value); } @@ -1533,10 +1550,14 @@ public: } else { // Alternative constant handling will use the C syntax to make a true C# constant and hope that it compiles as C# code if (Getattr(n, "wrappedasconstant")) { - if (SwigType_type(t) == T_CHAR) - Printf(constants_code, "\'%s\';\n", Getattr(n, "staticmembervariableHandler:value")); - else + if (SwigType_type(t) == T_CHAR) { + if (SwigType_type(valuetype) == T_CHAR) + Printf(constants_code, "\'%(hexescape)s\';\n", Getattr(n, "staticmembervariableHandler:value")); + else + Printf(constants_code, "(char)%s;\n", Getattr(n, "staticmembervariableHandler:value")); + } else { Printf(constants_code, "%s;\n", Getattr(n, "staticmembervariableHandler:value")); + } } else { Printf(constants_code, "%s;\n", Getattr(n, "value")); } @@ -1636,6 +1657,119 @@ public: return Language::pragmaDirective(n); } + /* ----------------------------------------------------------------------------- + * getQualifiedInterfaceName() + * ----------------------------------------------------------------------------- */ + + String *getQualifiedInterfaceName(Node *n) { + String *ret = Getattr(n, "interface:qname"); + if (!ret) { + String *nspace = Getattr(n, "sym:nspace"); + String *interface_name = Getattr(n, "interface:name"); + if (nspace) { + if (namespce) + ret = NewStringf("%s.%s.%s", namespce, nspace, interface_name); + else + ret = NewStringf("%s.%s", nspace, interface_name); + } else { + ret = Copy(interface_name); + } + Setattr(n, "interface:qname", ret); + } + return ret; + } + + /* ----------------------------------------------------------------------------- + * getInterfaceName() + * ----------------------------------------------------------------------------- */ + + String *getInterfaceName(SwigType *t, bool qualified) { + String *interface_name = NULL; + if (proxy_flag) { + Node *n = classLookup(t); + if (n && Getattr(n, "interface:name")) + interface_name = qualified ? getQualifiedInterfaceName(n) : Getattr(n, "interface:name"); + } + return interface_name; + } + + /* ----------------------------------------------------------------------------- + * addInterfaceNameAndUpcasts() + * ----------------------------------------------------------------------------- */ + + void addInterfaceNameAndUpcasts(SwigType *smart, String *interface_list, String *interface_upcasts, Hash *base_list, String *c_classname) { + List *keys = Keys(base_list); + for (Iterator it = First(keys); it.item; it = Next(it)) { + Node *base = Getattr(base_list, it.item); + String *c_baseclass = SwigType_namestr(Getattr(base, "name")); + String *interface_name = Getattr(base, "interface:name"); + if (Len(interface_list)) + Append(interface_list, ", "); + Append(interface_list, interface_name); + + Node *attributes = NewHash(); + String *interface_code = Copy(typemapLookup(base, "csinterfacecode", Getattr(base, "classtypeobj"), WARN_CSHARP_TYPEMAP_INTERFACECODE_UNDEF, attributes)); + String *cptr_method_name = 0; + if (interface_code) { + Replaceall(interface_code, "$interfacename", interface_name); + Printv(interface_upcasts, interface_code, NIL); + cptr_method_name = Copy(Getattr(attributes, "tmap:csinterfacecode:cptrmethod")); + } + if (!cptr_method_name) + cptr_method_name = NewStringf("%s_GetInterfaceCPtr", interface_name); + Replaceall(cptr_method_name, ".", "_"); + Replaceall(cptr_method_name, "$interfacename", interface_name); + + String *upcast_method_name = Swig_name_member(getNSpace(), proxy_class_name, cptr_method_name); + upcastsCode(smart, upcast_method_name, c_classname, c_baseclass); + + Delete(upcast_method_name); + Delete(cptr_method_name); + Delete(interface_code); + Delete(c_baseclass); + } + Delete(keys); + } + + /* ----------------------------------------------------------------------------- + * upcastsCode() + * + * Add code for C++ casting to base class + * ----------------------------------------------------------------------------- */ + + void upcastsCode(SwigType *smart, String *upcast_method_name, String *c_classname, String *c_baseclass) { + String *wname = Swig_name_wrapper(upcast_method_name); + + Printv(imclass_cppcasts_code, "\n [global::System.Runtime.InteropServices.DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); + Printf(imclass_cppcasts_code, " public static extern global::System.IntPtr %s(global::System.IntPtr jarg1);\n", upcast_method_name); + + Replaceall(imclass_cppcasts_code, "$csclassname", proxy_class_name); + + if (smart) { + SwigType *bsmart = Copy(smart); + SwigType *rclassname = SwigType_typedef_resolve_all(c_classname); + SwigType *rbaseclass = SwigType_typedef_resolve_all(c_baseclass); + Replaceall(bsmart, rclassname, rbaseclass); + Delete(rclassname); + Delete(rbaseclass); + String *smartnamestr = SwigType_namestr(smart); + String *bsmartnamestr = SwigType_namestr(bsmart); + Printv(upcasts_code, + "SWIGEXPORT ", bsmartnamestr, " * SWIGSTDCALL ", wname, "(", smartnamestr, " *jarg1) {\n", + " return jarg1 ? new ", bsmartnamestr, "(*jarg1) : 0;\n" + "}\n", "\n", NIL); + Delete(bsmartnamestr); + Delete(smartnamestr); + Delete(bsmart); + } else { + Printv(upcasts_code, + "SWIGEXPORT ", c_baseclass, " * SWIGSTDCALL ", wname, "(", c_classname, " *jarg1) {\n", + " return (", c_baseclass, " *)jarg1;\n" + "}\n", "\n", NIL); + } + Delete(wname); + } + /* ----------------------------------------------------------------------------- * emitProxyClassDefAndCPPCasts() * ----------------------------------------------------------------------------- */ @@ -1645,9 +1779,12 @@ public: String *c_baseclass = NULL; String *baseclass = NULL; String *c_baseclassname = NULL; + String *interface_list = NewStringEmpty(); + String *interface_upcasts = NewStringEmpty(); SwigType *typemap_lookup_type = Getattr(n, "classtypeobj"); bool feature_director = Swig_directorclass(n) ? true : false; bool has_outerclass = Getattr(n, "nested:outer") != 0 && !GetFlag(n, "feature:flatnested"); + SwigType *smart = Swig_cparse_smartptr(n); // Inheritance from pure C# classes Node *attributes = NewHash(); @@ -1660,31 +1797,29 @@ public: if (!purebase_replace) { List *baselist = Getattr(n, "bases"); if (baselist) { - Iterator base = First(baselist); - while (base.item && GetFlag(base.item, "feature:ignore")) { - base = Next(base); - } - if (base.item) { - c_baseclassname = Getattr(base.item, "name"); - baseclass = Copy(getProxyName(c_baseclassname)); - if (baseclass) - c_baseclass = SwigType_namestr(Getattr(base.item, "name")); - base = Next(base); - /* Warn about multiple inheritance for additional base class(es) */ - while (base.item) { - if (GetFlag(base.item, "feature:ignore")) { - base = Next(base); - continue; - } - String *proxyclassname = Getattr(n, "classtypeobj"); - String *baseclassname = Getattr(base.item, "name"); - Swig_warning(WARN_CSHARP_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in C#.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); - base = Next(base); - } - } + Iterator base = First(baselist); + while (base.item) { + if (!(GetFlag(base.item, "feature:ignore") || Getattr(base.item, "feature:interface"))) { + String *baseclassname = Getattr(base.item, "name"); + if (!c_baseclassname) { + c_baseclassname = baseclassname; + baseclass = Copy(getProxyName(baseclassname)); + if (baseclass) + c_baseclass = SwigType_namestr(baseclassname); + } else { + /* Warn about multiple inheritance for additional base class(es) */ + String *proxyclassname = Getattr(n, "classtypeobj"); + Swig_warning(WARN_CSHARP_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), + "Warning for %s, base %s ignored. Multiple inheritance is not supported in C#.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); + } + } + base = Next(base); + } } } + Hash *interface_bases = Getattr(n, "interface:bases"); + if (interface_bases) + addInterfaceNameAndUpcasts(smart, interface_list, interface_upcasts, interface_bases, c_classname); bool derived = baseclass && getProxyName(c_baseclassname); if (derived && purebase_notderived) @@ -1700,12 +1835,15 @@ public: Swig_error(Getfile(n), Getline(n), "The csbase typemap for proxy %s must contain just one of the 'replace' or 'notderived' attributes.\n", typemap_lookup_type); } else if (Len(pure_baseclass) > 0 && Len(baseclass) > 0) { Swig_warning(WARN_CSHARP_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in C#. " + "Warning for %s, base %s ignored. Multiple inheritance is not supported in C#. " "Perhaps you need one of the 'replace' or 'notderived' attributes in the csbase typemap?\n", typemap_lookup_type, pure_baseclass); } // Pure C# interfaces const String *pure_interfaces = typemapLookup(n, derived ? "csinterfaces_derived" : "csinterfaces", typemap_lookup_type, WARN_NONE); + if (*Char(interface_list) && *Char(pure_interfaces)) + Append(interface_list, ", "); + Append(interface_list, pure_interfaces); // Start writing the proxy class if (!has_outerclass) Printv(proxy_class_def, typemapLookup(n, "csimports", typemap_lookup_type, WARN_NONE), // Import statements @@ -1718,8 +1856,8 @@ public: Printv(proxy_class_def, typemapLookup(n, "csclassmodifiers", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CLASSMOD_UNDEF), // Class modifiers " $csclassname", // Class name and base class - (*Char(wanted_base) || *Char(pure_interfaces)) ? " : " : "", wanted_base, (*Char(wanted_base) && *Char(pure_interfaces)) ? // Interfaces - ", " : "", pure_interfaces, " {", derived ? typemapLookup(n, "csbody_derived", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF) : // main body of class + (*Char(wanted_base) || *Char(interface_list)) ? " : " : "", wanted_base, (*Char(wanted_base) && *Char(interface_list)) ? // Interfaces + ", " : "", interface_list, " {", derived ? typemapLookup(n, "csbody_derived", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF) : // main body of class typemapLookup(n, "csbody", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF), // main body of class NIL); @@ -1764,6 +1902,8 @@ public: Printv(proxy_class_def, "\n ", destruct_methodmodifiers, " ", derived ? "override" : "virtual", " void ", destruct_methodname, "() ", destruct, "\n", NIL); } + if (*Char(interface_upcasts)) + Printv(proxy_class_def, interface_upcasts, NIL); if (feature_director) { // Generate director connect method @@ -1845,6 +1985,8 @@ public: Delete(director_connect_method_name); } + Delete(interface_upcasts); + Delete(interface_list); Delete(attributes); Delete(destruct); @@ -1852,60 +1994,92 @@ public: Printv(proxy_class_def, typemapLookup(n, "cscode", typemap_lookup_type, WARN_NONE), // extra C# code "\n", NIL); - // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy) if (derived) { - String *smartptr = Getattr(n, "feature:smartptr"); - String *upcast_method = Swig_name_member(getNSpace(), getClassPrefix(), smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); - String *wname = Swig_name_wrapper(upcast_method); - - Printv(imclass_cppcasts_code, "\n [global::System.Runtime.InteropServices.DllImport(\"", dllimport, "\", EntryPoint=\"", wname, "\")]\n", NIL); - Printf(imclass_cppcasts_code, " public static extern global::System.IntPtr %s(global::System.IntPtr jarg1);\n", upcast_method); - - Replaceall(imclass_cppcasts_code, "$csclassname", proxy_class_name); - - if (smartptr) { - SwigType *spt = Swig_cparse_type(smartptr); - if (spt) { - SwigType *smart = SwigType_typedef_resolve_all(spt); - Delete(spt); - SwigType *bsmart = Copy(smart); - SwigType *rclassname = SwigType_typedef_resolve_all(c_classname); - SwigType *rbaseclass = SwigType_typedef_resolve_all(c_baseclass); - Replaceall(bsmart, rclassname, rbaseclass); - Delete(rclassname); - Delete(rbaseclass); - String *smartnamestr = SwigType_namestr(smart); - String *bsmartnamestr = SwigType_namestr(bsmart); - Printv(upcasts_code, - "SWIGEXPORT ", bsmartnamestr, " * SWIGSTDCALL ", wname, "(", smartnamestr, " *jarg1) {\n", - " return jarg1 ? new ", bsmartnamestr, "(*jarg1) : 0;\n" - "}\n", "\n", NIL); - Delete(bsmartnamestr); - Delete(smartnamestr); - Delete(bsmart); - } else { - Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, c_classname); - } - } else { - Printv(upcasts_code, - "SWIGEXPORT ", c_baseclass, " * SWIGSTDCALL ", wname, "(", c_classname, " *jarg1) {\n", - " return (", c_baseclass, " *)jarg1;\n" - "}\n", "\n", NIL); - } - Delete(wname); - Delete(upcast_method); + String *upcast_method_name = Swig_name_member(getNSpace(), getClassPrefix(), smart != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); + upcastsCode(smart, upcast_method_name, c_classname, c_baseclass); + Delete(upcast_method_name); } + + Delete(smart); Delete(baseclass); } + /* ---------------------------------------------------------------------- + * emitInterfaceDeclaration() + * ---------------------------------------------------------------------- */ + + void emitInterfaceDeclaration(Node *n, String *interface_name, File *f_interface) { + Printv(f_interface, typemapLookup(n, "csimports", Getattr(n, "classtypeobj"), WARN_NONE), "\n", NIL); + Printf(f_interface, "public interface %s", interface_name); + if (List *baselist = Getattr(n, "bases")) { + String *bases = 0; + for (Iterator base = First(baselist); base.item; base = Next(base)) { + if (GetFlag(base.item, "feature:ignore") || !Getattr(base.item, "feature:interface")) + continue; // TODO: warn about skipped non-interface bases + String *base_iname = Getattr(base.item, "interface:name"); + if (!bases) + bases = NewStringf(" : %s", base_iname); + else { + Append(bases, ", "); + Append(bases, base_iname); + } + } + if (bases) { + Printv(f_interface, bases, NIL); + Delete(bases); + } + } + Printf(f_interface, " {\n"); + + Node *attributes = NewHash(); + String *interface_code = Copy(typemapLookup(n, "csinterfacecode", Getattr(n, "classtypeobj"), WARN_CSHARP_TYPEMAP_INTERFACECODE_UNDEF, attributes)); + if (interface_code) { + String *interface_declaration = Copy(Getattr(attributes, "tmap:csinterfacecode:declaration")); + if (interface_declaration) { + Replaceall(interface_declaration, "$interfacename", interface_name); + Printv(f_interface, interface_declaration, NIL); + Delete(interface_declaration); + } + Delete(interface_code); + } + } + + /* ---------------------------------------------------------------------- + * calculateDirectBase() + * ---------------------------------------------------------------------- */ + + void calculateDirectBase(Node* n) { + Node* direct_base = 0; + // C++ inheritance + Node *attributes = NewHash(); + SwigType *typemap_lookup_type = Getattr(n, "classtypeobj"); + const String *pure_baseclass = typemapLookup(n, "csbase", typemap_lookup_type, WARN_NONE, attributes); + bool purebase_replace = GetFlag(attributes, "tmap:csbase:replace") ? true : false; + bool purebase_notderived = GetFlag(attributes, "tmap:csbase:notderived") ? true : false; + Delete(attributes); + if (!purebase_replace) { + if (List *baselist = Getattr(n, "bases")) { + Iterator base = First(baselist); + while (base.item && (GetFlag(base.item, "feature:ignore") || Getattr(base.item, "feature:interface"))) + base = Next(base); + direct_base = base.item; + } + if (!direct_base && purebase_notderived) + direct_base = symbolLookup(const_cast(pure_baseclass)); + } else { + direct_base = symbolLookup(const_cast(pure_baseclass)); + } + Setattr(n, "direct_base", direct_base); + } + /* ---------------------------------------------------------------------- * classHandler() * ---------------------------------------------------------------------- */ virtual int classHandler(Node *n) { - String *nspace = getNSpace(); File *f_proxy = NULL; + File *f_interface = NULL; // save class local variables String *old_proxy_class_name = proxy_class_name; String *old_full_imclass_name = full_imclass_name; @@ -1914,9 +2088,12 @@ public: String *old_proxy_class_def = proxy_class_def; String *old_proxy_class_code = proxy_class_code; bool has_outerclass = Getattr(n, "nested:outer") && !GetFlag(n, "feature:flatnested"); + String *old_interface_class_code = interface_class_code; + interface_class_code = 0; if (proxy_flag) { proxy_class_name = NewString(Getattr(n, "sym:name")); + String *interface_name = Getattr(n, "feature:interface") ? Getattr(n, "interface:name") : 0; if (Node *outer = Getattr(n, "nested:outer")) { String *outerClassesPrefix = Copy(Getattr(outer, "sym:name")); for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { @@ -1926,13 +2103,16 @@ public: String *fnspace = nspace ? NewStringf("%s.%s", nspace, outerClassesPrefix) : outerClassesPrefix; if (!addSymbol(proxy_class_name, n, fnspace)) return SWIG_ERROR; + if (interface_name && !addInterfaceSymbol(interface_name, n, fnspace)) + return SWIG_ERROR; if (nspace) Delete(fnspace); Delete(outerClassesPrefix); - } - else { + } else { if (!addSymbol(proxy_class_name, n, nspace)) return SWIG_ERROR; + if (interface_name && !addInterfaceSymbol(interface_name, n, nspace)) + return SWIG_ERROR; } if (!nspace) { @@ -1959,13 +2139,25 @@ public: f_proxy = getOutputFile(output_directory, proxy_class_name); addOpenNamespace(nspace, f_proxy); + Delete(output_directory); } else ++nesting_depth; + proxy_class_def = NewString(""); proxy_class_code = NewString(""); destructor_call = NewString(""); proxy_class_constants_code = NewString(""); + + if (Getattr(n, "feature:interface")) { + interface_class_code = NewString(""); + String *output_directory = outputDirectory(nspace); + f_interface = getOutputFile(output_directory, interface_name); + addOpenNamespace(nspace, f_interface); + emitInterfaceDeclaration(n, interface_name, interface_class_code); + Delete(output_directory); + } + calculateDirectBase(n); } Language::classHandler(n); @@ -1979,22 +2171,28 @@ public: Replaceall(proxy_class_def, "$csclassname", proxy_class_name); Replaceall(proxy_class_code, "$csclassname", proxy_class_name); Replaceall(proxy_class_constants_code, "$csclassname", proxy_class_name); + Replaceall(interface_class_code, "$csclassname", proxy_class_name); Replaceall(proxy_class_def, "$csclazzname", csclazzname); Replaceall(proxy_class_code, "$csclazzname", csclazzname); Replaceall(proxy_class_constants_code, "$csclazzname", csclazzname); + Replaceall(interface_class_code, "$csclazzname", csclazzname); Replaceall(proxy_class_def, "$module", module_class_name); Replaceall(proxy_class_code, "$module", module_class_name); Replaceall(proxy_class_constants_code, "$module", module_class_name); + Replaceall(interface_class_code, "$module", module_class_name); Replaceall(proxy_class_def, "$imclassname", full_imclass_name); Replaceall(proxy_class_code, "$imclassname", full_imclass_name); Replaceall(proxy_class_constants_code, "$imclassname", full_imclass_name); + Replaceall(interface_class_code, "$imclassname", full_imclass_name); Replaceall(proxy_class_def, "$dllimport", dllimport); Replaceall(proxy_class_code, "$dllimport", dllimport); Replaceall(proxy_class_constants_code, "$dllimport", dllimport); + Replaceall(interface_class_code, "$dllimport", dllimport); + if (!has_outerclass) Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); else { @@ -2057,8 +2255,18 @@ public: Delete(downcast_method); } + if (f_interface) { + Printv(f_interface, interface_class_code, "}\n", NIL); + addCloseNamespace(nspace, f_interface); + if (f_interface != f_single_out) + Delete(f_interface); + f_interface = 0; + } + emitDirectorExtraMethods(n); + Delete(interface_class_code); + interface_class_code = old_interface_class_code; Delete(csclazzname); Delete(proxy_class_name); proxy_class_name = old_proxy_class_name; @@ -2144,6 +2352,8 @@ public: String *pre_code = NewString(""); String *post_code = NewString(""); String *terminator_code = NewString(""); + bool is_interface = Getattr(parentNode(n), "feature:interface") != 0 + && !static_flag && Getattr(n, "interface:owner") == 0; if (!proxy_flag) return; @@ -2216,8 +2426,21 @@ public: Printf(function_code, " %s ", methodmods); if (!is_smart_pointer()) { // Smart pointer classes do not mirror the inheritance hierarchy of the underlying pointer type, so no virtual/override/new required. - if (Getattr(n, "override")) - Printf(function_code, "override "); + if (Node *base_ovr = Getattr(n, "override")) { + if (GetFlag(n, "isextendmember")) + Printf(function_code, "override "); + else { + Node* base = parentNode(base_ovr); + bool ovr = false; + for (Node* direct_base = Getattr(parentNode(n), "direct_base"); direct_base; direct_base = Getattr(direct_base, "direct_base")) { + if (direct_base == base) { // "override" only applies if the base was not discarded (e.g. in case of multiple inheritance or via "ignore") + ovr = true; + break; + } + } + Printf(function_code, ovr ? "override " : "virtual "); + } + } else if (checkAttribute(n, "storage", "virtual")) Printf(function_code, "virtual "); if (Getattr(n, "hides")) @@ -2227,6 +2450,9 @@ public: if (static_flag) Printf(function_code, "static "); Printf(function_code, "%s %s(", return_type, proxy_function_name); + if (is_interface) + Printf(interface_class_code, " %s %s(", return_type, proxy_function_name); + Printv(imcall, full_imclass_name, ".$imfuncname(", NIL); if (!static_flag) @@ -2306,10 +2532,15 @@ public: } /* Add parameter to proxy function */ - if (gencomma >= 2) + if (gencomma >= 2) { Printf(function_code, ", "); + if (is_interface) + Printf(interface_class_code, ", "); + } gencomma = 2; Printf(function_code, "%s %s", param_type, arg); + if (is_interface) + Printf(interface_class_code, "%s %s", param_type, arg); Delete(arg); Delete(param_type); @@ -2319,6 +2550,8 @@ public: Printf(imcall, ")"); Printf(function_code, ")"); + if (is_interface) + Printf(interface_class_code, ");\n"); // Transform return type used in PInvoke function (in intermediary class) to type used in C# wrapper function (in proxy class) if ((tm = Swig_typemap_lookup("csout", n, "", 0))) { @@ -3187,6 +3420,50 @@ public: substitution_performed = true; Delete(classnametype); } + if (Strstr(tm, "$csinterfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$csinterfacename", true); + substitution_performed = true; + Delete(interfacenametype); + } + if (Strstr(tm, "$*csinterfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + Delete(SwigType_pop(interfacenametype)); + if (Len(interfacenametype) > 0) { + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$*csinterfacename", true); + substitution_performed = true; + } + Delete(interfacenametype); + } + if (Strstr(tm, "$&csinterfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + SwigType_add_pointer(interfacenametype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$&csinterfacename", true); + substitution_performed = true; + Delete(interfacenametype); + } + if (Strstr(tm, "$interfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$interfacename", false); + substitution_performed = true; + Delete(interfacenametype); + } + if (Strstr(tm, "$*interfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + Delete(SwigType_pop(interfacenametype)); + if (Len(interfacenametype) > 0) { + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$*interfacename", false); + substitution_performed = true; + } + Delete(interfacenametype); + } + if (Strstr(tm, "$&interfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + SwigType_add_pointer(interfacenametype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$&interfacename", false); + substitution_performed = true; + Delete(interfacenametype); + } Delete(strippedtype); Delete(type); @@ -3232,6 +3509,20 @@ public: Delete(replacementname); } + /* ----------------------------------------------------------------------------- + * substituteInterfacenameSpecialVariable() + * ----------------------------------------------------------------------------- */ + + void substituteInterfacenameSpecialVariable(SwigType *interfacenametype, String *tm, const char *interfacenamespecialvariable, bool qualified) { + + String *interfacename = getInterfaceName(interfacenametype, qualified); + if (interfacename) { + String *replacementname = Copy(interfacename); + Replaceall(tm, interfacenamespecialvariable, replacementname); + Delete(replacementname); + } + } + /* ----------------------------------------------------------------------------- * emitTypeWrapperClass() * ----------------------------------------------------------------------------- */ @@ -3469,7 +3760,7 @@ public: Wrapper *code_wrap = NewWrapper(); Printf(code_wrap->def, "SWIGEXPORT void SWIGSTDCALL %s(void *objarg", wname); - if (Len(smartptr)) { + if (smartptr) { Printf(code_wrap->code, " %s *obj = (%s *)objarg;\n", smartptr, smartptr); Printf(code_wrap->code, " // Keep a local instance of the smart pointer around while we are using the raw pointer\n"); Printf(code_wrap->code, " // Avoids using smart pointer specific API.\n"); diff --git a/Source/Modules/d.cxx b/Source/Modules/d.cxx index 8b0bdded1..ec66ebed2 100644 --- a/Source/Modules/d.cxx +++ b/Source/Modules/d.cxx @@ -472,8 +472,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGD\n"); + Printf(f_runtime, "\n\n#ifndef SWIGD\n#define SWIGD\n#endif\n\n"); if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); @@ -911,7 +910,7 @@ public: const char *val = Equal(Getattr(n, "enumvalue"), "true") ? "1" : "0"; Setattr(n, "enumvalue", val); } else if (swigtype == T_CHAR) { - String *val = NewStringf("'%s'", Getattr(n, "enumvalue")); + String *val = NewStringf("'%(escape)s'", Getattr(n, "enumvalue")); Setattr(n, "enumvalue", val); Delete(val); } @@ -1424,6 +1423,7 @@ public: String *constants_code = NewString(""); SwigType *t = Getattr(n, "type"); + SwigType *valuetype = Getattr(n, "valuetype"); ParmList *l = Getattr(n, "parms"); // Attach the non-standard typemaps to the parameter list. @@ -1471,16 +1471,21 @@ public: Printf(constants_code, "%s;\n", override_value); } else { // Just take the value from the C definition and hope it compiles in D. - String* value = Getattr(n, "wrappedasconstant") ? - Getattr(n, "staticmembervariableHandler:value") : Getattr(n, "value"); - - // Add the stripped quotes back in. - if (SwigType_type(t) == T_STRING) { - Printf(constants_code, "\"%s\";\n", value); - } else if (SwigType_type(t) == T_CHAR) { - Printf(constants_code, "\'%s\';\n", value); + if (Getattr(n, "wrappedasconstant")) { + if (SwigType_type(valuetype) == T_CHAR) + Printf(constants_code, "\'%(escape)s\';\n", Getattr(n, "staticmembervariableHandler:value")); + else + Printf(constants_code, "%s;\n", Getattr(n, "staticmembervariableHandler:value")); } else { - Printf(constants_code, "%s;\n", value); + // Add the stripped quotes back in. + String* value = Getattr(n, "value"); + if (SwigType_type(t) == T_STRING) { + Printf(constants_code, "\"%s\";\n", value); + } else if (SwigType_type(t) == T_CHAR) { + Printf(constants_code, "\'%s\';\n", value); + } else { + Printf(constants_code, "%s;\n", value); + } } } @@ -3124,28 +3129,23 @@ private: List *baselist = Getattr(n, "bases"); if (baselist) { Iterator base = First(baselist); - while (base.item && GetFlag(base.item, "feature:ignore")) { - base = Next(base); - } - if (base.item) { - basenode = base.item; - c_baseclassname = Getattr(base.item, "name"); - basename = createProxyName(c_baseclassname); - if (basename) - c_baseclass = SwigType_namestr(Getattr(base.item, "name")); - base = Next(base); - /* Warn about multiple inheritance for additional base class(es) */ - while (base.item) { - if (GetFlag(base.item, "feature:ignore")) { - base = Next(base); - continue; + while (base.item) { + if (!GetFlag(base.item, "feature:ignore")) { + String *baseclassname = Getattr(base.item, "name"); + if (!c_baseclassname) { + basenode = base.item; + c_baseclassname = baseclassname; + basename = createProxyName(c_baseclassname); + if (basename) + c_baseclass = SwigType_namestr(baseclassname); + } else { + /* Warn about multiple inheritance for additional base class(es) */ + String *proxyclassname = Getattr(n, "classtypeobj"); + Swig_warning(WARN_D_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), + "Base %s of class %s ignored: multiple inheritance is not supported in D.\n", SwigType_namestr(baseclassname), SwigType_namestr(proxyclassname)); } - String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); - String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); - Swig_warning(WARN_D_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Base %s of class %s ignored: multiple inheritance is not supported in D.\n", baseclassname, proxyclassname); - base = Next(base); } + base = Next(base); } } } @@ -3170,7 +3170,7 @@ private: } } else if (basename && Len(pure_baseclass) > 0) { Swig_warning(WARN_D_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base class %s ignored. Multiple inheritance is not supported in D. " + "Warning for %s, base class %s ignored. Multiple inheritance is not supported in D. " "Perhaps you need one of the 'replace' or 'notderived' attributes in the dbase typemap?\n", typemap_lookup_type, pure_baseclass); } @@ -3329,45 +3329,33 @@ private: /* --------------------------------------------------------------------------- * D::writeClassUpcast() * --------------------------------------------------------------------------- */ - void writeClassUpcast(Node *n, const String* d_class_name, - String* c_class_name, String* c_base_name) { - - String *smartptr = Getattr(n, "feature:smartptr"); - String *upcast_name = Swig_name_member(getNSpace(), d_class_name, - (smartptr != 0 ? "SmartPtrUpcast" : "Upcast")); + void writeClassUpcast(Node *n, const String* d_class_name, String* c_class_name, String* c_base_name) { + SwigType *smart = Swig_cparse_smartptr(n); + String *upcast_name = Swig_name_member(getNSpace(), d_class_name, (smart != 0 ? "SmartPtrUpcast" : "Upcast")); String *upcast_wrapper_name = Swig_name_wrapper(upcast_name); writeImDModuleFunction(upcast_name, "void*", "(void* objectRef)", upcast_wrapper_name); - if (smartptr) { - SwigType *spt = Swig_cparse_type(smartptr); - if (spt) { - SwigType *smart = SwigType_typedef_resolve_all(spt); - Delete(spt); - SwigType *bsmart = Copy(smart); - SwigType *rclassname = SwigType_typedef_resolve_all(c_class_name); - SwigType *rbaseclass = SwigType_typedef_resolve_all(c_base_name); - Replaceall(bsmart, rclassname, rbaseclass); - Delete(rclassname); - Delete(rbaseclass); - String *smartnamestr = SwigType_namestr(smart); - String *bsmartnamestr = SwigType_namestr(bsmart); - Printv(upcasts_code, - "SWIGEXPORT ", bsmartnamestr, " * ", upcast_wrapper_name, - "(", smartnamestr, " *objectRef) {\n", - " return objectRef ? new ", bsmartnamestr, "(*objectRef) : 0;\n" - "}\n", - "\n", NIL); - Delete(bsmartnamestr); - Delete(smartnamestr); - Delete(bsmart); - } else { - Swig_error(Getfile(n), Getline(n), - "Invalid type (%s) in 'smartptr' feature for class %s.\n", - smartptr, c_class_name); - } + if (smart) { + SwigType *bsmart = Copy(smart); + SwigType *rclassname = SwigType_typedef_resolve_all(c_class_name); + SwigType *rbaseclass = SwigType_typedef_resolve_all(c_base_name); + Replaceall(bsmart, rclassname, rbaseclass); + Delete(rclassname); + Delete(rbaseclass); + String *smartnamestr = SwigType_namestr(smart); + String *bsmartnamestr = SwigType_namestr(bsmart); + Printv(upcasts_code, + "SWIGEXPORT ", bsmartnamestr, " * ", upcast_wrapper_name, + "(", smartnamestr, " *objectRef) {\n", + " return objectRef ? new ", bsmartnamestr, "(*objectRef) : 0;\n" + "}\n", + "\n", NIL); + Delete(bsmartnamestr); + Delete(smartnamestr); + Delete(bsmart); } else { Printv(upcasts_code, "SWIGEXPORT ", c_base_name, " * ", upcast_wrapper_name, @@ -3382,6 +3370,7 @@ private: Delete(upcast_name); Delete(upcast_wrapper_name); + Delete(smart); } /* --------------------------------------------------------------------------- diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 6b9ba760d..884ae906d 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -785,6 +785,13 @@ private: return SWIG_OK; } + // Don't emit constructors for abstract director classes. They + // will never succeed anyhow. + if (Swig_methodclass(n) && Swig_directorclass(n) + && Strcmp(Char(Getattr(n, "wrap:action")), director_prot_ctor_code) == 0) { + return SWIG_OK; + } + String *name = Getattr(n, "sym:name"); String *nodetype = Getattr(n, "nodeType"); bool is_static = is_static_member_function || isStatic(n); @@ -848,8 +855,7 @@ private: Delete(c2); Delete(c1); - if (Swig_methodclass(n) && Swig_directorclass(n) - && Strcmp(Char(Getattr(n, "wrap:action")), director_prot_ctor_code) != 0) { + if (Swig_methodclass(n) && Swig_directorclass(n)) { // The core SWIG code skips the first parameter when // generating the $nondirector_new string. Recreate the // action in this case. But don't it if we are using the @@ -1356,6 +1362,10 @@ private: goargout(info->parms); if (SwigType_type(info->result) != T_VOID) { + + Swig_save("cgoGoWrapper", info->n, "type", "tmap:goout", NULL); + Setattr(info->n, "type", info->result); + String *goout = goTypemapLookup("goout", info->n, "swig_r"); if (goout == NULL) { Printv(f_go_wrappers, "\treturn swig_r\n", NULL); @@ -1368,6 +1378,8 @@ private: Printv(f_go_wrappers, goout, "\n", NULL); Printv(f_go_wrappers, "\treturn swig_r_1\n", NULL); } + + Swig_restore(info->n); } Printv(f_go_wrappers, "}\n\n", NULL); @@ -1612,8 +1624,13 @@ private: receiver = NULL; } + Swig_save("cgoGoWrapper", n, "type", "tmap:goout", NULL); + Setattr(n, "type", result); + String *goout = goTypemapLookup("goout", n, "swig_r"); + Swig_restore(n); + bool add_to_interface = (interfaces && !is_constructor && !is_destructor && !is_static && !overname && checkFunctionVisibility(n, NULL)); bool needs_wrapper = (gccgo_flag || receiver || is_constructor || is_destructor || parm_count > required_count); @@ -2106,6 +2123,7 @@ private: emit_attach_parmmaps(parms, f); int parm_count = emit_num_arguments(parms); int required_count = emit_num_required(parms); + bool needs_swigargs = false; emit_return_variable(n, result, f); @@ -2119,6 +2137,7 @@ private: String *swigargs = NewString("\tstruct swigargs {\n"); if (parm_count > required_count) { + needs_swigargs = true; Printv(swigargs, "\t\tintgo _swig_optargc;\n", NULL); } @@ -2130,6 +2149,7 @@ private: SwigType *pt = Getattr(p, "type"); String *ct = gcCTypeForGoValue(p, pt, ln); Printv(swigargs, "\t\t\t", ct, ";\n", NULL); + needs_swigargs = true; Delete(ct); String *gn = NewStringf("_swig_go_%d", i); @@ -2146,6 +2166,7 @@ private: String *ct = gcCTypeForGoValue(n, result, ln); Delete(ln); Printv(swigargs, "\t\t", ct, ";\n", NULL); + needs_swigargs = true; Delete(ct); ln = NewString("_swig_go_result"); @@ -2154,7 +2175,7 @@ private: Delete(ct); Delete(ln); } - Printv(swigargs, "\t} *swig_a = (struct swigargs *) swig_v;\n", NULL); + Printv(swigargs, "\t} SWIGSTRUCTPACKED *swig_a = (struct swigargs *) swig_v;\n", NULL); // Copy the input arguments out of the structure into the Go local // variables. @@ -2202,7 +2223,10 @@ private: cleanupFunction(n, f, parms); - Printv(f->locals, swigargs, NULL); + if (needs_swigargs) + { + Printv(f->locals, swigargs, NULL); + } Printv(f->code, "}\n", NULL); @@ -2421,7 +2445,8 @@ private: } String *code = Copy(Getattr(n, "wrap:action")); - Replaceall(code, Getattr(parms, "lname"), current); + Replace(code, Getattr(parms, "lname"), current, DOH_REPLACE_ANY | DOH_REPLACE_ID); + Delete(current); Printv(actioncode, code, "\n", NULL); } @@ -2574,6 +2599,14 @@ private: Replaceall(f->code, "$cleanup", cleanup); Delete(cleanup); + /* See if there is any return cleanup code */ + String *tm; + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); + Delete(tm); + } + Replaceall(f->code, "$symname", Getattr(n, "sym:name")); } @@ -2699,6 +2732,9 @@ private: * ---------------------------------------------------------------------- */ virtual int enumDeclaration(Node *n) { + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + String *name = goEnumName(n); if (Strcmp(name, "int") != 0) { if (!ImportMode || !imported_package) { @@ -2773,28 +2809,39 @@ private: String *get = NewString(""); Printv(get, Swig_cresult_name(), " = ", NULL); - char quote; - if (Getattr(n, "wrappedasconstant")) { - quote = '\0'; - } else if (SwigType_type(type) == T_CHAR) { - quote = '\''; - } else if (SwigType_type(type) == T_STRING) { - quote = '"'; + String *rawval = Getattr(n, "rawval"); + if (rawval && Len(rawval)) { + if (SwigType_type(type) == T_STRING) { + Printv(get, "(char *)", NULL); + } + + Printv(get, rawval, NULL); } else { - quote = '\0'; - } + char quote; + if (Getattr(n, "wrappedasconstant")) { + quote = '\0'; + } else if (SwigType_type(type) == T_CHAR) { + quote = '\''; + } else if (SwigType_type(type) == T_STRING) { + Printv(get, "(char *)", NULL); + quote = '"'; + } else { + quote = '\0'; + } - if (quote != '\0') { - Printf(get, "%c", quote); - } + if (quote != '\0') { + Printf(get, "%c", quote); + } - Printv(get, Getattr(n, "value"), NULL); + Printv(get, Getattr(n, "value"), NULL); - if (quote != '\0') { - Printf(get, "%c", quote); + if (quote != '\0') { + Printf(get, "%c", quote); + } } Printv(get, ";\n", NULL); + Setattr(n, "wrap:action", get); String *sname = Copy(symname); @@ -3976,7 +4023,7 @@ private: Printv(f_c_directors, director_sig, NULL); if (!gccgo_flag) { - Printv(f_c_directors, " struct { intgo p; } a;\n", NULL); + Printv(f_c_directors, " struct { intgo p; } SWIGSTRUCTPACKED a;\n", NULL); Printv(f_c_directors, " a.p = go_val;\n", NULL); Printv(f_c_directors, " crosscall2(", wname, ", &a, (int) sizeof a);\n", NULL); @@ -4148,7 +4195,6 @@ private: Wrapper *dummy = NewWrapper(); emit_attach_parmmaps(parms, dummy); - DelWrapper(dummy); Swig_typemap_attach_parms("gotype", parms, NULL); Swig_typemap_attach_parms("imtype", parms, NULL); @@ -4205,6 +4251,8 @@ private: Swig_typemap_attach_parms("goin", parms, dummy); Swig_typemap_attach_parms("goargout", parms, dummy); + DelWrapper(dummy); + if (!is_ignored) { // We use an interface to see if this method is defined in Go. Printv(f_go_wrappers, "type ", interface_name, " interface {\n", NULL); @@ -5110,7 +5158,7 @@ private: Delete(rname); } - Printv(w->code, " } swig_a;\n", NULL); + Printv(w->code, " } SWIGSTRUCTPACKED swig_a;\n", NULL); Printv(w->code, " swig_a.go_val = go_val;\n", NULL); p = parms; diff --git a/Source/Modules/guile.cxx b/Source/Modules/guile.cxx index 61f79c1d0..7b42ff94f 100644 --- a/Source/Modules/guile.cxx +++ b/Source/Modules/guile.cxx @@ -322,8 +322,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGGUILE\n"); + Printf(f_runtime, "\n\n#ifndef SWIGGUILE\n#define SWIGGUILE\n#endif\n\n"); /* Write out directives and declarations */ diff --git a/Source/Modules/interface.cxx b/Source/Modules/interface.cxx new file mode 100644 index 000000000..f6d4c955b --- /dev/null +++ b/Source/Modules/interface.cxx @@ -0,0 +1,183 @@ +/* ----------------------------------------------------------------------------- + * This file is part of SWIG, which is licensed as a whole under version 3 + * (or any later version) of the GNU General Public License. Some additional + * terms also apply to certain portions of SWIG. The full details of the SWIG + * license and copyrights can be found in the LICENSE and COPYRIGHT files + * included with the SWIG source code as distributed by the SWIG developers + * and at http://www.swig.org/legal.html. + * + * interface.cxx + * + * This module contains support for the interface feature. + * This feature is used in language modules where the target language does not + * naturally support C++ style multiple inheritance, but does support inheritance + * from multiple interfaces. + * ----------------------------------------------------------------------------- */ + +#include "swigmod.h" + +static bool interface_feature_enabled = false; + +/* ----------------------------------------------------------------------------- + * collect_interface_methods() + * + * Create a list of all the methods from the base classes of class n that are + * marked as an interface. The resulting list is thus the list of methods that + * need to be implemented in order for n to be non-abstract. + * ----------------------------------------------------------------------------- */ + +static List *collect_interface_methods(Node *n) { + List *methods = NewList(); + if (Hash *bases = Getattr(n, "interface:bases")) { + List *keys = Keys(bases); + for (Iterator base = First(keys); base.item; base = Next(base)) { + Node *cls = Getattr(bases, base.item); + if (cls == n) + continue; + for (Node *child = firstChild(cls); child; child = nextSibling(child)) { + if (Cmp(nodeType(child), "cdecl") == 0) { + if (GetFlag(child, "feature:ignore") || Getattr(child, "interface:owner")) + continue; // skip methods propagated to bases + Node *m = Copy(child); + set_nextSibling(m, NIL); + set_previousSibling(m, NIL); + Setattr(m, "interface:owner", cls); + Append(methods, m); + } + } + } + Delete(keys); + } + return methods; +} + +/* ----------------------------------------------------------------------------- + * collect_interface_bases + * ----------------------------------------------------------------------------- */ + +static void collect_interface_bases(Hash *bases, Node *n) { + if (Getattr(n, "feature:interface")) { + String *name = Getattr(n, "interface:name"); + if (!Getattr(bases, name)) + Setattr(bases, name, n); + } + + if (List *baselist = Getattr(n, "bases")) { + for (Iterator base = First(baselist); base.item; base = Next(base)) { + if (!GetFlag(base.item, "feature:ignore")) { + if (Getattr(base.item, "feature:interface")) + collect_interface_bases(bases, base.item); + } + } + } +} + +/* ----------------------------------------------------------------------------- + * collect_interface_base_classes() + * + * Create a hash containing all the classes up the inheritance hierarchy + * marked with feature:interface (including this class n). + * Stops going up the inheritance chain as soon as a class is found without + * feature:interface. + * The idea is to find all the base interfaces that a class must implement. + * ----------------------------------------------------------------------------- */ + +static void collect_interface_base_classes(Node *n) { + if (Getattr(n, "feature:interface")) { + // check all bases are also interfaces + if (List *baselist = Getattr(n, "bases")) { + for (Iterator base = First(baselist); base.item; base = Next(base)) { + if (!GetFlag(base.item, "feature:ignore")) { + if (!Getattr(base.item, "feature:interface")) { + Swig_error(Getfile(n), Getline(n), "Base class '%s' of '%s' is not similarly marked as an interface.\n", SwigType_namestr(Getattr(base.item, "name")), SwigType_namestr(Getattr(n, "name"))); + SWIG_exit(EXIT_FAILURE); + } + } + } + } + } + + Hash *interface_bases = NewHash(); + collect_interface_bases(interface_bases, n); + if (Len(interface_bases) == 0) + Delete(interface_bases); + else + Setattr(n, "interface:bases", interface_bases); +} + +/* ----------------------------------------------------------------------------- + * process_interface_name() + * ----------------------------------------------------------------------------- */ + +static void process_interface_name(Node *n) { + if (Getattr(n, "feature:interface")) { + String *interface_name = Getattr(n, "feature:interface:name"); + if (!Len(interface_name)) { + Swig_error(Getfile(n), Getline(n), "The interface feature for '%s' is missing the name attribute.\n", SwigType_namestr(Getattr(n, "name"))); + SWIG_exit(EXIT_FAILURE); + } + if (Strchr(interface_name, '%')) { + String *name = NewStringf(interface_name, Getattr(n, "sym:name")); + Setattr(n, "interface:name", name); + } else { + Setattr(n, "interface:name", interface_name); + } + } +} + +/* ----------------------------------------------------------------------------- + * Swig_interface_propagate_methods() + * + * Find all the base classes marked as an interface (with feature:interface) for + * class node n. For each of these, add all of its methods as methods of n so that + * n is not abstract. If class n is also marked as an interface, it will remain + * abstract and not have any methods added. + * ----------------------------------------------------------------------------- */ + +void Swig_interface_propagate_methods(Node *n) { + if (interface_feature_enabled) { + process_interface_name(n); + collect_interface_base_classes(n); + List *methods = collect_interface_methods(n); + bool is_interface = Getattr(n, "feature:interface") != 0; + for (Iterator mi = First(methods); mi.item; mi = Next(mi)) { + if (!is_interface && GetFlag(mi.item, "abstract")) + continue; + String *this_decl = Getattr(mi.item, "decl"); + String *this_decl_resolved = SwigType_typedef_resolve_all(this_decl); + bool identically_overloaded_method = false; // true when a base class' method is implemented in n + if (SwigType_isfunction(this_decl_resolved)) { + String *name = Getattr(mi.item, "name"); + for (Node *child = firstChild(n); child; child = nextSibling(child)) { + if (Getattr(child, "interface:owner")) + break; // at the end of the list are newly appended methods + if (checkAttribute(child, "name", name)) { + String *decl = SwigType_typedef_resolve_all(Getattr(child, "decl")); + identically_overloaded_method = Strcmp(decl, this_decl_resolved) == 0; + Delete(decl); + if (identically_overloaded_method) + break; + } + } + } + Delete(this_decl_resolved); + if (!identically_overloaded_method) { + // TODO: Fix if the method is overloaded with different arguments / has default args + appendChild(n, mi.item); + } else { + Delete(mi.item); + } + } + Delete(methods); + } +} + +/* ----------------------------------------------------------------------------- + * Swig_interface_feature_enable() + * + * Turn on interface feature support + * ----------------------------------------------------------------------------- */ + +void Swig_interface_feature_enable() { + interface_feature_enabled = true; +} diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index 95348f234..04a018133 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -56,6 +56,7 @@ class JAVA:public Language { String *imclass_class_code; // intermediary class code String *proxy_class_def; String *proxy_class_code; + String *interface_class_code; // if %feature("interface") was declared for a class, here goes the interface declaration String *module_class_code; String *proxy_class_name; // proxy class name String *full_proxy_class_name;// fully qualified proxy class name when using nspace feature, otherwise same as proxy_class_name @@ -131,6 +132,7 @@ public: imclass_class_code(NULL), proxy_class_def(NULL), proxy_class_code(NULL), + interface_class_code(NULL), module_class_code(NULL), proxy_class_name(NULL), full_proxy_class_name(NULL), @@ -219,10 +221,14 @@ public: String *nspace = Getattr(n, "sym:nspace"); String *symname = Copy(Getattr(n, "sym:name")); if (symname && !GetFlag(n, "feature:flatnested")) { - for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { - Push(symname, jnidescriptor ? "$" : "."); - Push(symname, Getattr(outer_class, "sym:name")); - } + for (Node *outer_class = Getattr(n, "nested:outer"); outer_class; outer_class = Getattr(outer_class, "nested:outer")) { + if (String* name = Getattr(outer_class, "sym:name")) { + Push(symname, jnidescriptor ? "$" : "."); + Push(symname, name); + } + else + return NULL; + } } if (nspace) { if (package && !jnidescriptor) @@ -329,6 +335,7 @@ public: SWIG_config_file("java.swg"); allow_overloading(); + Swig_interface_feature_enable(); } /* --------------------------------------------------------------------- @@ -452,7 +459,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n#define SWIGJAVA\n"); + Printf(f_runtime, "\n\n#ifndef SWIGJAVA\n#define SWIGJAVA\n#endif\n\n"); if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); @@ -1347,8 +1354,10 @@ public: // Add extra indentation Replaceall(enum_code, "\n", "\n "); Replaceall(enum_code, " \n", "\n"); - - Printv(proxy_class_constants_code, " ", enum_code, "\n\n", NIL); + if (GetFlag(getCurrentClass(), "feature:interface")) + Printv(interface_class_code, " ", enum_code, "\n\n", NIL); + else + Printv(proxy_class_constants_code, " ", enum_code, "\n\n", NIL); } else { // Global enums are defined in their own file String *output_directory = outputDirectory(nspace); @@ -1436,7 +1445,7 @@ public: const char *val = Equal(Getattr(n, "enumvalue"), "true") ? "1" : "0"; Setattr(n, "enumvalue", val); } else if (swigtype == T_CHAR) { - String *val = NewStringf("'%s'", Getattr(n, "enumvalue")); + String *val = NewStringf("'%(escape)s'", Getattr(n, "enumvalue")); Setattr(n, "enumvalue", val); Delete(val); } @@ -1567,6 +1576,7 @@ public: virtual int constantWrapper(Node *n) { String *symname = Getattr(n, "sym:name"); SwigType *t = Getattr(n, "type"); + SwigType *valuetype = Getattr(n, "valuetype"); ParmList *l = Getattr(n, "parms"); String *tm; String *return_type = NewString(""); @@ -1668,8 +1678,8 @@ public: } else { // Alternative constant handling will use the C syntax to make a true Java constant and hope that it compiles as Java code if (Getattr(n, "wrappedasconstant")) { - if (SwigType_type(t) == T_CHAR) - Printf(constants_code, "\'%s\';\n", Getattr(n, "staticmembervariableHandler:value")); + if (SwigType_type(valuetype) == T_CHAR) + Printf(constants_code, "\'%(escape)s\';\n", Getattr(n, "staticmembervariableHandler:value")); else Printf(constants_code, "%s;\n", Getattr(n, "staticmembervariableHandler:value")); } else { @@ -1819,6 +1829,125 @@ public: return Language::pragmaDirective(n); } + /* ----------------------------------------------------------------------------- + * getQualifiedInterfaceName() + * ----------------------------------------------------------------------------- */ + + String *getQualifiedInterfaceName(Node *n) { + String *ret = Getattr(n, "interface:qname"); + if (!ret) { + String *nspace = Getattr(n, "sym:nspace"); + String *symname = Getattr(n, "interface:name"); + if (nspace) { + if (package) + ret = NewStringf("%s.%s.%s", package, nspace, symname); + else + ret = NewStringf("%s.%s", nspace, symname); + } else { + ret = Copy(symname); + } + Setattr(n, "interface:qname", ret); + } + return ret; + } + + /* ----------------------------------------------------------------------------- + * getInterfaceName() + * ----------------------------------------------------------------------------- */ + + String *getInterfaceName(SwigType *t, bool qualified) { + String *interface_name = NULL; + if (proxy_flag) { + Node *n = classLookup(t); + if (n && Getattr(n, "interface:name")) + interface_name = qualified ? getQualifiedInterfaceName(n) : Getattr(n, "interface:name"); + } + return interface_name; + } + + /* ----------------------------------------------------------------------------- + * addInterfaceNameAndUpcasts() + * ----------------------------------------------------------------------------- */ + + void addInterfaceNameAndUpcasts(SwigType *smart, String *interface_list, String *interface_upcasts, Hash *base_list, String *c_classname) { + List *keys = Keys(base_list); + for (Iterator it = First(keys); it.item; it = Next(it)) { + Node *base = Getattr(base_list, it.item); + String *c_baseclass = SwigType_namestr(Getattr(base, "name")); + String *interface_name = Getattr(base, "interface:name"); + if (Len(interface_list)) + Append(interface_list, ", "); + Append(interface_list, interface_name); + + Node *attributes = NewHash(); + String *interface_code = Copy(typemapLookup(base, "javainterfacecode", Getattr(base, "classtypeobj"), WARN_JAVA_TYPEMAP_INTERFACECODE_UNDEF, attributes)); + String *cptr_method_name = 0; + if (interface_code) { + Replaceall(interface_code, "$interfacename", interface_name); + Printv(interface_upcasts, interface_code, NIL); + cptr_method_name = Copy(Getattr(attributes, "tmap:javainterfacecode:cptrmethod")); + } + if (!cptr_method_name) + cptr_method_name = NewStringf("%s_GetInterfaceCPtr", interface_name); + Replaceall(cptr_method_name, ".", "_"); + Replaceall(cptr_method_name, "$interfacename", interface_name); + + String *upcast_method_name = Swig_name_member(getNSpace(), proxy_class_name, cptr_method_name); + upcastsCode(smart, upcast_method_name, c_classname, c_baseclass); + Delete(upcast_method_name); + Delete(cptr_method_name); + Delete(interface_code); + Delete(c_baseclass); + } + Delete(keys); + } + + /* ----------------------------------------------------------------------------- + * upcastsCode() + * + * Add code for C++ casting to base class + * ----------------------------------------------------------------------------- */ + + void upcastsCode(SwigType *smart, String *upcast_method_name, String *c_classname, String *c_baseclass) { + String *jniname = makeValidJniName(upcast_method_name); + String *wname = Swig_name_wrapper(jniname); + Printf(imclass_cppcasts_code, " public final static native long %s(long jarg1);\n", upcast_method_name); + if (smart) { + SwigType *bsmart = Copy(smart); + SwigType *rclassname = SwigType_typedef_resolve_all(c_classname); + SwigType *rbaseclass = SwigType_typedef_resolve_all(c_baseclass); + Replaceall(bsmart, rclassname, rbaseclass); + Delete(rclassname); + Delete(rbaseclass); + String *smartnamestr = SwigType_namestr(smart); + String *bsmartnamestr = SwigType_namestr(bsmart); + Printv(upcasts_code, + "SWIGEXPORT jlong JNICALL ", wname, "(JNIEnv *jenv, jclass jcls, jlong jarg1) {\n", + " jlong baseptr = 0;\n" + " ", smartnamestr, " *argp1;\n" + " (void)jenv;\n" + " (void)jcls;\n" + " argp1 = *(", smartnamestr, " **)&jarg1;\n" + " *(", bsmartnamestr, " **)&baseptr = argp1 ? new ", bsmartnamestr, "(*argp1) : 0;\n" + " return baseptr;\n" + "}\n", "\n", NIL); + Delete(bsmartnamestr); + Delete(smartnamestr); + Delete(bsmart); + } else { + Printv(upcasts_code, + "SWIGEXPORT jlong JNICALL ", wname, "(JNIEnv *jenv, jclass jcls, jlong jarg1) {\n", + " jlong baseptr = 0;\n" + " (void)jenv;\n" + " (void)jcls;\n" + " *(", c_baseclass, " **)&baseptr = *(", c_classname, " **)&jarg1;\n" + " return baseptr;\n" + "}\n", "\n", NIL); + } + Delete(wname); + Delete(jniname); + } + /* ----------------------------------------------------------------------------- * emitProxyClassDefAndCPPCasts() * ----------------------------------------------------------------------------- */ @@ -1828,9 +1957,12 @@ public: String *c_baseclass = NULL; String *baseclass = NULL; String *c_baseclassname = NULL; + String *interface_list = NewStringEmpty(); + String *interface_upcasts = NewStringEmpty(); SwigType *typemap_lookup_type = Getattr(n, "classtypeobj"); bool feature_director = Swig_directorclass(n) ? true : false; bool has_outerclass = Getattr(n, "nested:outer") != 0 && !GetFlag(n, "feature:flatnested"); + SwigType *smart = Swig_cparse_smartptr(n); // Inheritance from pure Java classes Node *attributes = NewHash(); @@ -1843,32 +1975,31 @@ public: if (!purebase_replace) { List *baselist = Getattr(n, "bases"); if (baselist) { - Iterator base = First(baselist); - while (base.item && GetFlag(base.item, "feature:ignore")) { - base = Next(base); - } - if (base.item) { - c_baseclassname = Getattr(base.item, "name"); - baseclass = Copy(getProxyName(c_baseclassname)); - if (baseclass) - c_baseclass = SwigType_namestr(Getattr(base.item, "name")); - base = Next(base); - /* Warn about multiple inheritance for additional base class(es) */ - while (base.item) { - if (GetFlag(base.item, "feature:ignore")) { - base = Next(base); - continue; - } - String *proxyclassname = Getattr(n, "classtypeobj"); - String *baseclassname = Getattr(base.item, "name"); - Swig_warning(WARN_JAVA_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Java.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); - base = Next(base); - } - } + Iterator base = First(baselist); + while (base.item) { + if (!(GetFlag(base.item, "feature:ignore") || Getattr(base.item, "feature:interface"))) { + String *baseclassname = Getattr(base.item, "name"); + if (!c_baseclassname) { + c_baseclassname = baseclassname; + baseclass = Copy(getProxyName(baseclassname)); + if (baseclass) + c_baseclass = SwigType_namestr(baseclassname); + } else { + /* Warn about multiple inheritance for additional base class(es) */ + String *proxyclassname = Getattr(n, "classtypeobj"); + Swig_warning(WARN_JAVA_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), + "Warning for %s, base %s ignored. Multiple inheritance is not supported in Java.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); + } + } + base = Next(base); + } } } + Hash *interface_bases = Getattr(n, "interface:bases"); + if (interface_bases) + addInterfaceNameAndUpcasts(smart, interface_list, interface_upcasts, interface_bases, c_classname); + bool derived = baseclass && getProxyName(c_baseclassname); if (derived && purebase_notderived) pure_baseclass = empty_string; @@ -1883,7 +2014,7 @@ public: Swig_error(Getfile(n), Getline(n), "The javabase typemap for proxy %s must contain just one of the 'replace' or 'notderived' attributes.\n", typemap_lookup_type); } else if (Len(pure_baseclass) > 0 && Len(baseclass) > 0) { Swig_warning(WARN_JAVA_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Java. " + "Warning for %s, base %s ignored. Multiple inheritance is not supported in Java. " "Perhaps you need one of the 'replace' or 'notderived' attributes in the javabase typemap?\n", typemap_lookup_type, pure_baseclass); } @@ -1899,6 +2030,10 @@ public: Delete(doxygen_comments); } + if (*Char(interface_list) && *Char(pure_interfaces)) + Append(interface_list, ", "); + Append(interface_list, pure_interfaces); + // Start writing the proxy class if (!has_outerclass) // Import statements Printv(proxy_class_def, typemapLookup(n, "javaimports", typemap_lookup_type, WARN_NONE),"\n", NIL); @@ -1906,8 +2041,8 @@ public: Printv(proxy_class_def, "static ", NIL); // C++ nested classes correspond to static java classes Printv(proxy_class_def, typemapLookup(n, "javaclassmodifiers", typemap_lookup_type, WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF), // Class modifiers " $javaclassname", // Class name and bases - (*Char(wanted_base)) ? " extends " : "", wanted_base, *Char(pure_interfaces) ? // Pure Java interfaces - " implements " : "", pure_interfaces, " {", derived ? typemapLookup(n, "javabody_derived", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF) : // main body of class + (*Char(wanted_base)) ? " extends " : "", wanted_base, *Char(interface_list) ? // Pure Java interfaces + " implements " : "", interface_list, " {", derived ? typemapLookup(n, "javabody_derived", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF) : // main body of class typemapLookup(n, "javabody", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF), // main body of class NIL); @@ -1950,6 +2085,8 @@ public: if (*Char(destruct)) Printv(proxy_class_def, "\n ", destruct_methodmodifiers, " void ", destruct_methodname, "()", destructor_throws_clause, " ", destruct, "\n", NIL); } + if (*Char(interface_upcasts)) + Printv(proxy_class_def, interface_upcasts, NIL); /* Insert directordisconnect typemap, if this class has directors enabled */ /* Also insert the swigTakeOwnership and swigReleaseOwnership methods */ @@ -1971,6 +2108,8 @@ public: Delete(take_jnicall); } + Delete(interface_upcasts); + Delete(interface_list); Delete(attributes); Delete(destruct); @@ -1978,66 +2117,80 @@ public: Printv(proxy_class_def, typemapLookup(n, "javacode", typemap_lookup_type, WARN_NONE), // extra Java code "\n", NIL); - // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy) if (derived) { - String *smartptr = Getattr(n, "feature:smartptr"); - String *upcast_method = Swig_name_member(getNSpace(), getClassPrefix(), smartptr != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); - String *jniname = makeValidJniName(upcast_method); - String *wname = Swig_name_wrapper(jniname); - Printf(imclass_cppcasts_code, " public final static native long %s(long jarg1);\n", upcast_method); - if (smartptr) { - SwigType *spt = Swig_cparse_type(smartptr); - if (spt) { - SwigType *smart = SwigType_typedef_resolve_all(spt); - Delete(spt); - SwigType *bsmart = Copy(smart); - SwigType *rclassname = SwigType_typedef_resolve_all(c_classname); - SwigType *rbaseclass = SwigType_typedef_resolve_all(c_baseclass); - Replaceall(bsmart, rclassname, rbaseclass); - Delete(rclassname); - Delete(rbaseclass); - String *smartnamestr = SwigType_namestr(smart); - String *bsmartnamestr = SwigType_namestr(bsmart); - Printv(upcasts_code, - "SWIGEXPORT jlong JNICALL ", wname, "(JNIEnv *jenv, jclass jcls, jlong jarg1) {\n", - " jlong baseptr = 0;\n" - " ", smartnamestr, " *argp1;\n" - " (void)jenv;\n" - " (void)jcls;\n" - " argp1 = *(", smartnamestr, " **)&jarg1;\n" - " *(", bsmartnamestr, " **)&baseptr = argp1 ? new ", bsmartnamestr, "(*argp1) : 0;\n" - " return baseptr;\n" - "}\n", "\n", NIL); - Delete(bsmartnamestr); - Delete(smartnamestr); - Delete(bsmart); - } else { - Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, c_classname); - } - } else { - Printv(upcasts_code, - "SWIGEXPORT jlong JNICALL ", wname, "(JNIEnv *jenv, jclass jcls, jlong jarg1) {\n", - " jlong baseptr = 0;\n" - " (void)jenv;\n" - " (void)jcls;\n" - " *(", c_baseclass, " **)&baseptr = *(", c_classname, " **)&jarg1;\n" - " return baseptr;\n" - "}\n", "\n", NIL); - } - Delete(wname); - Delete(jniname); - Delete(upcast_method); + String *upcast_method_name = Swig_name_member(getNSpace(), getClassPrefix(), smart != 0 ? "SWIGSmartPtrUpcast" : "SWIGUpcast"); + upcastsCode(smart, upcast_method_name, c_classname, c_baseclass); + Delete(upcast_method_name); } + + Delete(smart); Delete(baseclass); } /* ---------------------------------------------------------------------- - * classHandler() + * emitInterfaceDeclaration() * ---------------------------------------------------------------------- */ - virtual int classHandler(Node *n) { + void emitInterfaceDeclaration(Node *n, String *interface_name, File *f_interface, String *nspace) { + if (package || nspace) { + Printf(f_interface, "package "); + if (package) + Printv(f_interface, package, nspace ? "." : "", NIL); + if (nspace) + Printv(f_interface, nspace, NIL); + Printf(f_interface, ";\n"); + } + Printv(f_interface, typemapLookup(n, "javaimports", Getattr(n, "classtypeobj"), WARN_NONE), "\n", NIL); + Printf(f_interface, "public interface %s", interface_name); + if (List *baselist = Getattr(n, "bases")) { + String *bases = 0; + for (Iterator base = First(baselist); base.item; base = Next(base)) { + if (GetFlag(base.item, "feature:ignore") || !Getattr(base.item, "feature:interface")) + continue; // TODO: warn about skipped non-interface bases + String *base_iname = Getattr(base.item, "interface:name"); + if (!bases) + bases = Copy(base_iname); + else { + Append(bases, ", "); + Append(bases, base_iname); + } + } + if (bases) { + Printv(f_interface, " extends ", bases, NIL); + Delete(bases); + } + } + Printf(f_interface, " {\n"); + + Node *attributes = NewHash(); + String *interface_code = Copy(typemapLookup(n, "javainterfacecode", Getattr(n, "classtypeobj"), WARN_JAVA_TYPEMAP_INTERFACECODE_UNDEF, attributes)); + if (interface_code) { + String *interface_declaration = Copy(Getattr(attributes, "tmap:javainterfacecode:declaration")); + if (interface_declaration) { + Replaceall(interface_declaration, "$interfacename", interface_name); + Printv(f_interface, interface_declaration, NIL); + Delete(interface_declaration); + } + Delete(interface_code); + } + } + + /* ---------------------------------------------------------------------- + * classDeclaration() + * ---------------------------------------------------------------------- */ + + int classDeclaration(Node *n) { + return Language::classDeclaration(n); + } + + /* ---------------------------------------------------------------------- + * classHandler() + * ---------------------------------------------------------------------- */ + + virtual int classHandler(Node *n) { File *f_proxy = NULL; + File *f_interface = NULL; String *old_proxy_class_name = proxy_class_name; String *old_full_proxy_class_name = full_proxy_class_name; String *old_full_imclass_name = full_imclass_name; @@ -2047,6 +2200,8 @@ public: String *old_proxy_class_def = proxy_class_def; String *old_proxy_class_code = proxy_class_code; bool has_outerclass = Getattr(n, "nested:outer") && !GetFlag(n, "feature:flatnested"); + String *old_interface_class_code = interface_class_code; + interface_class_code = 0; if (proxy_flag) { proxy_class_name = NewString(Getattr(n, "sym:name")); @@ -2087,17 +2242,21 @@ public: } } + String *interface_name = Getattr(n, "feature:interface") ? Getattr(n, "interface:name") : 0; if (outerClassesPrefix) { String *fnspace = nspace ? NewStringf("%s.%s", nspace, outerClassesPrefix) : outerClassesPrefix; if (!addSymbol(proxy_class_name, n, fnspace)) return SWIG_ERROR; + if (interface_name && !addInterfaceSymbol(interface_name, n, fnspace)) + return SWIG_ERROR; if (nspace) Delete(fnspace); Delete(outerClassesPrefix); - } - else { + } else { if (!addSymbol(proxy_class_name, n, nspace)) return SWIG_ERROR; + if (interface_name && !addInterfaceSymbol(interface_name, n, nspace)) + return SWIG_ERROR; } // Each outer proxy class goes into a separate file @@ -2133,11 +2292,27 @@ public: destructor_call = NewString(""); destructor_throws_clause = NewString(""); proxy_class_constants_code = NewString(""); + + if (Getattr(n, "feature:interface")) { + interface_class_code = NewString(""); + String *output_directory = outputDirectory(nspace); + String *filen = NewStringf("%s%s.java", output_directory, interface_name); + f_interface = NewFile(filen, "w", SWIG_output_files()); + if (!f_interface) { + FileErrorDisplay(filen); + SWIG_exit(EXIT_FAILURE); + } + Append(filenames_list, filen); // file name ownership goes to the list + emitBanner(f_interface); + emitInterfaceDeclaration(n, interface_name, interface_class_code, nspace); + Delete(filen); + Delete(output_directory); + } } + Language::classHandler(n); if (proxy_flag) { - emitProxyClassDefAndCPPCasts(n); String *javaclazzname = Swig_name_member(getNSpace(), getClassPrefix(), ""); // mangled full proxy class name @@ -2145,18 +2320,22 @@ public: Replaceall(proxy_class_def, "$javaclassname", proxy_class_name); Replaceall(proxy_class_code, "$javaclassname", proxy_class_name); Replaceall(proxy_class_constants_code, "$javaclassname", proxy_class_name); + Replaceall(interface_class_code, "$javaclassname", proxy_class_name); Replaceall(proxy_class_def, "$javaclazzname", javaclazzname); Replaceall(proxy_class_code, "$javaclazzname", javaclazzname); Replaceall(proxy_class_constants_code, "$javaclazzname", javaclazzname); + Replaceall(interface_class_code, "$javaclazzname", javaclazzname); Replaceall(proxy_class_def, "$module", module_class_name); Replaceall(proxy_class_code, "$module", module_class_name); Replaceall(proxy_class_constants_code, "$module", module_class_name); + Replaceall(interface_class_code, "$module", module_class_name); Replaceall(proxy_class_def, "$imclassname", full_imclass_name); Replaceall(proxy_class_code, "$imclassname", full_imclass_name); Replaceall(proxy_class_constants_code, "$imclassname", full_imclass_name); + Replaceall(interface_class_code, "$imclassname", full_imclass_name); if (!has_outerclass) Printv(f_proxy, proxy_class_def, proxy_class_code, NIL); @@ -2221,8 +2400,16 @@ public: Delete(downcast_method); } + if (f_interface) { + Printv(f_interface, interface_class_code, "}\n", NIL); + Delete(f_interface); + f_interface = 0; + } + emitDirectorExtraMethods(n); + Delete(interface_class_code); + interface_class_code = old_interface_class_code; Delete(javaclazzname); Delete(proxy_class_name); proxy_class_name = old_proxy_class_name; @@ -2314,6 +2501,8 @@ public: bool setter_flag = false; String *pre_code = NewString(""); String *post_code = NewString(""); + bool is_interface = Getattr(parentNode(n), "feature:interface") != 0 + && !static_flag && Getattr(n, "interface:owner") == 0; if (!proxy_flag) return; @@ -2372,6 +2561,9 @@ public: if (static_flag) Printf(function_code, "static "); Printf(function_code, "%s %s(", return_type, proxy_function_name); + + if (is_interface) + Printf(interface_class_code, " %s %s(", return_type, proxy_function_name); Printv(imcall, full_imclass_name, ".$imfuncname(", NIL); if (!static_flag) { @@ -2459,10 +2651,15 @@ public: } /* Add parameter to proxy function */ - if (gencomma >= 2) + if (gencomma >= 2) { Printf(function_code, ", "); + if (is_interface) + Printf(interface_class_code, ", "); + } gencomma = 2; Printf(function_code, "%s %s", param_type, arg); + if (is_interface) + Printf(interface_class_code, "%s %s", param_type, arg); if (prematureGarbageCollectionPreventionParameter(pt, p)) { String *pgcppname = Getattr(p, "tmap:javain:pgcppname"); @@ -2484,6 +2681,8 @@ public: Printf(imcall, ")"); Printf(function_code, ")"); + if (is_interface) + Printf(interface_class_code, ");\n"); // Transform return type used in JNI function (in intermediary class) to type used in Java wrapper function (in proxy class) if ((tm = Swig_typemap_lookup("javaout", n, "", 0))) { @@ -3206,6 +3405,50 @@ public: substitution_performed = true; Delete(classnametype); } + if (Strstr(tm, "$javainterfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$javainterfacename", jnidescriptor, true); + substitution_performed = true; + Delete(interfacenametype); + } + if (Strstr(tm, "$*javainterfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + Delete(SwigType_pop(interfacenametype)); + if (Len(interfacenametype) > 0) { + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$*javainterfacename", jnidescriptor, true); + substitution_performed = true; + } + Delete(interfacenametype); + } + if (Strstr(tm, "$&javainterfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + SwigType_add_pointer(interfacenametype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$&javainterfacename", jnidescriptor, true); + substitution_performed = true; + Delete(interfacenametype); + } + if (Strstr(tm, "$interfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$interfacename", jnidescriptor, false); + substitution_performed = true; + Delete(interfacenametype); + } + if (Strstr(tm, "$*interfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + Delete(SwigType_pop(interfacenametype)); + if (Len(interfacenametype) > 0) { + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$*interfacename", jnidescriptor, false); + substitution_performed = true; + } + Delete(interfacenametype); + } + if (Strstr(tm, "$&interfacename")) { + SwigType *interfacenametype = Copy(strippedtype); + SwigType_add_pointer(interfacenametype); + substituteInterfacenameSpecialVariable(interfacenametype, tm, "$&interfacename", jnidescriptor, false); + substitution_performed = true; + Delete(interfacenametype); + } Delete(strippedtype); Delete(type); @@ -3254,6 +3497,24 @@ public: Delete(replacementname); } + /* ----------------------------------------------------------------------------- + * substituteInterfacenameSpecialVariable() + * ----------------------------------------------------------------------------- */ + + void substituteInterfacenameSpecialVariable(SwigType *interfacenametype, String *tm, const char *interfacenamespecialvariable, bool jnidescriptor, bool qualified) { + + String *interfacename = getInterfaceName(interfacenametype/*, jnidescriptor*/, qualified); + if (interfacename) { + String *replacementname = Copy(interfacename); + + if (jnidescriptor) + Replaceall(replacementname,".","/"); + Replaceall(tm, interfacenamespecialvariable, replacementname); + + Delete(replacementname); + } + } + /* ----------------------------------------------------------------------------- * emitTypeWrapperClass() * ----------------------------------------------------------------------------- */ @@ -3412,7 +3673,7 @@ public: * ----------------------------------------------------------------------------- */ String *prematureGarbageCollectionPreventionParameter(SwigType *t, Parm *p) { - String *proxyClassName = 0; + String *pgcpp_java_type = 0; String *jtype = NewString(Getattr(p, "tmap:jtype")); // Strip C comments @@ -3429,11 +3690,9 @@ public: if (Cmp(jtype, "long") == 0) { if (proxy_flag) { if (!GetFlag(p, "tmap:jtype:nopgcpp") && !nopgcpp_flag) { - String *proxyname = getProxyName(t); - if (proxyname) { - // Found a struct/class parameter passed by value, reference, pointer, or pointer reference - proxyClassName = proxyname; - } else { + String *interface_name = getInterfaceName(t, true); + pgcpp_java_type = interface_name ? interface_name : getProxyName(t); + if (!pgcpp_java_type) { // Look for proxy class parameters passed to C++ layer using non-default typemaps, ie not one of above types String *jstype = NewString(Getattr(p, "tmap:jstype")); if (jstype) { @@ -3455,7 +3714,7 @@ public: if (cls && !Getattr(cls, "feature:ignore")) { String *symname = Getattr(cls, "sym:name"); if (symname && Strcmp(symname, jstype) == 0) { - proxyClassName = symname; + pgcpp_java_type = symname; } } } @@ -3467,7 +3726,7 @@ public: } } Delete(jtype); - return proxyClassName; + return pgcpp_java_type; } /* ----------------------------------------------------------------------------- @@ -3619,7 +3878,7 @@ public: "SWIGEXPORT void JNICALL Java_%s%s_%s(JNIEnv *jenv, jclass jcls, jobject jself, jlong objarg, jboolean jswig_mem_own, " "jboolean jweak_global) {\n", jnipackage, jni_imclass_name, swig_director_connect_jni); - if (Len(smartptr)) { + if (smartptr) { Printf(code_wrap->code, " %s *obj = *((%s **)&objarg);\n", smartptr, smartptr); Printf(code_wrap->code, " (void)jcls;\n"); Printf(code_wrap->code, " // Keep a local instance of the smart pointer around while we are using the raw pointer\n"); diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 179ffb28c..4e7a7912f 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1100,7 +1100,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { * ----------------------------------------------------------------------------- */ int JSEmitter::emitConstant(Node *n) { - // HACK: somehow it happened under OSX that before everything started + // HACK: somehow it happened under Mac OS X that before everything started // a lot of SWIG internal constants were emitted // This didn't happen on other platforms yet... // we ignore those premature definitions @@ -1354,6 +1354,11 @@ void JSEmitter::emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params) { } } + /* See if there is any return cleanup code */ + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Printf(wrapper->code, "%s\n", tm); + Delete(tm); + } } int JSEmitter::switchNamespace(Node *n) { diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 8869c30fb..a2b9019de 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -873,7 +873,7 @@ int Language::cDeclaration(Node *n) { } else { // Found an unignored templated method that has an empty template instantiation (%template()) // Ignore it unless it has been %rename'd - if (Strncmp(symname, "__dummy_", 8) == 0) { + if (Strncmp(symname, "__dummy_", 8) == 0 && Cmp(storage, "typedef") != 0) { SetFlag(n, "feature:ignore"); Swig_warning(WARN_LANG_TEMPLATE_METHOD_IGNORE, input_file, line_number, "%%template() contains no name. Template method ignored: %s\n", Swig_name_decl(n)); @@ -1652,6 +1652,9 @@ int Language::externDeclaration(Node *n) { * ---------------------------------------------------------------------- */ int Language::enumDeclaration(Node *n) { + if (CurrentClass && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + String *oldNSpace = NSpace; NSpace = Getattr(n, "sym:nspace"); @@ -3133,6 +3136,31 @@ int Language::addSymbol(const String *s, const Node *n, const_String_or_char_ptr return 1; } +/* ----------------------------------------------------------------------------- + * Language::addInterfaceSymbol() + * + * Adds a symbol entry into the target language symbol tables - for the interface + * feature only. + * Returns 1 if the symbol is added successfully. + * The scope is as per addSymbol. + * ----------------------------------------------------------------------------- */ + +int Language::addInterfaceSymbol(const String *interface_name, Node *n, const_String_or_char_ptr scope) { + if (interface_name) { + Node *existing_symbol = symbolLookup(interface_name, scope); + if (existing_symbol) { + String *proxy_class_name = Getattr(n, "sym:name"); + Swig_error(input_file, line_number, "The interface feature name '%s' for proxy class '%s' is already defined in the generated target language module in scope '%s'.\n", + interface_name, proxy_class_name, scope); + Swig_error(Getfile(existing_symbol), Getline(existing_symbol), "Previous declaration of '%s'\n", interface_name); + return 0; + } + if (!addSymbol(interface_name, n, scope)) + return 0; + } + return 1; +} + /* ----------------------------------------------------------------------------- * Language::symbolAddScope() * @@ -3229,7 +3257,7 @@ void Language::dumpSymbols() { * Language::symbolLookup() * ----------------------------------------------------------------------------- */ -Node *Language::symbolLookup(String *s, const_String_or_char_ptr scope) { +Node *Language::symbolLookup(const String *s, const_String_or_char_ptr scope) { Hash *symbols = Getattr(symtabs, scope ? scope : ""); if (!symbols) { return NULL; @@ -3820,6 +3848,7 @@ String *Language::defaultExternalRuntimeFilename() { /* ----------------------------------------------------------------------------- * Language::replaceSpecialVariables() + * * Language modules should implement this if special variables are to be handled * correctly in the $typemap(...) special variable macro. * method - typemap method name @@ -3839,3 +3868,4 @@ Language *Language::instance() { Hash *Language::getClassHash() const { return classhash; } + diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 8211fb317..80ea47f3f 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -329,8 +329,7 @@ public: /* Standard stuff for the SWIG runtime section */ Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGLUA\n"); + Printf(f_runtime, "\n\n#ifndef SWIGLUA\n#define SWIGLUA\n#endif\n\n"); emitLuaFlavor(f_runtime); @@ -857,6 +856,9 @@ public: //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); if (!luaAddSymbol(lua_name, n)) { + DelWrapper(f); + Delete(dispatch); + Delete(tmp); return SWIG_ERROR; } @@ -1158,6 +1160,9 @@ public: * ------------------------------------------------------------ */ virtual int enumDeclaration(Node *n) { + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + current[STATIC_CONST] = true; current[ENUM_CONST] = true; // There is some slightly specific behaviour with enums. Basically, diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 632a001ac..12b83b2e4 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -64,7 +64,7 @@ static const char *usage1 = (const char *) "\ -copyctor - Automatically generate copy constructors wherever possible\n\ -cpperraswarn - Treat the preprocessor #error statement as #warning (default)\n\ -cppext - Change file extension of generated C++ files to \n\ - (default is cxx, except for PHP which uses cpp)\n\ + (default is cxx, except for PHP5 which uses cpp)\n\ -copyright - Display copyright notices\n\ -debug-classes - Display information about the classes found in the interface\n\ -debug-module - Display module parse tree at stages 1-4, is a csv list of stages\n\ diff --git a/Source/Modules/modula3.cxx b/Source/Modules/modula3.cxx index d9a0c922b..9983e69d2 100644 --- a/Source/Modules/modula3.cxx +++ b/Source/Modules/modula3.cxx @@ -958,9 +958,7 @@ MODULA3(): Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGMODULA3\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGMODULA3\n#define SWIGMODULA3\n#endif\n\n"); Swig_name_register("wrapper", "Modula3_%f"); if (old_variable_names) { @@ -2178,20 +2176,24 @@ MODULA3(): /* Deal with inheritance */ List *baselist = Getattr(n, "bases"); - if (baselist != NIL) { + if (baselist) { Iterator base = First(baselist); - if (base.item) { - c_baseclassname = Getattr(base.item, "name"); - baseclass = Copy(getProxyName(c_baseclassname)); - if (baseclass) { - c_baseclass = SwigType_namestr(Getattr(base.item, "name")); + while (base.item) { + if (!GetFlag(base.item, "feature:ignore")) { + String *baseclassname = Getattr(base.item, "name"); + if (!c_baseclassname) { + c_baseclassname = baseclassname; + baseclass = Copy(getProxyName(baseclassname)); + if (baseclass) + c_baseclass = SwigType_namestr(baseclassname); + } else { + /* Warn about multiple inheritance for additional base class(es) */ + String *proxyclassname = Getattr(n, "classtypeobj"); + Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), + "Warning for %s, base %s ignored. Multiple inheritance is not supported in Modula 3.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); + } } base = Next(base); - if (base.item != NIL) { - Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Modula 3.\n", - name, Getattr(base.item, "name")); - } } } @@ -2203,7 +2205,7 @@ MODULA3(): const String *pure_baseclass = typemapLookup(n, "m3base", name, WARN_NONE); if (hasContent(pure_baseclass) && hasContent(baseclass)) { Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Modula 3.\n", name, pure_baseclass); + "Warning for %s, base %s ignored. Multiple inheritance is not supported in Modula 3.\n", name, pure_baseclass); } // Pure Modula 3 interfaces const String *pure_interfaces = typemapLookup(n, derived ? "m3interfaces_derived" : "m3interfaces", @@ -2433,7 +2435,7 @@ MODULA3(): base = Next(base); if (base.item) { Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Modula 3.\n", + "Warning for %s, base %s ignored. Multiple inheritance is not supported in Modula 3.\n", proxy_class_name, Getattr(base.item, "name")); } } diff --git a/Source/Modules/mzscheme.cxx b/Source/Modules/mzscheme.cxx index ed9641b30..dd3aecc40 100644 --- a/Source/Modules/mzscheme.cxx +++ b/Source/Modules/mzscheme.cxx @@ -150,9 +150,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGMZSCHEME\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGMZSCHEME\n#define SWIGMZSCHEME\n#endif\n\n"); module = Getattr(n, "name"); diff --git a/Source/Modules/ocaml.cxx b/Source/Modules/ocaml.cxx index 87b430b02..73dd14f96 100644 --- a/Source/Modules/ocaml.cxx +++ b/Source/Modules/ocaml.cxx @@ -269,8 +269,8 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGOCAML\n"); + Printf(f_runtime, "\n\n#ifndef SWIGOCAML\n#define SWIGOCAML\n#endif\n\n"); + Printf(f_runtime, "#define SWIG_MODULE \"%s\"\n", module); /* Module name */ Printf(f_mlbody, "let module_name = \"%s\"\n", module); @@ -676,6 +676,14 @@ public: Printv(f->code, tm, "\n", NIL); } } + + /* See if there is any return cleanup code */ + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); + Delete(tm); + } + // Free any memory allocated by the function being wrapped.. if ((tm = Swig_typemap_lookup("swig_result", n, Swig_cresult_name(), 0))) { @@ -1287,6 +1295,9 @@ public: * typedef enum and enum are handled. I need to produce consistent names, * which means looking up and registering by typedef and enum name. */ int enumDeclaration(Node *n) { + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + String *name = Getattr(n, "name"); if (name) { String *oname = NewString(name); diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index e5f18cae8..b977609a8 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -194,8 +194,8 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGOCTAVE\n"); + Printf(f_runtime, "\n\n#ifndef SWIGOCTAVE\n#define SWIGOCTAVE\n#endif\n\n"); + Printf(f_runtime, "#define SWIG_name_d \"%s\"\n", module); Printf(f_runtime, "#define SWIG_name %s\n", module); @@ -234,7 +234,7 @@ public: } Printf(f_init, "return true;\n}\n"); - Printf(s_global_tab, "{0,0,0,0,0}\n};\n"); + Printf(s_global_tab, "{0,0,0,0,0,0}\n};\n"); Printv(f_wrappers, s_global_tab, NIL); SwigType_emit_type_table(f_runtime, f_wrappers); @@ -469,7 +469,6 @@ public: value = Getattr(p, "tmap:doc:value"); } - // Note: the generated name should be consistent with that in kwnames[] name = name ? name : Getattr(p, "name"); name = name ? name : Getattr(p, "lname"); name = Swig_name_make(p, 0, name, 0, 0); // rename parameter if a keyword @@ -966,25 +965,13 @@ public: SwigType *t = Copy(Getattr(n, "name")); SwigType_add_pointer(t); - String *smartptr = Getattr(n, "feature:smartptr"); // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers) - SwigType *smart = 0; - if (smartptr) { - SwigType *cpt = Swig_cparse_type(smartptr); - if (cpt) { - smart = SwigType_typedef_resolve_all(cpt); - Delete(cpt); - } else { - // TODO: report line number of where the feature comes from - Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, class_name); - } - } + // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers) + SwigType *smart = Swig_cparse_smartptr(n); String *wrap_class = NewStringf("&_wrap_class_%s", class_name); - if(smart){ + if (smart) { SwigType_add_pointer(smart); SwigType_remember_clientdata(smart, wrap_class); } - Delete(smart); - Delete(smartptr); //String *wrap_class = NewStringf("&_wrap_class_%s", class_name); SwigType_remember_clientdata(t, wrap_class); @@ -1010,7 +997,7 @@ public: Delete(cnameshdw); } - Printf(s_members_tab, "{0,0,0,0}\n};\n"); + Printf(s_members_tab, "{0,0,0,0,0,0}\n};\n"); Printv(f_wrappers, s_members_tab, NIL); String *base_class_names = NewString(""); @@ -1064,6 +1051,7 @@ public: Delete(base_class); Delete(base_class_names); + Delete(smart); Delete(t); Delete(s_members_tab); s_members_tab = 0; diff --git a/Source/Modules/overload.cxx b/Source/Modules/overload.cxx index dd3ca4972..330294efd 100644 --- a/Source/Modules/overload.cxx +++ b/Source/Modules/overload.cxx @@ -433,6 +433,7 @@ String *Swig_overload_dispatch_cast(Node *n, const_String_or_char_ptr fmt, int * int fn = 0; Node *ni = Getitem(dispatch, i); Parm *pi = Getattr(ni, "wrap:parms"); + bool implicitconvtypecheckoff = GetFlag(ni, "implicitconvtypecheckoff") != 0; int num_required = emit_num_required(pi); int num_arguments = emit_num_arguments(pi); if (num_arguments > *maxargs) @@ -476,6 +477,7 @@ String *Swig_overload_dispatch_cast(Node *n, const_String_or_char_ptr fmt, int * String *tm = Getattr(pj, "tmap:typecheck"); if (tm) { + tm = Copy(tm); /* normalise for comparison later */ Replaceid(tm, Getattr(pj, "lname"), "_v"); @@ -528,13 +530,14 @@ String *Swig_overload_dispatch_cast(Node *n, const_String_or_char_ptr fmt, int * String *tmp = NewStringf(argv_template_string, j); String *conv = Getattr(pj, "implicitconv"); - if (conv) { + if (conv && !implicitconvtypecheckoff) { Replaceall(tm, "$implicitconv", conv); } else { Replaceall(tm, "$implicitconv", "0"); } Replaceall(tm, "$input", tmp); Printv(f, "{\n", tm, "}\n", NIL); + Delete(tm); fn = i + 1; Printf(f, "if (!_v) goto check_%d;\n", fn); Printf(f, "_ranki += _v*_pi;\n"); @@ -574,6 +577,9 @@ String *Swig_overload_dispatch_cast(Node *n, const_String_or_char_ptr fmt, int * if (fn) Printf(f, "check_%d:\n\n", fn); + if (implicitconvtypecheckoff) + Delattr(ni, "implicitconvtypecheckoff"); + Delete(lfmt); Delete(coll); } @@ -607,6 +613,7 @@ String *Swig_overload_dispatch_fast(Node *n, const_String_or_char_ptr fmt, int * int fn = 0; Node *ni = Getitem(dispatch, i); Parm *pi = Getattr(ni, "wrap:parms"); + bool implicitconvtypecheckoff = GetFlag(ni, "implicitconvtypecheckoff") != 0; int num_required = emit_num_required(pi); int num_arguments = emit_num_arguments(pi); if (num_arguments > *maxargs) @@ -646,6 +653,7 @@ String *Swig_overload_dispatch_fast(Node *n, const_String_or_char_ptr fmt, int * String *tm = Getattr(pj, "tmap:typecheck"); if (tm) { + tm = Copy(tm); /* normalise for comparison later */ Replaceid(tm, Getattr(pj, "lname"), "_v"); @@ -699,13 +707,14 @@ String *Swig_overload_dispatch_fast(Node *n, const_String_or_char_ptr fmt, int * String *tmp = NewStringf(argv_template_string, j); String *conv = Getattr(pj, "implicitconv"); - if (conv) { + if (conv && !implicitconvtypecheckoff) { Replaceall(tm, "$implicitconv", conv); } else { Replaceall(tm, "$implicitconv", "0"); } Replaceall(tm, "$input", tmp); Printv(f, "{\n", tm, "}\n", NIL); + Delete(tm); fn = i + 1; Printf(f, "if (!_v) goto check_%d;\n", fn); } @@ -737,6 +746,9 @@ String *Swig_overload_dispatch_fast(Node *n, const_String_or_char_ptr fmt, int * if (fn) Printf(f, "check_%d:\n\n", fn); + if (implicitconvtypecheckoff) + Delattr(ni, "implicitconvtypecheckoff"); + Delete(lfmt); Delete(coll); } diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index 979f96484..406568b16 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -325,8 +325,8 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGPERL\n"); + Printf(f_runtime, "\n\n#ifndef SWIGPERL\n#define SWIGPERL\n#endif\n\n"); + if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); } @@ -1045,21 +1045,9 @@ public: String *tt = Getattr(n, "tmap:varout:type"); if (tt) { - String *tm = NewStringf("&SWIGTYPE%s", SwigType_manglestr(t)); - if (Replaceall(tt, "$1_descriptor", tm)) { - SwigType_remember(t); - } - Delete(tm); - SwigType *st = Copy(t); - SwigType_add_pointer(st); - tm = NewStringf("&SWIGTYPE%s", SwigType_manglestr(st)); - if (Replaceall(tt, "$&1_descriptor", tm)) { - SwigType_remember(st); - } - Delete(tm); - Delete(st); + tt = NewStringf("&%s", tt); } else { - tt = (String *) "0"; + tt = NewString("0"); } /* Now add symbol to the PERL interpreter */ if (GetFlag(n, "feature:immutable")) { @@ -1087,6 +1075,7 @@ public: if (export_all) Printf(exported, "$%s ", iname); + Delete(tt); DelWrapper(setf); DelWrapper(getf); Delete(getname); @@ -2141,6 +2130,8 @@ public: String *cres = SwigType_lstr(returntype, "c_result"); Printf(w->code, "%s;\n", cres); Delete(cres); + } + if (!ignored_method) { String *pres = NewStringf("SV *%s", Swig_cresult_name()); Wrapper_add_local(w, Swig_cresult_name(), pres); Delete(pres); diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index 37a8f9628..213025d95 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -43,7 +43,7 @@ #include static const char *usage = "\ -PHP Options (available with -php)\n\ +PHP Options (available with -php7)\n\ -noproxy - Don't generate proxy classes.\n\ -prefix - Prepend to all class names in PHP wrappers\n\ \n"; @@ -100,6 +100,11 @@ static String *s_oowrappers; static String *s_fakeoowrappers; static String *s_phpclasses; +/* To reduce code size (generated and compiled) we only want to emit each + * different arginfo once, so we need to track which have been used. + */ +static Hash *arginfo_used; + /* Variables for using PHP classes */ static Node *current_class = 0; @@ -129,6 +134,7 @@ extern "C" { static void SwigPHP_emit_resource_registrations() { Iterator ki; + bool emitted_default_dtor = false; if (!zend_types) return; @@ -140,9 +146,7 @@ static void SwigPHP_emit_resource_registrations() { DOH *key = ki.key; Node *class_node = ki.item; String *human_name = key; - - // Write out destructor function header - Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(_wrap_destroy%s) {\n", key); + String *rsrc_dtor_name = NULL; // write out body if (class_node != NOTCLASS) { @@ -152,51 +156,42 @@ static void SwigPHP_emit_resource_registrations() { human_name = Getattr(class_node, "name"); // Do we have a known destructor for this type? if (destructor) { - Printf(s_wrappers, " %s(rsrc, SWIGTYPE%s->name TSRMLS_CC);\n", destructor, key); - } else { - Printf(s_wrappers, " /* No destructor for class %s */\n", human_name); - Printf(s_wrappers, " efree(rsrc->ptr);\n"); + rsrc_dtor_name = NewStringf("_wrap_destroy%s", key); + // Write out custom destructor function + Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(%s) {\n", rsrc_dtor_name); + Printf(s_wrappers, " %s(res, SWIGTYPE%s->name);\n", destructor, key); + Printf(s_wrappers, "}\n"); } - } else { - Printf(s_wrappers, " /* No destructor for simple type %s */\n", key); - Printf(s_wrappers, " efree(rsrc->ptr);\n"); } - // close function - Printf(s_wrappers, "}\n"); + if (!rsrc_dtor_name) { + rsrc_dtor_name = NewString("_swig_default_rsrc_destroy"); + if (!emitted_default_dtor) { + // Write out custom destructor function + Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(%s) {\n", rsrc_dtor_name); + Printf(s_wrappers, " efree(res->ptr);\n"); + Printf(s_wrappers, "}\n"); + emitted_default_dtor = true; + } + } // declare le_swig_ to store php registration Printf(s_vdecl, "static int le_swig_%s=0; /* handle for %s */\n", key, human_name); // register with php Printf(s_oinit, "le_swig_%s=zend_register_list_destructors_ex" - "(_wrap_destroy%s,NULL,(char *)(SWIGTYPE%s->name),module_number);\n", key, key, key); + "(%s, NULL, SWIGTYPE%s->name, module_number);\n", key, rsrc_dtor_name, key); // store php type in class struct Printf(s_oinit, "SWIG_TypeClientData(SWIGTYPE%s,&le_swig_%s);\n", key, key); + Delete(rsrc_dtor_name); + ki = Next(ki); } } class PHP : public Language { - String *emit_action(Node *n) { - // Adjust wrap:action to add TSRMLS_CC. - String * action = Getattr(n, "wrap:action"); - if (action) { - char * p = Strstr(action, "Swig::DirectorPureVirtualException::raise(\""); - if (p) { - p += strlen("Swig::DirectorPureVirtualException::raise(\""); - p = strchr(p, '"'); - if (p) { - ++p; - Insert(action, (int)(p - Char(action)), " TSRMLS_CC"); - } - } - } - return ::emit_action(n); - } - public: PHP() { director_language = 1; @@ -208,7 +203,6 @@ public: virtual void main(int argc, char *argv[]) { SWIG_library_directory("php"); - SWIG_config_cppext("cpp"); for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-prefix") == 0) { @@ -225,25 +219,11 @@ public: Swig_mark_arg(i); } else if (strcmp(argv[i], "-help") == 0) { fputs(usage, stdout); - } else if (strcmp(argv[i], "-make") == 0 || - strcmp(argv[i], "-withc") == 0 || - strcmp(argv[i], "-withcxx") == 0) { - Printf(stderr, "*** %s is no longer supported.\n", argv[i]); - SWIG_exit(EXIT_FAILURE); - } else if (strcmp(argv[i], "-phpfull") == 0 || - strcmp(argv[i], "-withlibs") == 0 || - strcmp(argv[i], "-withincs") == 0) { - Printf(stderr, "*** %s is no longer supported.\n*** We recommend building as a dynamically loadable module.\n", argv[i]); - SWIG_exit(EXIT_FAILURE); - } else if (strcmp(argv[i], "-dlname") == 0) { - Printf(stderr, "*** -dlname is no longer supported.\n*** If you want to change the module name, use -module instead.\n"); - SWIG_exit(EXIT_FAILURE); } } Preprocessor_define("SWIGPHP 1", 0); - // SWIGPHP5 is deprecated, and no longer documented. - Preprocessor_define("SWIGPHP5 1", 0); + Preprocessor_define("SWIGPHP7 1", 0); SWIG_typemap_lang("php"); SWIG_config_file("php.swg"); allow_overloading(); @@ -267,7 +247,7 @@ public: } /* Set comparison with null for ConstructorToFunction */ - setSubclassInstanceCheck(NewString("$arg->type != IS_NULL")); + setSubclassInstanceCheck(NewString("Z_TYPE_P($arg) != IS_NULL")); /* Initialize all of the output files */ String *outfile = Getattr(n, "outfile"); @@ -320,9 +300,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGPHP\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGPHP\n#define SWIGPHP\n#endif\n\n"); if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); @@ -404,9 +382,9 @@ public: * which has to be dynamically generated as it depends on the module name. */ Append(s_header, "#ifdef __GNUC__\n"); - Append(s_header, "static void SWIG_FAIL(TSRMLS_D) __attribute__ ((__noreturn__));\n"); + Append(s_header, "static void SWIG_FAIL(void) __attribute__ ((__noreturn__));\n"); Append(s_header, "#endif\n\n"); - Append(s_header, "static void SWIG_FAIL(TSRMLS_D) {\n"); + Append(s_header, "static void SWIG_FAIL(void) {\n"); Append(s_header, " zend_error(SWIG_ErrorCode(), \"%s\", SWIG_ErrorMsg());\n"); // zend_error() should never return with the parameters we pass, but if it // does, we really don't want to let SWIG_FAIL() return. This also avoids @@ -422,38 +400,36 @@ public: Printf(s_header, "static void %s_destroy_globals(zend_%s_globals * globals) { (void)globals; }\n", module, module); Printf(s_header, "\n"); - Printf(s_header, "static void SWIG_ResetError(TSRMLS_D) {\n"); + Printf(s_header, "static void SWIG_ResetError(void) {\n"); Printf(s_header, " SWIG_ErrorMsg() = default_error_msg;\n"); Printf(s_header, " SWIG_ErrorCode() = default_error_code;\n"); Printf(s_header, "}\n"); Append(s_header, "\n"); Printf(s_header, "ZEND_NAMED_FUNCTION(_wrap_swig_%s_alter_newobject) {\n", module); - Append(s_header, " zval **args[2];\n"); + Append(s_header, " zval args[2];\n"); Append(s_header, " swig_object_wrapper *value;\n"); - Append(s_header, " int type;\n"); Append(s_header, "\n"); - Append(s_header, " SWIG_ResetError(TSRMLS_C);\n"); + Append(s_header, " SWIG_ResetError();\n"); Append(s_header, " if(ZEND_NUM_ARGS() != 2 || zend_get_parameters_array_ex(2, args) != SUCCESS) {\n"); Append(s_header, " WRONG_PARAM_COUNT;\n"); Append(s_header, " }\n"); Append(s_header, "\n"); - Append(s_header, " value = (swig_object_wrapper *) zend_list_find((*args[0])->value.lval, &type);\n"); - Append(s_header, " value->newobject = zval_is_true(*args[1]);\n"); + Append(s_header, " value = (swig_object_wrapper *) Z_RES_VAL(args[0]);\n"); + Append(s_header, " value->newobject = zval_is_true(&args[1]);\n"); Append(s_header, "\n"); Append(s_header, " return;\n"); Append(s_header, "}\n"); Printf(s_header, "ZEND_NAMED_FUNCTION(_wrap_swig_%s_get_newobject) {\n", module); - Append(s_header, " zval **args[1];\n"); + Append(s_header, " zval args[1];\n"); Append(s_header, " swig_object_wrapper *value;\n"); - Append(s_header, " int type;\n"); Append(s_header, "\n"); - Append(s_header, " SWIG_ResetError(TSRMLS_C);\n"); + Append(s_header, " SWIG_ResetError();\n"); Append(s_header, " if(ZEND_NUM_ARGS() != 1 || zend_get_parameters_array_ex(1, args) != SUCCESS) {\n"); Append(s_header, " WRONG_PARAM_COUNT;\n"); Append(s_header, " }\n"); Append(s_header, "\n"); - Append(s_header, " value = (swig_object_wrapper *) zend_list_find((*args[0])->value.lval, &type);\n"); + Append(s_header, " value = (swig_object_wrapper *) Z_RES_VAL(args[0]);\n"); Append(s_header, " RETVAL_LONG(value->newobject);\n"); Append(s_header, "\n"); Append(s_header, " return;\n"); @@ -509,6 +485,7 @@ public: /* start the arginfo section */ s_arginfo = NewString("/* arginfo subsection */\n"); + arginfo_used = NewHash(); /* start the function entry section */ s_entry = NewString("/* entry subsection */\n"); @@ -527,7 +504,7 @@ public: Append(s_init, "#endif\n"); Printv(s_init, "zend_module_entry ", module, "_module_entry = {\n", NIL); Printf(s_init, " STANDARD_MODULE_HEADER,\n"); - Printf(s_init, " (char*)\"%s\",\n", module); + Printf(s_init, " \"%s\",\n", module); Printf(s_init, " %s_functions,\n", module); Printf(s_init, " PHP_MINIT(%s),\n", module); Printf(s_init, " PHP_MSHUTDOWN(%s),\n", module); @@ -639,7 +616,7 @@ public: Printv(f_begin, all_cs_entry, "\n\n", s_arginfo, "\n\n", s_entry, " SWIG_ZEND_NAMED_FE(swig_", module, "_alter_newobject,_wrap_swig_", module, "_alter_newobject,NULL)\n" " SWIG_ZEND_NAMED_FE(swig_", module, "_get_newobject,_wrap_swig_", module, "_get_newobject,NULL)\n" - "{NULL, NULL, NULL}\n};\n\n", NIL); + " ZEND_FE_END\n};\n\n", NIL); Printv(f_begin, s_init, NIL); Delete(s_header); Delete(s_wrappers); @@ -650,6 +627,7 @@ public: Delete(s_arginfo); Delete(f_runtime); Delete(f_begin); + Delete(arginfo_used); Printf(f_phpcode, "%s\n%s\n", pragma_incl, pragma_code); if (s_fakeoowrappers) { @@ -669,22 +647,36 @@ public: void create_command(String *cname, String *iname, Node *n) { // This is for the single main zend_function_entry record Printf(f_h, "ZEND_NAMED_FUNCTION(%s);\n", iname); - String * s = cs_entry; - if (!s) s = s_entry; - Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,swig_arginfo_%(lower)s)\n", cname, iname, cname); - // This is the above referenced arginfo structure. + // We want to only emit each different arginfo once, as that reduces the + // size of both the generated source code and the compiled extension + // module. To do this, we name the arginfo to encode the number of + // parameters and which (if any) are passed by reference by using a + // sequence of 0s (for non-reference) and 1s (for by references). ParmList *l = Getattr(n, "parms"); - Printf(s_arginfo, "ZEND_BEGIN_ARG_INFO_EX(swig_arginfo_%(lower)s, 0, 0, 0)\n", cname); + String * arginfo_code = NewStringEmpty(); for (Parm *p = l; p; p = Getattr(p, "tmap:in:next")) { /* Ignored parameters */ if (checkAttribute(p, "tmap:in:numinputs", "0")) { continue; } - int byref = GetFlag(p, "tmap:in:byref"); - Printf(s_arginfo, " ZEND_ARG_PASS_INFO(%d)\n", byref); + Append(arginfo_code, GetFlag(p, "tmap:in:byref") ? "1" : "0"); } - Printf(s_arginfo, "ZEND_END_ARG_INFO()\n"); + + if (!GetFlag(arginfo_used, arginfo_code)) { + // Not had this one before, so emit it. + SetFlag(arginfo_used, arginfo_code); + Printf(s_arginfo, "ZEND_BEGIN_ARG_INFO_EX(swig_arginfo_%s, 0, 0, 0)\n", arginfo_code); + for (const char * p = Char(arginfo_code); *p; ++p) { + Printf(s_arginfo, " ZEND_ARG_PASS_INFO(%c)\n", *p); + } + Printf(s_arginfo, "ZEND_END_ARG_INFO()\n"); + } + + String * s = cs_entry; + if (!s) s = s_entry; + Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,swig_arginfo_%s)\n", cname, iname, arginfo_code); + Delete(arginfo_code); } /* ------------------------------------------------------------ @@ -712,12 +704,12 @@ public: Wrapper_add_local(f, "argc", "int argc"); - Printf(tmp, "zval **argv[%d]", maxargs); + Printf(tmp, "zval argv[%d]", maxargs); Wrapper_add_local(f, "argv", tmp); Printf(f->code, "argc = ZEND_NUM_ARGS();\n"); - Printf(f->code, "zend_get_parameters_array_ex(argc,argv);\n"); + Printf(f->code, "zend_get_parameters_array_ex(argc, argv);\n"); Replaceall(dispatch, "$args", "self,args"); @@ -725,7 +717,7 @@ public: Printf(f->code, "SWIG_ErrorCode() = E_ERROR;\n"); Printf(f->code, "SWIG_ErrorMsg() = \"No matching function for overloaded '%s'\";\n", symname); - Printv(f->code, "SWIG_FAIL(TSRMLS_C);\n", NIL); + Printv(f->code, "SWIG_FAIL();\n", NIL); Printv(f->code, "}\n", NIL); Wrapper_print(f, s_wrappers); @@ -821,8 +813,8 @@ public: if (num_arguments > 0) { String *args = NewStringEmpty(); if (wrapperType == directorconstructor) - Wrapper_add_local(f, "arg0", "zval *arg0"); - Printf(args, "zval **args[%d]", num_arguments); + Wrapper_add_local(f, "arg0", "zval * arg0"); + Printf(args, "zval args[%d]", num_arguments); Wrapper_add_local(f, "args", args); Delete(args); args = NULL; @@ -836,7 +828,7 @@ public: // NOTE: possible we ignore this_ptr as a param for native constructor - Printf(f->code, "SWIG_ResetError(TSRMLS_C);\n"); + Printf(f->code, "SWIG_ResetError();\n"); if (numopt > 0) { // membervariable wrappers do not have optional args Wrapper_add_local(f, "arg_count", "int arg_count"); @@ -853,7 +845,7 @@ public: Printf(f->code, "WRONG_PARAM_COUNT;\n}\n\n"); } if (wrapperType == directorconstructor) - Printf(f->code, "arg0 = *args[0];\n \n"); + Printf(f->code, "arg0 = &args[0];\n \n"); /* Now convert from PHP to C variables */ // At this point, argcount if used is the number of deliberately passed args @@ -893,7 +885,7 @@ public: } if ((tm = Getattr(p, "tmap:in"))) { - Replaceall(tm, "$source", source); + Replaceall(tm, "$source", &source); Replaceall(tm, "$target", ln); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); @@ -917,7 +909,7 @@ public: if (is_member_director(n)) { Wrapper_add_local(f, "upcall", "bool upcall = false"); - Printf(f->code, "upcall = !Swig::Director::swig_is_overridden_method((char *)\"%s%s\", (char *)\"%s\" TSRMLS_CC);\n", + Printf(f->code, "upcall = !Swig::Director::swig_is_overridden_method(\"%s%s\", \"%s\");\n", prefix, Swig_class_name(Swig_methodclass(n)), name); } @@ -1002,12 +994,13 @@ public: Delete(tm); } + Printf(f->code, "thrown:\n"); Printf(f->code, "return;\n"); /* Error handling code */ Printf(f->code, "fail:\n"); Printv(f->code, cleanup, NIL); - Append(f->code, "SWIG_FAIL(TSRMLS_C);\n"); + Append(f->code, "SWIG_FAIL();\n"); Printf(f->code, "}\n"); @@ -1057,6 +1050,7 @@ public: bool handle_as_overload = false; String **arg_names; String **arg_values; + unsigned char * byref; // Method or static method or plain function. const char *methodname = 0; String *output = s_oowrappers; @@ -1197,7 +1191,8 @@ public: } arg_values = (String **) malloc(max_num_of_arguments * sizeof(String *)); - if (!arg_values) { + byref = (unsigned char *) malloc(max_num_of_arguments); + if (!arg_values || !byref) { /* FIXME: How should this be handled? The rest of SWIG just seems * to not bother checking for malloc failing! */ fprintf(stderr, "Malloc failed!\n"); @@ -1205,6 +1200,7 @@ public: } for (i = 0; i < max_num_of_arguments; ++i) { arg_values[i] = NULL; + byref[i] = false; } Node *o; @@ -1224,6 +1220,7 @@ public: continue; } assert(0 <= argno && argno < max_num_of_arguments); + byref[argno] = GetFlag(p, "tmap:in:byref"); String *&pname = arg_names[argno]; const char *pname_cstr = GetChar(p, "name"); // Just get rid of the C++ namespace part for now. @@ -1472,6 +1469,7 @@ public: Printf(args, ","); if (i || wrapperType == memberfn) Printf(invoke, ","); + if (byref[i]) Printf(args, "&"); String *value = arg_values[i]; if (value) { const char *v = Char(value); @@ -1906,7 +1904,7 @@ done: enumvalue = GetChar(n, "enumvalueex"); } - if (enumvalue) { + if (enumvalue && *Char(enumvalue)) { // Check for a simple constant expression which is valid in PHP. // If we find one, initialise the const member with it; otherwise // we initialise it using the C/C++ wrapped constant. @@ -1918,7 +1916,8 @@ done: break; } } - if (!*p) set_to = enumvalue; + if (!*p) + set_to = enumvalue; } if (wrapping_member_constant) { @@ -2020,7 +2019,7 @@ done: String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); Swig_warning(WARN_PHP_MULTIPLE_INHERITANCE, input_file, line_number, - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, baseclassname); + "Warning for %s, base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, baseclassname); base = Next(base); } } @@ -2290,15 +2289,15 @@ done: Delete(director_ctor_code); director_ctor_code = NewStringEmpty(); director_prot_ctor_code = NewStringEmpty(); - Printf(director_ctor_code, "if ( arg0->type == IS_NULL ) { /* not subclassed */\n"); - Printf(director_prot_ctor_code, "if ( arg0->type == IS_NULL ) { /* not subclassed */\n"); + Printf(director_ctor_code, "if (Z_TYPE_P(arg0) == IS_NULL) { /* not subclassed */\n"); + Printf(director_prot_ctor_code, "if (Z_TYPE_P(arg0) == IS_NULL) { /* not subclassed */\n"); Printf(director_ctor_code, " %s = (%s *)new %s(%s);\n", Swig_cresult_name(), ctype, ctype, args); Printf(director_prot_ctor_code, " SWIG_PHP_Error(E_ERROR, \"accessing abstract class or protected constructor\");\n", name, name, args); if (i) { Insert(args, 0, ", "); } - Printf(director_ctor_code, "} else {\n %s = (%s *)new SwigDirector_%s(arg0 TSRMLS_CC%s);\n}\n", Swig_cresult_name(), ctype, sname, args); - Printf(director_prot_ctor_code, "} else {\n %s = (%s *)new SwigDirector_%s(arg0 TSRMLS_CC%s);\n}\n", Swig_cresult_name(), ctype, sname, args); + Printf(director_ctor_code, "} else {\n %s = (%s *)new SwigDirector_%s(arg0%s);\n}\n", Swig_cresult_name(), ctype, sname, args); + Printf(director_prot_ctor_code, "} else {\n %s = (%s *)new SwigDirector_%s(arg0%s);\n}\n", Swig_cresult_name(), ctype, sname, args); Delete(args); wrapperType = directorconstructor; @@ -2328,9 +2327,9 @@ done: Wrapper *f = NewWrapper(); Printf(f->def, "/* This function is designed to be called by the zend list destructors */\n"); Printf(f->def, "/* to typecast and do the actual destruction */\n"); - Printf(f->def, "static void %s(zend_rsrc_list_entry *rsrc, const char *type_name TSRMLS_DC) {\n", destructorname); + Printf(f->def, "static void %s(zend_resource *res, const char *type_name) {\n", destructorname); - Wrapper_add_localv(f, "value", "swig_object_wrapper *value=(swig_object_wrapper *) rsrc->ptr", NIL); + Wrapper_add_localv(f, "value", "swig_object_wrapper *value=(swig_object_wrapper *) res->ptr", NIL); Wrapper_add_localv(f, "ptr", "void *ptr=value->ptr", NIL); Wrapper_add_localv(f, "newobject", "int newobject=value->newobject", NIL); @@ -2348,7 +2347,7 @@ done: Printf(f->code, " efree(value);\n"); Printf(f->code, " if (! newobject) return; /* can't delete it! */\n"); - Printf(f->code, " arg1 = (%s)SWIG_ZTS_ConvertResourceData(ptr,type_name,SWIGTYPE%s TSRMLS_CC);\n", SwigType_lstr(pt, 0), SwigType_manglestr(pt)); + Printf(f->code, " arg1 = (%s)SWIG_ConvertResourceData(ptr, type_name, SWIGTYPE%s);\n", SwigType_lstr(pt, 0), SwigType_manglestr(pt)); Printf(f->code, " if (! arg1) zend_error(E_ERROR, \"%s resource already free'd\");\n", Char(name)); Setattr(n, "wrap:name", destructorname); @@ -2357,9 +2356,10 @@ done: Append(f->code, actioncode); Delete(actioncode); + Printf(f->code, "thrown:\n"); Append(f->code, "return;\n"); Append(f->code, "fail:\n"); - Append(f->code, "SWIG_FAIL(TSRMLS_C);\n"); + Append(f->code, "SWIG_FAIL();\n"); Printf(f->code, "}\n"); Wrapper_print(f, s_wrappers); @@ -2419,16 +2419,9 @@ done: String *call; String *basetype = Getattr(parent, "classtype"); - // We put TSRMLS_DC after the self parameter in order to cope with - // any default parameters. String *target = Swig_method_decl(0, decl, classname, parms, 0, 0); - const char * p = Char(target); - const char * comma = strchr(p, ','); - int ins = comma ? (int)(comma - p) : Len(target) - 1; - Insert(target, ins, " TSRMLS_DC"); - call = Swig_csuperclass_call(0, basetype, superparms); - Printf(w->def, "%s::%s: %s, Swig::Director(self TSRMLS_CC) {", classname, target, call); + Printf(w->def, "%s::%s: %s, Swig::Director(self) {", classname, target, call); Append(w->def, "}"); Delete(target); Wrapper_print(w, f_directors); @@ -2438,14 +2431,7 @@ done: /* constructor header */ { - // We put TSRMLS_DC after the self parameter in order to cope with - // any default parameters. String *target = Swig_method_decl(0, decl, classname, parms, 0, 1); - const char * p = Char(target); - const char * comma = strchr(p, ','); - int ins = comma ? (int)(comma - p) : Len(target) - 1; - Insert(target, ins, " TSRMLS_DC"); - Printf(f_directors_h, " %s;\n", target); Delete(target); } @@ -2530,8 +2516,6 @@ done: Append(w->def, " {"); Append(declaration, ";\n"); - Printf(w->code, "TSRMLS_FETCH_FROM_CTX(swig_zts_ctx);\n"); - /* declare method return value * if the return value is a reference or const reference, a specialized typemap must * handle it, including declaration of c_result ($result). @@ -2552,7 +2536,7 @@ done: Printf(w->code, "%s;\n", super_call); Delete(super_call); } else { - Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\" TSRMLS_CC);\n", SwigType_namestr(c_classname), + Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname), SwigType_namestr(name)); } } else { @@ -2567,7 +2551,6 @@ done: Swig_typemap_attach_parms("directorargout", l, w); Parm *p; - char source[256]; int outputs = 0; if (!is_void) @@ -2591,16 +2574,11 @@ done: if ((tm = Getattr(p, "tmap:directorin")) != 0) { String *parse = Getattr(p, "tmap:directorin:parse"); if (!parse) { - sprintf(source, "obj%d", idx++); - String *input = NewStringf("&%s", source); + String *input = NewStringf("&args[%d]", idx++); Setattr(p, "emit:directorinput", input); Replaceall(tm, "$input", input); Delete(input); Replaceall(tm, "$owner", "0"); - Printv(wrap_args, "zval ", source, ";\n", NIL); - Printf(wrap_args, "args[%d] = &%s;\n", idx - 1, source); - Printv(wrap_args, "INIT_ZVAL(", source, ");\n", NIL); - Printv(wrap_args, tm, "\n", NIL); Putc('O', parse_args); } else { @@ -2624,6 +2602,7 @@ done: } /* exception handling */ + bool error_used_in_typemap = false; tm = Swig_typemap_lookup("director:except", n, Swig_cresult_name(), 0); if (!tm) { tm = Getattr(n, "feature:director:except"); @@ -2633,6 +2612,7 @@ done: if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { if (Replaceall(tm, "$error", "error")) { /* Only declare error if it is used by the typemap. */ + error_used_in_typemap = true; Append(w->code, "int error;\n"); } } else { @@ -2641,23 +2621,26 @@ done: } if (!idx) { - Printf(w->code, "zval **args = NULL;\n"); + Printf(w->code, "zval *args = NULL;\n"); } else { - Printf(w->code, "zval *args[%d];\n", idx); + Printf(w->code, "zval args[%d];\n", idx); } - Printf(w->code, "zval *%s, funcname;\n", Swig_cresult_name()); - Append(w->code, "if (!swig_self) {\n"); - Append(w->code, " SWIG_PHP_Error(E_ERROR, \"this pointer is NULL\");"); - Append(w->code, "}\n\n"); - Printf(w->code, "MAKE_STD_ZVAL(%s);\n", Swig_cresult_name()); + // typemap_directorout testcase requires that 0 can be assigned to the + // variable named after the result of Swig_cresult_name(), so that can't + // be a zval - make it a pointer to one instead. + Printf(w->code, "zval swig_zval_result, swig_funcname;\n", Swig_cresult_name()); + Printf(w->code, "zval *%s = &swig_zval_result;\n", Swig_cresult_name()); const char * funcname = GetChar(n, "sym:name"); - Printf(w->code, "ZVAL_STRINGL(&funcname, (char *)\"%s\", %d, 0);\n", funcname, strlen(funcname)); + Printf(w->code, "ZVAL_STRINGL(&swig_funcname, \"%s\", %d);\n", funcname, strlen(funcname)); /* wrap complex arguments to zvals */ Printv(w->code, wrap_args, NIL); - Append(w->code, "call_user_function(EG(function_table), (zval**)&swig_self, &funcname,"); - Printf(w->code, " %s, %d, args TSRMLS_CC);\n", Swig_cresult_name(), idx); + if (error_used_in_typemap) { + Append(w->code, "error = "); + } + Append(w->code, "call_user_function(EG(function_table), &swig_self, &swig_funcname,"); + Printf(w->code, " &swig_zval_result, %d, args);\n", idx); if (tm) { Printv(w->code, Str(tm), "\n", NIL); @@ -2709,13 +2692,12 @@ done: } } - Printf(w->code, "FREE_ZVAL(%s);\n", Swig_cresult_name()); - Delete(parse_args); Delete(cleanup); Delete(outarg); } + Append(w->code, "thrown:\n"); if (!is_void) { if (!(ignored_method && !pure_virtual)) { String *rettype = SwigType_str(returntype, 0); @@ -2731,7 +2713,7 @@ done: } Append(w->code, "fail:\n"); - Append(w->code, "SWIG_FAIL(TSRMLS_C);\n"); + Append(w->code, "SWIG_FAIL();\n"); Append(w->code, "}\n"); // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method @@ -2776,7 +2758,8 @@ static PHP *maininstance = 0; // We use this function to be able to write out zend_register_list_destructor_ex // lines for most things in the type table // NOTE: it's a function NOT A PHP::METHOD -extern "C" void typetrace(const SwigType *ty, String *mangled, String *clientdata) { +extern "C" { +static void typetrace(const SwigType *ty, String *mangled, String *clientdata) { Node *class_node; if (!zend_types) { zend_types = NewHash(); @@ -2796,6 +2779,7 @@ extern "C" void typetrace(const SwigType *ty, String *mangled, String *clientdat if (r_prevtracefunc) (*r_prevtracefunc) (ty, mangled, (String *) clientdata); } +} /* ----------------------------------------------------------------------------- * new_swig_php() - Instantiate module @@ -2812,13 +2796,6 @@ static Language *new_swig_php() { return maininstance; } -extern "C" Language *swig_php4(void) { - Printf(stderr, "*** -php4 is no longer supported.\n" - "*** Either upgrade to PHP5 or use SWIG 1.3.36 or earlier.\n"); - SWIG_exit(EXIT_FAILURE); - return NULL; // To avoid compiler warnings. -} - extern "C" Language *swig_php(void) { return new_swig_php(); } diff --git a/Source/Modules/php5.cxx b/Source/Modules/php5.cxx new file mode 100644 index 000000000..3b7fdc1b0 --- /dev/null +++ b/Source/Modules/php5.cxx @@ -0,0 +1,2861 @@ +/* ----------------------------------------------------------------------------- + * This file is part of SWIG, which is licensed as a whole under version 3 + * (or any later version) of the GNU General Public License. Some additional + * terms also apply to certain portions of SWIG. The full details of the SWIG + * license and copyrights can be found in the LICENSE and COPYRIGHT files + * included with the SWIG source code as distributed by the SWIG developers + * and at http://www.swig.org/legal.html. + * + * php5.cxx + * + * PHP5 language module for SWIG. + * ----------------------------------------------------------------------------- + */ + +/* FIXME: PHP5 OO wrapping TODO list: + * + * Medium term: + * + * Handle default parameters on overloaded methods in PHP where possible. + * (Mostly done - just need to handle cases of overloaded methods with + * default parameters...) + * This is an optimisation - we could handle this case using a PHP + * default value, but currently we treat it as we would for a default + * value which is a compound C++ expression (i.e. as if we had a + * method with two overloaded forms instead of a single method with + * a default parameter value). + * + * Long term: + * + * Sort out locale-dependent behaviour of strtod() - it's harmless unless + * SWIG ever sets the locale and DOH/base.c calls atof, so we're probably + * OK currently at least. + */ + +/* + * TODO: Replace remaining stderr messages with Swig_error or Swig_warning + * (may need to add more WARN_PHP_xxx codes...) + */ + +#include "swigmod.h" + +#include +#include + +static const char *usage = "\ +PHP5 Options (available with -php5)\n\ + -noproxy - Don't generate proxy classes.\n\ + -prefix - Prepend to all class names in PHP wrappers\n\ +\n"; + +/* The original class wrappers for PHP stored the pointer to the C++ class in + * the object property _cPtr. If we use the same name for the member variable + * which we put the pointer to the C++ class in, then the flat function + * wrappers will automatically pull it out without any changes being required. + * FIXME: Isn't using a leading underscore a bit suspect here? + */ +#define SWIG_PTR "_cPtr" + +/* This is the name of the hash where the variables existing only in PHP + * classes are stored. + */ +#define SWIG_DATA "_pData" + +static int constructors = 0; +static String *NOTCLASS = NewString("Not a class"); +static Node *classnode = 0; +static String *module = 0; +static String *cap_module = 0; +static String *prefix = 0; + +static String *shadow_classname = 0; + +static File *f_begin = 0; +static File *f_runtime = 0; +static File *f_runtime_h = 0; +static File *f_h = 0; +static File *f_phpcode = 0; +static File *f_directors = 0; +static File *f_directors_h = 0; +static String *phpfilename = 0; + +static String *s_header; +static String *s_wrappers; +static String *s_init; +static String *r_init; // RINIT user code +static String *s_shutdown; // MSHUTDOWN user code +static String *r_shutdown; // RSHUTDOWN user code +static String *s_vinit; // varinit initialization code. +static String *s_vdecl; +static String *s_cinit; // consttab initialization code. +static String *s_oinit; +static String *s_arginfo; +static String *s_entry; +static String *cs_entry; +static String *all_cs_entry; +static String *pragma_incl; +static String *pragma_code; +static String *pragma_phpinfo; +static String *s_oowrappers; +static String *s_fakeoowrappers; +static String *s_phpclasses; + +/* To reduce code size (generated and compiled) we only want to emit each + * different arginfo once, so we need to track which have been used. + */ +static Hash *arginfo_used; + +/* Variables for using PHP classes */ +static Node *current_class = 0; + +static Hash *shadow_get_vars; +static Hash *shadow_set_vars; +static Hash *zend_types = 0; + +static int shadow = 1; + +static bool class_has_ctor = false; +static String *wrapping_member_constant = NULL; + +// These static variables are used to pass some state from Handlers into functionWrapper +static enum { + standard = 0, + memberfn, + staticmemberfn, + membervar, + staticmembervar, + constructor, + directorconstructor +} wrapperType = standard; + +extern "C" { + static void (*r_prevtracefunc) (const SwigType *t, String *mangled, String *clientdata) = 0; +} + +static void SwigPHP_emit_resource_registrations() { + Iterator ki; + bool emitted_default_dtor = false; + + if (!zend_types) + return; + + ki = First(zend_types); + if (ki.key) + Printf(s_oinit, "\n/* Register resource destructors for pointer types */\n"); + while (ki.key) { + DOH *key = ki.key; + Node *class_node = ki.item; + String *human_name = key; + String *rsrc_dtor_name = NULL; + + // write out body + if (class_node != NOTCLASS) { + String *destructor = Getattr(class_node, "destructor"); + human_name = Getattr(class_node, "sym:name"); + if (!human_name) + human_name = Getattr(class_node, "name"); + // Do we have a known destructor for this type? + if (destructor) { + rsrc_dtor_name = NewStringf("_wrap_destroy%s", key); + // Write out custom destructor function + Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(%s) {\n", rsrc_dtor_name); + Printf(s_wrappers, " %s(rsrc, SWIGTYPE%s->name TSRMLS_CC);\n", destructor, key); + Printf(s_wrappers, "}\n"); + } + } + + if (!rsrc_dtor_name) { + rsrc_dtor_name = NewString("_swig_default_rsrc_destroy"); + if (!emitted_default_dtor) { + // Write out custom destructor function + Printf(s_wrappers, "static ZEND_RSRC_DTOR_FUNC(%s) {\n", rsrc_dtor_name); + Printf(s_wrappers, " efree(rsrc->ptr);\n"); + Printf(s_wrappers, "}\n"); + emitted_default_dtor = true; + } + } + + // declare le_swig_ to store php registration + Printf(s_vdecl, "static int le_swig_%s=0; /* handle for %s */\n", key, human_name); + + // register with php + Printf(s_oinit, "le_swig_%s=zend_register_list_destructors_ex" + "(%s, NULL, (char *)SWIGTYPE%s->name, module_number);\n", key, rsrc_dtor_name, key); + + // store php type in class struct + Printf(s_oinit, "SWIG_TypeClientData(SWIGTYPE%s,&le_swig_%s);\n", key, key); + + Delete(rsrc_dtor_name); + + ki = Next(ki); + } +} + +class PHP5 : public Language { + String *emit_action(Node *n) { + // Adjust wrap:action to add TSRMLS_CC. + String * action = Getattr(n, "wrap:action"); + if (action) { + char * p = Strstr(action, "Swig::DirectorPureVirtualException::raise(\""); + if (p) { + p += strlen("Swig::DirectorPureVirtualException::raise(\""); + p = strchr(p, '"'); + if (p) { + ++p; + Insert(action, (int)(p - Char(action)), " TSRMLS_CC"); + } + } + } + return ::emit_action(n); + } + +public: + PHP5() { + director_language = 1; + } + + /* ------------------------------------------------------------ + * main() + * ------------------------------------------------------------ */ + + virtual void main(int argc, char *argv[]) { + SWIG_library_directory("php5"); + SWIG_config_cppext("cpp"); + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-prefix") == 0) { + if (argv[i + 1]) { + prefix = NewString(argv[i + 1]); + Swig_mark_arg(i); + Swig_mark_arg(i + 1); + i++; + } else { + Swig_arg_error(); + } + } else if ((strcmp(argv[i], "-noshadow") == 0) || (strcmp(argv[i], "-noproxy") == 0)) { + shadow = 0; + Swig_mark_arg(i); + } else if (strcmp(argv[i], "-help") == 0) { + fputs(usage, stdout); + } else if (strcmp(argv[i], "-make") == 0 || + strcmp(argv[i], "-withc") == 0 || + strcmp(argv[i], "-withcxx") == 0) { + Printf(stderr, "*** %s is no longer supported.\n", argv[i]); + SWIG_exit(EXIT_FAILURE); + } else if (strcmp(argv[i], "-phpfull") == 0 || + strcmp(argv[i], "-withlibs") == 0 || + strcmp(argv[i], "-withincs") == 0) { + Printf(stderr, "*** %s is no longer supported.\n*** We recommend building as a dynamically loadable module.\n", argv[i]); + SWIG_exit(EXIT_FAILURE); + } else if (strcmp(argv[i], "-dlname") == 0) { + Printf(stderr, "*** -dlname is no longer supported.\n*** If you want to change the module name, use -module instead.\n"); + SWIG_exit(EXIT_FAILURE); + } + } + + Preprocessor_define("SWIGPHP 1", 0); + // SWIGPHP5 is deprecated, and no longer documented. + Preprocessor_define("SWIGPHP5 1", 0); + SWIG_typemap_lang("php"); + SWIG_config_file("php.swg"); + allow_overloading(); + } + + /* ------------------------------------------------------------ + * top() + * ------------------------------------------------------------ */ + + virtual int top(Node *n) { + + String *filen; + + /* Check if directors are enabled for this module. */ + Node *mod = Getattr(n, "module"); + if (mod) { + Node *options = Getattr(mod, "options"); + if (options && Getattr(options, "directors")) { + allow_directors(); + } + } + + /* Set comparison with null for ConstructorToFunction */ + setSubclassInstanceCheck(NewString("$arg->type != IS_NULL")); + + /* Initialize all of the output files */ + String *outfile = Getattr(n, "outfile"); + String *outfile_h = Getattr(n, "outfile_h"); + + /* main output file */ + f_begin = NewFile(outfile, "w", SWIG_output_files()); + if (!f_begin) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } + f_runtime = NewStringEmpty(); + + /* sections of the output file */ + s_init = NewString("/* init section */\n"); + r_init = NewString("/* rinit section */\n"); + s_shutdown = NewString("/* shutdown section */\n"); + r_shutdown = NewString("/* rshutdown section */\n"); + s_header = NewString("/* header section */\n"); + s_wrappers = NewString("/* wrapper section */\n"); + /* subsections of the init section */ + s_vinit = NewString("/* vinit subsection */\n"); + s_vdecl = NewString("/* vdecl subsection */\n"); + s_cinit = NewString("/* cinit subsection */\n"); + s_oinit = NewString("/* oinit subsection */\n"); + pragma_phpinfo = NewStringEmpty(); + s_phpclasses = NewString("/* PHP Proxy Classes */\n"); + f_directors_h = NewStringEmpty(); + f_directors = NewStringEmpty(); + + if (directorsEnabled()) { + f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files()); + if (!f_runtime_h) { + FileErrorDisplay(outfile_h); + SWIG_exit(EXIT_FAILURE); + } + } + + /* Register file targets with the SWIG file handler */ + Swig_register_filebyname("begin", f_begin); + Swig_register_filebyname("runtime", f_runtime); + Swig_register_filebyname("init", s_init); + Swig_register_filebyname("rinit", r_init); + Swig_register_filebyname("shutdown", s_shutdown); + Swig_register_filebyname("rshutdown", r_shutdown); + Swig_register_filebyname("header", s_header); + Swig_register_filebyname("wrapper", s_wrappers); + Swig_register_filebyname("director", f_directors); + Swig_register_filebyname("director_h", f_directors_h); + + Swig_banner(f_begin); + + Printf(f_runtime, "\n\n#ifndef SWIGPHP\n#define SWIGPHP\n#endif\n\n"); + + if (directorsEnabled()) { + Printf(f_runtime, "#define SWIG_DIRECTORS\n"); + } + + /* Set the module name */ + module = Copy(Getattr(n, "name")); + cap_module = NewStringf("%(upper)s", module); + if (!prefix) + prefix = NewStringEmpty(); + + Printf(f_runtime, "#define SWIG_PREFIX \"%s\"\n", prefix); + Printf(f_runtime, "#define SWIG_PREFIX_LEN %lu\n", (unsigned long)Len(prefix)); + + if (directorsEnabled()) { + Swig_banner(f_directors_h); + Printf(f_directors_h, "\n"); + Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", cap_module); + Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", cap_module); + + String *filename = Swig_file_filename(outfile_h); + Printf(f_directors, "\n#include \"%s\"\n\n", filename); + Delete(filename); + } + + /* PHP module file */ + filen = NewStringEmpty(); + Printv(filen, SWIG_output_directory(), module, ".php", NIL); + phpfilename = NewString(filen); + + f_phpcode = NewFile(filen, "w", SWIG_output_files()); + if (!f_phpcode) { + FileErrorDisplay(filen); + SWIG_exit(EXIT_FAILURE); + } + + Printf(f_phpcode, "error_msg = default_error_msg;\n"); + Printf(s_header, " globals->error_code = default_error_code;\n"); + Printf(s_header, "}\n"); + + Printf(s_header, "static void %s_destroy_globals(zend_%s_globals * globals) { (void)globals; }\n", module, module); + + Printf(s_header, "\n"); + Printf(s_header, "static void SWIG_ResetError(TSRMLS_D) {\n"); + Printf(s_header, " SWIG_ErrorMsg() = default_error_msg;\n"); + Printf(s_header, " SWIG_ErrorCode() = default_error_code;\n"); + Printf(s_header, "}\n"); + + Append(s_header, "\n"); + Printf(s_header, "ZEND_NAMED_FUNCTION(_wrap_swig_%s_alter_newobject) {\n", module); + Append(s_header, " zval **args[2];\n"); + Append(s_header, " swig_object_wrapper *value;\n"); + Append(s_header, " int type;\n"); + Append(s_header, "\n"); + Append(s_header, " SWIG_ResetError(TSRMLS_C);\n"); + Append(s_header, " if(ZEND_NUM_ARGS() != 2 || zend_get_parameters_array_ex(2, args) != SUCCESS) {\n"); + Append(s_header, " WRONG_PARAM_COUNT;\n"); + Append(s_header, " }\n"); + Append(s_header, "\n"); + Append(s_header, " value = (swig_object_wrapper *) zend_list_find((*args[0])->value.lval, &type);\n"); + Append(s_header, " value->newobject = zval_is_true(*args[1]);\n"); + Append(s_header, "\n"); + Append(s_header, " return;\n"); + Append(s_header, "}\n"); + Printf(s_header, "ZEND_NAMED_FUNCTION(_wrap_swig_%s_get_newobject) {\n", module); + Append(s_header, " zval **args[1];\n"); + Append(s_header, " swig_object_wrapper *value;\n"); + Append(s_header, " int type;\n"); + Append(s_header, "\n"); + Append(s_header, " SWIG_ResetError(TSRMLS_C);\n"); + Append(s_header, " if(ZEND_NUM_ARGS() != 1 || zend_get_parameters_array_ex(1, args) != SUCCESS) {\n"); + Append(s_header, " WRONG_PARAM_COUNT;\n"); + Append(s_header, " }\n"); + Append(s_header, "\n"); + Append(s_header, " value = (swig_object_wrapper *) zend_list_find((*args[0])->value.lval, &type);\n"); + Append(s_header, " RETVAL_LONG(value->newobject);\n"); + Append(s_header, "\n"); + Append(s_header, " return;\n"); + Append(s_header, "}\n"); + + Printf(s_header, "#define SWIG_name \"%s\"\n", module); + Printf(s_header, "#ifdef __cplusplus\n"); + Printf(s_header, "extern \"C\" {\n"); + Printf(s_header, "#endif\n"); + Printf(s_header, "#include \"php.h\"\n"); + Printf(s_header, "#include \"php_ini.h\"\n"); + Printf(s_header, "#include \"ext/standard/info.h\"\n"); + Printf(s_header, "#include \"php_%s.h\"\n", module); + Printf(s_header, "#ifdef __cplusplus\n"); + Printf(s_header, "}\n"); + Printf(s_header, "#endif\n\n"); + + if (directorsEnabled()) { + // Insert director runtime + Swig_insert_file("director_common.swg", s_header); + Swig_insert_file("director.swg", s_header); + } + + /* Create the .h file too */ + filen = NewStringEmpty(); + Printv(filen, SWIG_output_directory(), "php_", module, ".h", NIL); + f_h = NewFile(filen, "w", SWIG_output_files()); + if (!f_h) { + FileErrorDisplay(filen); + SWIG_exit(EXIT_FAILURE); + } + + Swig_banner(f_h); + + Printf(f_h, "\n"); + Printf(f_h, "#ifndef PHP_%s_H\n", cap_module); + Printf(f_h, "#define PHP_%s_H\n\n", cap_module); + Printf(f_h, "extern zend_module_entry %s_module_entry;\n", module); + Printf(f_h, "#define phpext_%s_ptr &%s_module_entry\n\n", module, module); + Printf(f_h, "#ifdef PHP_WIN32\n"); + Printf(f_h, "# define PHP_%s_API __declspec(dllexport)\n", cap_module); + Printf(f_h, "#else\n"); + Printf(f_h, "# define PHP_%s_API\n", cap_module); + Printf(f_h, "#endif\n\n"); + Printf(f_h, "#ifdef ZTS\n"); + Printf(f_h, "#include \"TSRM.h\"\n"); + Printf(f_h, "#endif\n\n"); + Printf(f_h, "PHP_MINIT_FUNCTION(%s);\n", module); + Printf(f_h, "PHP_MSHUTDOWN_FUNCTION(%s);\n", module); + Printf(f_h, "PHP_RINIT_FUNCTION(%s);\n", module); + Printf(f_h, "PHP_RSHUTDOWN_FUNCTION(%s);\n", module); + Printf(f_h, "PHP_MINFO_FUNCTION(%s);\n\n", module); + + /* start the arginfo section */ + s_arginfo = NewString("/* arginfo subsection */\n"); + arginfo_used = NewHash(); + + /* start the function entry section */ + s_entry = NewString("/* entry subsection */\n"); + + /* holds all the per-class function entry sections */ + all_cs_entry = NewString("/* class entry subsection */\n"); + cs_entry = NULL; + + Printf(s_entry, "/* Every non-class user visible function must have an entry here */\n"); + Printf(s_entry, "static zend_function_entry %s_functions[] = {\n", module); + + /* start the init section */ + Append(s_init, "#if ZEND_MODULE_API_NO <= 20090626\n"); + Append(s_init, "#undef ZEND_MODULE_BUILD_ID\n"); + Append(s_init, "#define ZEND_MODULE_BUILD_ID (char*)\"API\" ZEND_TOSTR(ZEND_MODULE_API_NO) ZEND_BUILD_TS ZEND_BUILD_DEBUG ZEND_BUILD_SYSTEM ZEND_BUILD_EXTRA\n"); + Append(s_init, "#endif\n"); + Printv(s_init, "zend_module_entry ", module, "_module_entry = {\n", NIL); + Printf(s_init, " STANDARD_MODULE_HEADER,\n"); + Printf(s_init, " (char*)\"%s\",\n", module); + Printf(s_init, " %s_functions,\n", module); + Printf(s_init, " PHP_MINIT(%s),\n", module); + Printf(s_init, " PHP_MSHUTDOWN(%s),\n", module); + Printf(s_init, " PHP_RINIT(%s),\n", module); + Printf(s_init, " PHP_RSHUTDOWN(%s),\n", module); + Printf(s_init, " PHP_MINFO(%s),\n", module); + Printf(s_init, " NO_VERSION_YET,\n"); + Printf(s_init, " STANDARD_MODULE_PROPERTIES\n"); + Printf(s_init, "};\n"); + Printf(s_init, "zend_module_entry* SWIG_module_entry = &%s_module_entry;\n\n", module); + + Printf(s_init, "#ifdef __cplusplus\n"); + Printf(s_init, "extern \"C\" {\n"); + Printf(s_init, "#endif\n"); + // We want to write "SWIGEXPORT ZEND_GET_MODULE(%s)" but ZEND_GET_MODULE + // in PHP5 has "extern "C" { ... }" around it so we can't do that. + Printf(s_init, "SWIGEXPORT zend_module_entry *get_module(void) { return &%s_module_entry; }\n", module); + Printf(s_init, "#ifdef __cplusplus\n"); + Printf(s_init, "}\n"); + Printf(s_init, "#endif\n\n"); + + /* We have to register the constants before they are (possibly) used + * by the pointer typemaps. This all needs re-arranging really as + * things are being called in the wrong order + */ + Printf(s_init, "#define SWIG_php_minit PHP_MINIT_FUNCTION(%s)\n", module); + + /* Emit all of the code */ + Language::top(n); + + SwigPHP_emit_resource_registrations(); + // Printv(s_init,s_resourcetypes,NIL); + /* We need this after all classes written out by ::top */ + Printf(s_oinit, "CG(active_class_entry) = NULL;\n"); + Printf(s_oinit, "/* end oinit subsection */\n"); + Printf(s_init, "%s\n", s_oinit); + + /* Constants generated during top call */ + Printf(s_cinit, "/* end cinit subsection */\n"); + Printf(s_init, "%s\n", s_cinit); + Clear(s_cinit); + Delete(s_cinit); + + Printf(s_init, " return SUCCESS;\n"); + Printf(s_init, "}\n\n"); + + // Now do REQUEST init which holds any user specified %rinit, and also vinit + Printf(s_init, "PHP_RINIT_FUNCTION(%s)\n{\n", module); + Printf(s_init, "%s\n", r_init); + + /* finish our init section which will have been used by class wrappers */ + Printf(s_vinit, "/* end vinit subsection */\n"); + Printf(s_init, "%s\n", s_vinit); + Clear(s_vinit); + Delete(s_vinit); + + Printf(s_init, " return SUCCESS;\n"); + Printf(s_init, "}\n\n"); + + Printv(s_init, "PHP_MSHUTDOWN_FUNCTION(", module, ")\n" + "{\n", + s_shutdown, + "#ifdef ZTS\n" + " ts_free_id(", module, "_globals_id);\n" + "#endif\n" + " return SUCCESS;\n" + "}\n\n", NIL); + + Printf(s_init, "PHP_RSHUTDOWN_FUNCTION(%s)\n{\n", module); + Printf(s_init, "%s\n", r_shutdown); + Printf(s_init, " return SUCCESS;\n"); + Printf(s_init, "}\n\n"); + + Printf(s_init, "PHP_MINFO_FUNCTION(%s)\n{\n", module); + Printf(s_init, "%s", pragma_phpinfo); + Printf(s_init, "}\n"); + Printf(s_init, "/* end init section */\n"); + + Printf(f_h, "#endif /* PHP_%s_H */\n", cap_module); + + Delete(f_h); + + String *type_table = NewStringEmpty(); + SwigType_emit_type_table(f_runtime, type_table); + Printf(s_header, "%s", type_table); + Delete(type_table); + + /* Oh dear, more things being called in the wrong order. This whole + * function really needs totally redoing. + */ + + if (directorsEnabled()) { + Dump(f_directors_h, f_runtime_h); + Printf(f_runtime_h, "\n"); + Printf(f_runtime_h, "#endif\n"); + Delete(f_runtime_h); + } + + Printf(s_header, "/* end header section */\n"); + Printf(s_wrappers, "/* end wrapper section */\n"); + Printf(s_vdecl, "/* end vdecl subsection */\n"); + + Dump(f_runtime, f_begin); + Printv(f_begin, s_header, NIL); + if (directorsEnabled()) { + Dump(f_directors, f_begin); + } + Printv(f_begin, s_vdecl, s_wrappers, NIL); + Printv(f_begin, all_cs_entry, "\n\n", s_arginfo, "\n\n", s_entry, + " SWIG_ZEND_NAMED_FE(swig_", module, "_alter_newobject,_wrap_swig_", module, "_alter_newobject,NULL)\n" + " SWIG_ZEND_NAMED_FE(swig_", module, "_get_newobject,_wrap_swig_", module, "_get_newobject,NULL)\n" + " ZEND_FE_END\n};\n\n", NIL); + Printv(f_begin, s_init, NIL); + Delete(s_header); + Delete(s_wrappers); + Delete(s_init); + Delete(s_vdecl); + Delete(all_cs_entry); + Delete(s_entry); + Delete(s_arginfo); + Delete(f_runtime); + Delete(f_begin); + Delete(arginfo_used); + + Printf(f_phpcode, "%s\n%s\n", pragma_incl, pragma_code); + if (s_fakeoowrappers) { + Printf(f_phpcode, "abstract class %s {", Len(prefix) ? prefix : module); + Printf(f_phpcode, "%s", s_fakeoowrappers); + Printf(f_phpcode, "}\n\n"); + Delete(s_fakeoowrappers); + s_fakeoowrappers = NULL; + } + Printf(f_phpcode, "%s\n?>\n", s_phpclasses); + Delete(f_phpcode); + + return SWIG_OK; + } + + /* Just need to append function names to function table to register with PHP. */ + void create_command(String *cname, String *iname, Node *n) { + // This is for the single main zend_function_entry record + Printf(f_h, "ZEND_NAMED_FUNCTION(%s);\n", iname); + + // We want to only emit each different arginfo once, as that reduces the + // size of both the generated source code and the compiled extension + // module. To do this, we name the arginfo to encode the number of + // parameters and which (if any) are passed by reference by using a + // sequence of 0s (for non-reference) and 1s (for by references). + ParmList *l = Getattr(n, "parms"); + String * arginfo_code = NewStringEmpty(); + for (Parm *p = l; p; p = Getattr(p, "tmap:in:next")) { + /* Ignored parameters */ + if (checkAttribute(p, "tmap:in:numinputs", "0")) { + continue; + } + Append(arginfo_code, GetFlag(p, "tmap:in:byref") ? "1" : "0"); + } + + if (!GetFlag(arginfo_used, arginfo_code)) { + // Not had this one before, so emit it. + SetFlag(arginfo_used, arginfo_code); + Printf(s_arginfo, "ZEND_BEGIN_ARG_INFO_EX(swig_arginfo_%s, 0, 0, 0)\n", arginfo_code); + for (const char * p = Char(arginfo_code); *p; ++p) { + Printf(s_arginfo, " ZEND_ARG_PASS_INFO(%c)\n", *p); + } + Printf(s_arginfo, "ZEND_END_ARG_INFO()\n"); + } + + String * s = cs_entry; + if (!s) s = s_entry; + Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,swig_arginfo_%s)\n", cname, iname, arginfo_code); + Delete(arginfo_code); + } + + /* ------------------------------------------------------------ + * dispatchFunction() + * ------------------------------------------------------------ */ + void dispatchFunction(Node *n) { + /* Last node in overloaded chain */ + + int maxargs; + String *tmp = NewStringEmpty(); + if (Swig_directorclass(n) && wrapperType == directorconstructor) { + /* We have an extra 'this' parameter. */ + SetFlag(n, "wrap:this"); + } + String *dispatch = Swig_overload_dispatch(n, "%s(INTERNAL_FUNCTION_PARAM_PASSTHRU); return;", &maxargs); + + /* Generate a dispatch wrapper for all overloaded functions */ + + Wrapper *f = NewWrapper(); + String *symname = Getattr(n, "sym:name"); + String *wname = Swig_name_wrapper(symname); + + create_command(symname, wname, n); + Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); + + Wrapper_add_local(f, "argc", "int argc"); + + Printf(tmp, "zval **argv[%d]", maxargs); + Wrapper_add_local(f, "argv", tmp); + + Printf(f->code, "argc = ZEND_NUM_ARGS();\n"); + + Printf(f->code, "zend_get_parameters_array_ex(argc,argv);\n"); + + Replaceall(dispatch, "$args", "self,args"); + + Printv(f->code, dispatch, "\n", NIL); + + Printf(f->code, "SWIG_ErrorCode() = E_ERROR;\n"); + Printf(f->code, "SWIG_ErrorMsg() = \"No matching function for overloaded '%s'\";\n", symname); + Printv(f->code, "SWIG_FAIL(TSRMLS_C);\n", NIL); + + Printv(f->code, "}\n", NIL); + Wrapper_print(f, s_wrappers); + + DelWrapper(f); + Delete(dispatch); + Delete(tmp); + Delete(wname); + } + + /* ------------------------------------------------------------ + * functionWrapper() + * ------------------------------------------------------------ */ + + /* Helper method for PHP5::functionWrapper */ + bool is_class(SwigType *t) { + Node *n = classLookup(t); + if (n) { + String *r = Getattr(n, "php:proxy"); // Set by classDeclaration() + if (!r) + r = Getattr(n, "sym:name"); // Not seen by classDeclaration yet, but this is the name + if (r) + return true; + } + return false; + } + + virtual int functionWrapper(Node *n) { + String *name = GetChar(n, "name"); + String *iname = GetChar(n, "sym:name"); + SwigType *d = Getattr(n, "type"); + ParmList *l = Getattr(n, "parms"); + String *nodeType = Getattr(n, "nodeType"); + int newobject = GetFlag(n, "feature:new"); + int constructor = (Cmp(nodeType, "constructor") == 0); + + Parm *p; + int i; + int numopt; + String *tm; + Wrapper *f; + + String *wname; + int overloaded = 0; + String *overname = 0; + + if (Cmp(nodeType, "destructor") == 0) { + // We just generate the Zend List Destructor and let Zend manage the + // reference counting. There's no explicit destructor, but the user can + // just do `$obj = null;' to remove a reference to an object. + return CreateZendListDestructor(n); + } + // Test for overloading; + if (Getattr(n, "sym:overloaded")) { + overloaded = 1; + overname = Getattr(n, "sym:overname"); + } else { + if (!addSymbol(iname, n)) + return SWIG_ERROR; + } + + wname = Swig_name_wrapper(iname); + if (overname) { + Printf(wname, "%s", overname); + } + + f = NewWrapper(); + + String *outarg = NewStringEmpty(); + String *cleanup = NewStringEmpty(); + + Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); + + emit_parameter_variables(l, f); + /* Attach standard typemaps */ + + emit_attach_parmmaps(l, f); + // Not issued for overloaded functions. + if (!overloaded) { + create_command(iname, wname, n); + } + + // wrap:parms is used by overload resolution. + Setattr(n, "wrap:parms", l); + + int num_arguments = emit_num_arguments(l); + int num_required = emit_num_required(l); + numopt = num_arguments - num_required; + + if (wrapperType == directorconstructor) + num_arguments++; + + if (num_arguments > 0) { + String *args = NewStringEmpty(); + if (wrapperType == directorconstructor) + Wrapper_add_local(f, "arg0", "zval *arg0"); + Printf(args, "zval **args[%d]", num_arguments); + Wrapper_add_local(f, "args", args); + Delete(args); + args = NULL; + } + + // This generated code may be called: + // 1) as an object method, or + // 2) as a class-method/function (without a "this_ptr") + // Option (1) has "this_ptr" for "this", option (2) needs it as + // first parameter + + // NOTE: possible we ignore this_ptr as a param for native constructor + + Printf(f->code, "SWIG_ResetError(TSRMLS_C);\n"); + + if (numopt > 0) { // membervariable wrappers do not have optional args + Wrapper_add_local(f, "arg_count", "int arg_count"); + Printf(f->code, "arg_count = ZEND_NUM_ARGS();\n"); + Printf(f->code, "if(arg_count<%d || arg_count>%d ||\n", num_required, num_arguments); + Printf(f->code, " zend_get_parameters_array_ex(arg_count,args)!=SUCCESS)\n"); + Printf(f->code, "\tWRONG_PARAM_COUNT;\n\n"); + } else { + if (num_arguments == 0) { + Printf(f->code, "if(ZEND_NUM_ARGS() != 0) {\n"); + } else { + Printf(f->code, "if(ZEND_NUM_ARGS() != %d || zend_get_parameters_array_ex(%d, args) != SUCCESS) {\n", num_arguments, num_arguments); + } + Printf(f->code, "WRONG_PARAM_COUNT;\n}\n\n"); + } + if (wrapperType == directorconstructor) + Printf(f->code, "arg0 = *args[0];\n \n"); + + /* Now convert from PHP to C variables */ + // At this point, argcount if used is the number of deliberately passed args + // not including this_ptr even if it is used. + // It means error messages may be out by argbase with error + // reports. We can either take argbase into account when raising + // errors, or find a better way of dealing with _thisptr. + // I would like, if objects are wrapped, to assume _thisptr is always + // _this and not the first argument. + // This may mean looking at Language::memberfunctionHandler + + int limit = num_arguments; + if (wrapperType == directorconstructor) + limit--; + for (i = 0, p = l; i < limit; i++) { + String *source; + + /* Skip ignored arguments */ + //while (Getattr(p,"tmap:ignore")) { p = Getattr(p,"tmap:ignore:next");} + while (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + } + + SwigType *pt = Getattr(p, "type"); + + if (wrapperType == directorconstructor) { + source = NewStringf("args[%d]", i+1); + } else { + source = NewStringf("args[%d]", i); + } + + String *ln = Getattr(p, "lname"); + + /* Check if optional */ + if (i >= num_required) { + Printf(f->code, "\tif(arg_count > %d) {\n", i); + } + + if ((tm = Getattr(p, "tmap:in"))) { + Replaceall(tm, "$source", source); + Replaceall(tm, "$target", ln); + Replaceall(tm, "$input", source); + Setattr(p, "emit:input", source); + Printf(f->code, "%s\n", tm); + if (i == 0 && Getattr(p, "self")) { + Printf(f->code, "\tif(!arg1) SWIG_PHP_Error(E_ERROR, \"this pointer is NULL\");\n"); + } + p = Getattr(p, "tmap:in:next"); + if (i >= num_required) { + Printf(f->code, "}\n"); + } + continue; + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + } + if (i >= num_required) { + Printf(f->code, "\t}\n"); + } + Delete(source); + } + + if (is_member_director(n)) { + Wrapper_add_local(f, "upcall", "bool upcall = false"); + Printf(f->code, "upcall = !Swig::Director::swig_is_overridden_method((char *)\"%s%s\", (char *)\"%s\" TSRMLS_CC);\n", + prefix, Swig_class_name(Swig_methodclass(n)), name); + } + + Swig_director_emit_dynamic_cast(n, f); + + /* Insert constraint checking code */ + for (p = l; p;) { + if ((tm = Getattr(p, "tmap:check"))) { + Replaceall(tm, "$target", Getattr(p, "lname")); + Printv(f->code, tm, "\n", NIL); + p = Getattr(p, "tmap:check:next"); + } else { + p = nextSibling(p); + } + } + + /* Insert cleanup code */ + for (i = 0, p = l; p; i++) { + if ((tm = Getattr(p, "tmap:freearg"))) { + Replaceall(tm, "$source", Getattr(p, "lname")); + Printv(cleanup, tm, "\n", NIL); + p = Getattr(p, "tmap:freearg:next"); + } else { + p = nextSibling(p); + } + } + + /* Insert argument output code */ + bool hasargout = false; + for (i = 0, p = l; p; i++) { + if ((tm = Getattr(p, "tmap:argout"))) { + hasargout = true; + Replaceall(tm, "$source", Getattr(p, "lname")); + // Replaceall(tm,"$input",Getattr(p,"lname")); + Replaceall(tm, "$target", "return_value"); + Replaceall(tm, "$result", "return_value"); + Replaceall(tm, "$arg", Getattr(p, "emit:input")); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(outarg, tm, "\n", NIL); + p = Getattr(p, "tmap:argout:next"); + } else { + p = nextSibling(p); + } + } + + Setattr(n, "wrap:name", wname); + + /* emit function call */ + String *actioncode = emit_action(n); + + if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) { + Replaceall(tm, "$input", Swig_cresult_name()); + Replaceall(tm, "$source", Swig_cresult_name()); + Replaceall(tm, "$target", "return_value"); + Replaceall(tm, "$result", "return_value"); + Replaceall(tm, "$owner", newobject ? "1" : "0"); + Printf(f->code, "%s\n", tm); + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name); + } + emit_return_variable(n, d, f); + + if (outarg) { + Printv(f->code, outarg, NIL); + } + + if (cleanup) { + Printv(f->code, cleanup, NIL); + } + + /* Look to see if there is any newfree cleanup code */ + if (GetFlag(n, "feature:new")) { + if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { + Printf(f->code, "%s\n", tm); + Delete(tm); + } + } + + /* See if there is any return cleanup code */ + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Printf(f->code, "%s\n", tm); + Delete(tm); + } + + Printf(f->code, "thrown:\n"); + Printf(f->code, "return;\n"); + + /* Error handling code */ + Printf(f->code, "fail:\n"); + Printv(f->code, cleanup, NIL); + Append(f->code, "SWIG_FAIL(TSRMLS_C);\n"); + + Printf(f->code, "}\n"); + + Replaceall(f->code, "$cleanup", cleanup); + Replaceall(f->code, "$symname", iname); + + Wrapper_print(f, s_wrappers); + DelWrapper(f); + f = NULL; + + if (overloaded && !Getattr(n, "sym:nextSibling")) { + dispatchFunction(n); + } + + Delete(wname); + wname = NULL; + + if (!shadow) { + return SWIG_OK; + } + + // Handle getters and setters. + if (wrapperType == membervar) { + const char *p = Char(iname); + if (strlen(p) > 4) { + p += strlen(p) - 4; + String *varname = Getattr(n, "membervariableHandler:sym:name"); + if (strcmp(p, "_get") == 0) { + Setattr(shadow_get_vars, varname, Getattr(n, "type")); + } else if (strcmp(p, "_set") == 0) { + Setattr(shadow_set_vars, varname, iname); + } + } + return SWIG_OK; + } + + // Only look at non-overloaded methods and the last entry in each overload + // chain (we check the last so that wrap:parms and wrap:name have been set + // for them all). + if (overloaded && Getattr(n, "sym:nextSibling") != 0) + return SWIG_OK; + + if (!s_oowrappers) + s_oowrappers = NewStringEmpty(); + + if (newobject || wrapperType == memberfn || wrapperType == staticmemberfn || wrapperType == standard || wrapperType == staticmembervar) { + bool handle_as_overload = false; + String **arg_names; + String **arg_values; + // Method or static method or plain function. + const char *methodname = 0; + String *output = s_oowrappers; + if (constructor) { + class_has_ctor = true; + // Skip the Foo:: prefix. + char *ptr = strrchr(GetChar(Swig_methodclass(n), "sym:name"), ':'); + if (ptr) { + ptr++; + } else { + ptr = GetChar(Swig_methodclass(n), "sym:name"); + } + if (strcmp(ptr, GetChar(n, "constructorHandler:sym:name")) == 0) { + methodname = "__construct"; + } else { + // The class has multiple constructors and this one is + // renamed, so this will be a static factory function + methodname = GetChar(n, "constructorHandler:sym:name"); + } + } else if (wrapperType == memberfn) { + methodname = Char(Getattr(n, "memberfunctionHandler:sym:name")); + } else if (wrapperType == staticmemberfn) { + methodname = Char(Getattr(n, "staticmemberfunctionHandler:sym:name")); + } else if (wrapperType == staticmembervar) { + // Static member variable, wrapped as a function due to PHP limitations. + methodname = Char(Getattr(n, "staticmembervariableHandler:sym:name")); + } else { // wrapperType == standard + methodname = Char(iname); + if (!s_fakeoowrappers) + s_fakeoowrappers = NewStringEmpty(); + output = s_fakeoowrappers; + } + + bool really_overloaded = overloaded ? true : false; + int min_num_of_arguments = emit_num_required(l); + int max_num_of_arguments = emit_num_arguments(l); + + Hash *ret_types = NewHash(); + Setattr(ret_types, d, d); + + bool non_void_return = (Cmp(d, "void") != 0); + + if (overloaded) { + // Look at all the overloaded versions of this method in turn to + // decide if it's really an overloaded method, or just one where some + // parameters have default values. + Node *o = Getattr(n, "sym:overloaded"); + while (o) { + if (o == n) { + o = Getattr(o, "sym:nextSibling"); + continue; + } + + SwigType *d2 = Getattr(o, "type"); + if (!d2) { + assert(constructor); + } else if (!Getattr(ret_types, d2)) { + Setattr(ret_types, d2, d2); + non_void_return = non_void_return || (Cmp(d2, "void") != 0); + } + + ParmList *l2 = Getattr(o, "wrap:parms"); + int num_arguments = emit_num_arguments(l2); + int num_required = emit_num_required(l2); + if (num_required < min_num_of_arguments) + min_num_of_arguments = num_required; + + if (num_arguments > max_num_of_arguments) { + max_num_of_arguments = num_arguments; + } + o = Getattr(o, "sym:nextSibling"); + } + + o = Getattr(n, "sym:overloaded"); + while (o) { + if (o == n) { + o = Getattr(o, "sym:nextSibling"); + continue; + } + + ParmList *l2 = Getattr(o, "wrap:parms"); + Parm *p = l, *p2 = l2; + if (wrapperType == memberfn) { + p = nextSibling(p); + p2 = nextSibling(p2); + } + while (p && p2) { + if (Cmp(Getattr(p, "type"), Getattr(p2, "type")) != 0) + break; + if (Cmp(Getattr(p, "name"), Getattr(p2, "name")) != 0) + break; + String *value = Getattr(p, "value"); + String *value2 = Getattr(p2, "value"); + if (value && !value2) + break; + if (!value && value2) + break; + if (value) { + if (Cmp(value, value2) != 0) + break; + } + p = nextSibling(p); + p2 = nextSibling(p2); + } + if (p && p2) + break; + // One parameter list is a prefix of the other, so check that all + // remaining parameters of the longer list are optional. + if (p2) + p = p2; + while (p && Getattr(p, "value")) + p = nextSibling(p); + if (p) + break; + o = Getattr(o, "sym:nextSibling"); + } + if (!o) { + // This "overloaded method" is really just one with default args. + really_overloaded = false; + } + } + + if (wrapperType == memberfn) { + // Allow for the "this" pointer. + --min_num_of_arguments; + --max_num_of_arguments; + } + + arg_names = (String **) malloc(max_num_of_arguments * sizeof(String *)); + if (!arg_names) { + /* FIXME: How should this be handled? The rest of SWIG just seems + * to not bother checking for malloc failing! */ + fprintf(stderr, "Malloc failed!\n"); + exit(1); + } + for (i = 0; i < max_num_of_arguments; ++i) { + arg_names[i] = NULL; + } + + arg_values = (String **) malloc(max_num_of_arguments * sizeof(String *)); + if (!arg_values) { + /* FIXME: How should this be handled? The rest of SWIG just seems + * to not bother checking for malloc failing! */ + fprintf(stderr, "Malloc failed!\n"); + exit(1); + } + for (i = 0; i < max_num_of_arguments; ++i) { + arg_values[i] = NULL; + } + + Node *o; + if (overloaded) { + o = Getattr(n, "sym:overloaded"); + } else { + o = n; + } + while (o) { + int argno = 0; + Parm *p = Getattr(o, "wrap:parms"); + if (wrapperType == memberfn) + p = nextSibling(p); + while (p) { + if (GetInt(p, "tmap:in:numinputs") == 0) { + p = nextSibling(p); + continue; + } + assert(0 <= argno && argno < max_num_of_arguments); + String *&pname = arg_names[argno]; + const char *pname_cstr = GetChar(p, "name"); + // Just get rid of the C++ namespace part for now. + const char *ptr = NULL; + if (pname_cstr && (ptr = strrchr(pname_cstr, ':'))) { + pname_cstr = ptr + 1; + } + if (!pname_cstr) { + // Unnamed parameter, e.g. int foo(int); + } else if (!pname) { + pname = NewString(pname_cstr); + } else { + size_t len = strlen(pname_cstr); + size_t spc = 0; + size_t len_pname = strlen(Char(pname)); + while (spc + len <= len_pname) { + if (strncmp(pname_cstr, Char(pname) + spc, len) == 0) { + char ch = ((char *) Char(pname))[spc + len]; + if (ch == '\0' || ch == ' ') { + // Already have this pname_cstr. + pname_cstr = NULL; + break; + } + } + char *p = strchr(Char(pname) + spc, ' '); + if (!p) + break; + spc = (p + 4) - Char(pname); + } + if (pname_cstr) { + Printf(pname, " or_%s", pname_cstr); + } + } + String *value = NewString(Getattr(p, "value")); + if (Len(value)) { + /* Check that value is a valid constant in PHP (and adjust it if + * necessary, or replace it with "?" if it's just not valid). */ + SwigType *type = Getattr(p, "type"); + switch (SwigType_type(type)) { + case T_BOOL: { + if (Strcmp(value, "true") == 0 || Strcmp(value, "false") == 0) + break; + char *p; + errno = 0; + long n = strtol(Char(value), &p, 0); + Clear(value); + if (errno || *p) { + Append(value, "?"); + } else if (n) { + Append(value, "true"); + } else { + Append(value, "false"); + } + break; + } + case T_CHAR: + case T_SCHAR: + case T_SHORT: + case T_INT: + case T_LONG: + case T_LONGLONG: { + char *p; + errno = 0; + long n = strtol(Char(value), &p, 0); + (void) n; + if (errno || *p) { + Clear(value); + Append(value, "?"); + } + break; + } + case T_UCHAR: + case T_USHORT: + case T_UINT: + case T_ULONG: + case T_ULONGLONG: { + char *p; + errno = 0; + unsigned int n = strtoul(Char(value), &p, 0); + (void) n; + if (errno || *p) { + Clear(value); + Append(value, "?"); + } + break; + } + case T_FLOAT: + case T_DOUBLE: + case T_LONGDOUBLE: { + char *p; + errno = 0; + /* FIXME: strtod is locale dependent... */ + double val = strtod(Char(value), &p); + if (errno || *p) { + Clear(value); + Append(value, "?"); + } else if (strchr(Char(value), '.') == 0) { + // Ensure value is a double constant, not an integer one. + Append(value, ".0"); + double val2 = strtod(Char(value), &p); + if (errno || *p || val != val2) { + Clear(value); + Append(value, "?"); + } + } + break; + } + case T_STRING: + if (Len(value) < 2) { + // How can a string (including "" be less than 2 characters?) + Clear(value); + Append(value, "?"); + } else { + const char *v = Char(value); + if (v[0] != '"' || v[Len(value) - 1] != '"') { + Clear(value); + Append(value, "?"); + } + // Strings containing "$" require special handling, but we do + // that later. + } + break; + case T_VOID: + assert(false); + break; + case T_POINTER: { + const char *v = Char(value); + if (v[0] == '(') { + // Handle "(void*)0", "(TYPE*)0", "(char*)NULL", etc. + v += strcspn(v + 1, "*()") + 1; + if (*v == '*') { + do { + v++; + v += strspn(v, " \t"); + } while (*v == '*'); + if (*v++ == ')') { + v += strspn(v, " \t"); + String * old = value; + value = NewString(v); + Delete(old); + } + } + } + if (Strcmp(value, "NULL") == 0 || + Strcmp(value, "nullptr") == 0 || + Strcmp(value, "0") == 0 || + Strcmp(value, "0L") == 0) { + Clear(value); + Append(value, "null"); + } else { + Clear(value); + Append(value, "?"); + } + break; + } + default: + /* Safe default */ + Clear(value); + Append(value, "?"); + break; + } + + if (!arg_values[argno]) { + arg_values[argno] = value; + value = NULL; + } else if (Cmp(arg_values[argno], value) != 0) { + // If a parameter has two different default values in + // different overloaded forms of the function, we can't + // set its default in PHP. Flag this by setting its + // default to `?'. + Delete(arg_values[argno]); + arg_values[argno] = NewString("?"); + } + } else if (arg_values[argno]) { + // This argument already has a default value in another overloaded + // form, but doesn't in this form. So don't try to do anything + // clever, just let the C wrappers resolve the overload and set the + // default values. + // + // This handling is safe, but I'm wondering if it may be overly + // conservative (FIXME) in some cases. It seems it's only bad when + // there's an overloaded form with the appropriate number of + // parameters which doesn't want the default value, but I need to + // think about this more. + Delete(arg_values[argno]); + arg_values[argno] = NewString("?"); + } + Delete(value); + p = nextSibling(p); + ++argno; + } + if (!really_overloaded) + break; + o = Getattr(o, "sym:nextSibling"); + } + + /* Clean up any parameters which haven't yet got names, or whose + * names clash. */ + Hash *seen = NewHash(); + /* We need $this to refer to the current class, so can't allow it + * to be used as a parameter. */ + Setattr(seen, "this", seen); + /* We use $r to store the return value, so disallow that as a parameter + * name in case the user uses the "call-time pass-by-reference" feature + * (it's deprecated and off by default in PHP5, but we want to be + * maximally portable). Similarly we use $c for the classname or new + * stdClass object. + */ + Setattr(seen, "r", seen); + Setattr(seen, "c", seen); + + for (int argno = 0; argno < max_num_of_arguments; ++argno) { + String *&pname = arg_names[argno]; + if (pname) { + Replaceall(pname, " ", "_"); + } else { + /* We get here if the SWIG .i file has "int foo(int);" */ + pname = NewStringEmpty(); + Printf(pname, "arg%d", argno + 1); + } + // Check if we've already used this parameter name. + while (Getattr(seen, pname)) { + // Append "_" to clashing names until they stop clashing... + Printf(pname, "_"); + } + Setattr(seen, Char(pname), seen); + + if (arg_values[argno] && Cmp(arg_values[argno], "?") == 0) { + handle_as_overload = true; + } + } + Delete(seen); + seen = NULL; + + String *invoke = NewStringEmpty(); + String *prepare = NewStringEmpty(); + String *args = NewStringEmpty(); + + if (!handle_as_overload && !(really_overloaded && max_num_of_arguments > min_num_of_arguments)) { + Printf(invoke, "%s(", iname); + if (wrapperType == memberfn) { + Printf(invoke, "$this->%s", SWIG_PTR); + } + for (int i = 0; i < max_num_of_arguments; ++i) { + if (i) + Printf(args, ","); + if (i || wrapperType == memberfn) + Printf(invoke, ","); + String *value = arg_values[i]; + if (value) { + const char *v = Char(value); + if (v[0] == '"') { + /* In a PHP double quoted string, $ needs to be escaped as \$. */ + Replaceall(value, "$", "\\$"); + } + Printf(args, "$%s=%s", arg_names[i], value); + } else { + Printf(args, "$%s", arg_names[i]); + } + Printf(invoke, "$%s", arg_names[i]); + } + Printf(invoke, ")"); + } else { + int i; + for (i = 0; i < min_num_of_arguments; ++i) { + if (i) + Printf(args, ","); + Printf(args, "$%s", arg_names[i]); + } + String *invoke_args = NewStringEmpty(); + if (wrapperType == memberfn) { + Printf(invoke_args, "$this->%s", SWIG_PTR); + if (min_num_of_arguments > 0) + Printf(invoke_args, ","); + } + Printf(invoke_args, "%s", args); + bool had_a_case = false; + int last_handled_i = i - 1; + for (; i < max_num_of_arguments; ++i) { + if (i) + Printf(args, ","); + const char *value = Char(arg_values[i]); + // FIXME: (really_overloaded && handle_as_overload) is perhaps a + // little conservative, but it doesn't hit any cases that it + // shouldn't for Xapian at least (and we need it to handle + // "Enquire::get_mset()" correctly). + bool non_php_default = ((really_overloaded && handle_as_overload) || + !value || strcmp(value, "?") == 0); + if (non_php_default) + value = "null"; + Printf(args, "$%s=%s", arg_names[i], value); + if (non_php_default) { + if (!had_a_case) { + Printf(prepare, "\t\tswitch (func_num_args()) {\n"); + had_a_case = true; + } + Printf(prepare, "\t\t"); + while (last_handled_i < i) { + Printf(prepare, "case %d: ", ++last_handled_i); + } + if (non_void_return) { + if ((!directorsEnabled() || !Swig_directorclass(n)) && !newobject) { + Append(prepare, "$r="); + } else { + Printf(prepare, "$this->%s=", SWIG_PTR); + } + } + if (!directorsEnabled() || !Swig_directorclass(n) || !newobject) { + Printf(prepare, "%s(%s); break;\n", iname, invoke_args); + } else if (!i) { + Printf(prepare, "%s($_this%s); break;\n", iname, invoke_args); + } else { + Printf(prepare, "%s($_this, %s); break;\n", iname, invoke_args); + } + } + if (i || wrapperType == memberfn) + Printf(invoke_args, ","); + Printf(invoke_args, "$%s", arg_names[i]); + } + Printf(prepare, "\t\t"); + if (had_a_case) + Printf(prepare, "default: "); + if (non_void_return) { + if ((!directorsEnabled() || !Swig_directorclass(n)) && !newobject) { + Append(prepare, "$r="); + } else { + Printf(prepare, "$this->%s=", SWIG_PTR); + } + } + + if (!directorsEnabled() || !Swig_directorclass(n) || !newobject) { + Printf(prepare, "%s(%s);\n", iname, invoke_args); + } else { + Printf(prepare, "%s($_this, %s);\n", iname, invoke_args); + } + if (had_a_case) + Printf(prepare, "\t\t}\n"); + Delete(invoke_args); + Printf(invoke, "$r"); + } + + Printf(output, "\n"); + // If it's a member function or a class constructor... + if (wrapperType == memberfn || (constructor && current_class)) { + String *acc = NewString(Getattr(n, "access")); + // If a base has the same method with public access, then PHP + // requires to have it here as public as well + Node *bases = Getattr(Swig_methodclass(n), "bases"); + if (bases && Strcmp(acc, "public") != 0) { + String *warnmsg = 0; + int haspublicbase = 0; + Iterator i = First(bases); + while (i.item) { + Node *j = firstChild(i.item); + while (j) { + String *jname = Getattr(j, "name"); + if (!jname || Strcmp(jname, Getattr(n, "name")) != 0) { + j = nextSibling(j); + continue; + } + if (Strcmp(nodeType(j), "cdecl") == 0) { + if (!Getattr(j, "access") || checkAttribute(j, "access", "public")) { + haspublicbase = 1; + } + } else if (Strcmp(nodeType(j), "using") == 0 && firstChild(j) && Strcmp(nodeType(firstChild(j)), "cdecl") == 0) { + if (!Getattr(firstChild(j), "access") || checkAttribute(firstChild(j), "access", "public")) { + haspublicbase = 1; + } + } + if (haspublicbase) { + warnmsg = NewStringf("Modifying the access of '%s::%s' to public, as the base '%s' has it as public as well.\n", Getattr(current_class, "classtype"), Getattr(n, "name"), Getattr(i.item, "classtype")); + break; + } + j = nextSibling(j); + } + i = Next(i); + if (haspublicbase) { + break; + } + } + if (Getattr(n, "access") && haspublicbase) { + Delete(acc); + acc = NewStringEmpty(); // implicitly public + Swig_warning(WARN_PHP_PUBLIC_BASE, input_file, line_number, Char(warnmsg)); + Delete(warnmsg); + } + } + + if (Cmp(acc, "public") == 0) { + // The default visibility for methods is public, so don't specify + // that explicitly to keep the wrapper size down. + Delete(acc); + acc = NewStringEmpty(); + } else if (Cmp(acc, "") != 0) { + Append(acc, " "); + } + + if (constructor) { + const char * arg0; + if (max_num_of_arguments > 0) { + arg0 = Char(arg_names[0]); + } else { + arg0 = "res"; + Delete(args); + args = NewString("$res=null"); + } + String *mangled_type = SwigType_manglestr(Getattr(n, "type")); + Printf(output, "\t%sfunction %s(%s) {\n", acc, methodname, args); + Printf(output, "\t\tif (is_resource($%s) && get_resource_type($%s) === '%s') {\n", arg0, arg0, mangled_type); + Printf(output, "\t\t\t$this->%s=$%s;\n", SWIG_PTR, arg0); + Printf(output, "\t\t\treturn;\n"); + Printf(output, "\t\t}\n"); + } else { + Printf(output, "\t%sfunction %s(%s) {\n", acc, methodname, args); + } + Delete(acc); + } else if (wrapperType == staticmembervar) { + // We're called twice for a writable static member variable - first + // with "foo_set" and then with "foo_get" - so generate half the + // wrapper function each time. + // + // For a const static member, we only get called once. + static bool started = false; + if (!started) { + Printf(output, "\tstatic function %s() {\n", methodname); + if (max_num_of_arguments) { + // Setter. + Printf(output, "\t\tif (func_num_args()) {\n"); + Printf(output, "\t\t\t%s(func_get_arg(0));\n", iname); + Printf(output, "\t\t\treturn;\n"); + Printf(output, "\t\t}\n"); + started = true; + goto done; + } + } + started = false; + } else { + Printf(output, "\tstatic function %s(%s) {\n", methodname, args); + } + + if (!newobject) + Printf(output, "%s", prepare); + if (constructor) { + if (!directorsEnabled() || !Swig_directorclass(n)) { + if (!Len(prepare)) { + if (strcmp(methodname, "__construct") == 0) { + Printf(output, "\t\t$this->%s=%s;\n", SWIG_PTR, invoke); + } else { + String *classname = Swig_class_name(current_class); + Printf(output, "\t\treturn new %s%s(%s);\n", prefix, classname, invoke); + } + } + } else { + Node *parent = Swig_methodclass(n); + String *classname = Swig_class_name(parent); + Printf(output, "\t\tif (get_class($this) === '%s%s') {\n", prefix, classname); + Printf(output, "\t\t\t$_this = null;\n"); + Printf(output, "\t\t} else {\n"); + Printf(output, "\t\t\t$_this = $this;\n"); + Printf(output, "\t\t}\n"); + if (!Len(prepare)) { + if (num_arguments > 1) { + Printf(output, "\t\t$this->%s=%s($_this, %s);\n", SWIG_PTR, iname, args); + } else { + Printf(output, "\t\t$this->%s=%s($_this);\n", SWIG_PTR, iname); + } + } + } + Printf(output, "%s", prepare); + } else if (!non_void_return && !hasargout) { + if (Cmp(invoke, "$r") != 0) + Printf(output, "\t\t%s;\n", invoke); + } else if (is_class(d)) { + if (Cmp(invoke, "$r") != 0) + Printf(output, "\t\t$r=%s;\n", invoke); + if (Len(ret_types) == 1) { + /* If d is abstract we can't create a new wrapper type d. */ + Node *d_class = classLookup(d); + int is_abstract = 0; + if (Getattr(d_class, "abstracts")) { + is_abstract = 1; + } + if (newobject || !is_abstract) { + Printf(output, "\t\tif (is_resource($r)) {\n"); + if (Getattr(classLookup(Getattr(n, "type")), "module")) { + /* + * _p_Foo -> Foo, _p_ns__Bar -> Bar + * TODO: do this in a more elegant way + */ + if (Len(prefix) == 0) { + Printf(output, "\t\t\t$c=substr(get_resource_type($r), (strpos(get_resource_type($r), '__') ? strpos(get_resource_type($r), '__') + 2 : 3));\n"); + } else { + Printf(output, "\t\t\t$c='%s'.substr(get_resource_type($r), (strpos(get_resource_type($r), '__') ? strpos(get_resource_type($r), '__') + 2 : 3));\n", prefix); + } + Printf(output, "\t\t\tif (class_exists($c)) return new $c($r);\n"); + Printf(output, "\t\t\treturn new %s%s($r);\n", prefix, Getattr(classLookup(d), "sym:name")); + } else { + Printf(output, "\t\t\t$c = new stdClass();\n"); + Printf(output, "\t\t\t$c->" SWIG_PTR " = $r;\n"); + Printf(output, "\t\t\treturn $c;\n"); + } + Printf(output, "\t\t}\n\t\treturn $r;\n"); + } else { + Printf(output, "\t\t$this->%s = $r;\n", SWIG_PTR); + Printf(output, "\t\treturn $this;\n"); + } + } else { + Printf(output, "\t\tif (!is_resource($r)) return $r;\n"); + String *wrapobj = NULL; + String *common = NULL; + Iterator i = First(ret_types); + while (i.item) { + SwigType *ret_type = i.item; + i = Next(i); + String *mangled = NewString("_p"); + Printf(mangled, "%s", SwigType_manglestr(ret_type)); + Node *class_node = Getattr(zend_types, mangled); + if (!class_node) { + /* This is needed when we're returning a pointer to a type + * rather than returning the type by value or reference. */ + Delete(mangled); + mangled = NewString(SwigType_manglestr(ret_type)); + class_node = Getattr(zend_types, mangled); + if (!class_node) { + // Return type isn't an object, so will be handled by the + // !is_resource() check before the switch. + continue; + } + } + const char *classname = GetChar(class_node, "sym:name"); + if (!classname) + classname = GetChar(class_node, "name"); + String * action = NewStringEmpty(); + if (classname) + Printf(action, "return new %s%s($r);\n", prefix, classname); + else + Printf(action, "return $r;\n"); + if (!wrapobj) { + wrapobj = NewString("\t\tswitch (get_resource_type($r)) {\n"); + common = action; + } else { + if (common && Cmp(common, action) != 0) { + Delete(common); + common = NULL; + } + } + Printf(wrapobj, "\t\t"); + if (i.item) { + Printf(wrapobj, "case '%s': ", mangled); + } else { + Printf(wrapobj, "default: "); + } + Printv(wrapobj, action, NIL); + if (action != common) Delete(action); + Delete(mangled); + } + Printf(wrapobj, "\t\t}\n"); + if (common) { + // All cases have the same action, so eliminate the switch + // wrapper. + Printf(output, "\t\t%s", common); + Delete(common); + } else { + Printv(output, wrapobj, NIL); + } + Delete(wrapobj); + } + } else { + if (non_void_return) { + Printf(output, "\t\treturn %s;\n", invoke); + } else if (Cmp(invoke, "$r") != 0) { + Printf(output, "\t\t%s;\n", invoke); + } + } + Printf(output, "\t}\n"); + +done: + Delete(prepare); + Delete(invoke); + free(arg_values); + + Delete(args); + args = NULL; + + for (int i = 0; i < max_num_of_arguments; ++i) { + Delete(arg_names[i]); + } + free(arg_names); + arg_names = NULL; + } + + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * globalvariableHandler() + * ------------------------------------------------------------ */ + + virtual int globalvariableHandler(Node *n) { + char *name = GetChar(n, "name"); + char *iname = GetChar(n, "sym:name"); + SwigType *t = Getattr(n, "type"); + String *tm; + + /* First do the wrappers such as name_set(), name_get() + * as provided by the baseclass's implementation of variableWrapper + */ + if (Language::globalvariableHandler(n) == SWIG_NOWRAP) { + return SWIG_NOWRAP; + } + + if (!addSymbol(iname, n)) + return SWIG_ERROR; + + /* First link C variables to PHP */ + + tm = Swig_typemap_lookup("varinit", n, name, 0); + if (tm) { + Replaceall(tm, "$target", name); + Printf(s_vinit, "%s\n", tm); + } else { + Swig_error(input_file, line_number, "Unable to link with type %s\n", SwigType_str(t, 0)); + } + + /* Now generate PHP -> C sync blocks */ + /* + tm = Swig_typemap_lookup("varin", n, name, 0); + if(tm) { + Replaceall(tm, "$symname", iname); + Printf(f_c->code, "%s\n", tm); + } else { + Swig_error(input_file, line_number, "Unable to link with type %s\n", SwigType_str(t, 0)); + } + */ + /* Now generate C -> PHP sync blocks */ + /* + if(!GetFlag(n,"feature:immutable")) { + + tm = Swig_typemap_lookup("varout", n, name, 0); + if(tm) { + Replaceall(tm, "$symname", iname); + Printf(f_php->code, "%s\n", tm); + } else { + Swig_error(input_file, line_number, "Unable to link with type %s\n", SwigType_str(t, 0)); + } + } + */ + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * constantWrapper() + * ------------------------------------------------------------ */ + + virtual int constantWrapper(Node *n) { + String *name = GetChar(n, "name"); + String *iname = GetChar(n, "sym:name"); + SwigType *type = Getattr(n, "type"); + String *rawval = Getattr(n, "rawval"); + String *value = rawval ? rawval : Getattr(n, "value"); + String *tm; + + if (!addSymbol(iname, n)) + return SWIG_ERROR; + + SwigType_remember(type); + + if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { + Replaceall(tm, "$source", value); + Replaceall(tm, "$target", name); + Replaceall(tm, "$value", value); + Printf(s_cinit, "%s\n", tm); + } + + if (shadow) { + String *enumvalue = GetChar(n, "enumvalue"); + String *set_to = iname; + + if (!enumvalue) { + enumvalue = GetChar(n, "enumvalueex"); + } + + if (enumvalue && *Char(enumvalue)) { + // Check for a simple constant expression which is valid in PHP. + // If we find one, initialise the const member with it; otherwise + // we initialise it using the C/C++ wrapped constant. + const char *p; + for (p = Char(enumvalue); *p; ++p) { + if (!isdigit((unsigned char)*p) && !strchr(" +-", *p)) { + // FIXME: enhance to handle ` + 1' which is what + // we get for enums that don't have an explicit value set. + break; + } + } + if (!*p) + set_to = enumvalue; + } + + if (wrapping_member_constant) { + if (!s_oowrappers) + s_oowrappers = NewStringEmpty(); + Printf(s_oowrappers, "\n\tconst %s = %s;\n", wrapping_member_constant, set_to); + } else { + if (!s_fakeoowrappers) + s_fakeoowrappers = NewStringEmpty(); + Printf(s_fakeoowrappers, "\n\tconst %s = %s;\n", iname, set_to); + } + } + + return SWIG_OK; + } + + /* + * PHP5::pragma() + * + * Pragma directive. + * + * %pragma(php) code="String" # Includes a string in the .php file + * %pragma(php) include="file.php" # Includes a file in the .php file + */ + + virtual int pragmaDirective(Node *n) { + if (!ImportMode) { + String *lang = Getattr(n, "lang"); + String *type = Getattr(n, "name"); + String *value = Getattr(n, "value"); + + if (Strcmp(lang, "php") == 0 || Strcmp(lang, "php4") == 0) { + if (Strcmp(type, "code") == 0) { + if (value) { + Printf(pragma_code, "%s\n", value); + } + } else if (Strcmp(type, "include") == 0) { + if (value) { + Printf(pragma_incl, "include '%s';\n", value); + } + } else if (Strcmp(type, "phpinfo") == 0) { + if (value) { + Printf(pragma_phpinfo, "%s\n", value); + } + } else { + Swig_warning(WARN_PHP_UNKNOWN_PRAGMA, input_file, line_number, "Unrecognized pragma <%s>.\n", type); + } + } + } + return Language::pragmaDirective(n); + } + + /* ------------------------------------------------------------ + * classDeclaration() + * ------------------------------------------------------------ */ + + virtual int classDeclaration(Node *n) { + if (!Getattr(n, "feature:onlychildren")) { + String *symname = Getattr(n, "sym:name"); + Setattr(n, "php:proxy", symname); + } + + return Language::classDeclaration(n); + } + + /* ------------------------------------------------------------ + * classHandler() + * ------------------------------------------------------------ */ + + virtual int classHandler(Node *n) { + constructors = 0; + current_class = n; + + if (shadow) { + char *rename = GetChar(n, "sym:name"); + + if (!addSymbol(rename, n)) + return SWIG_ERROR; + shadow_classname = NewString(rename); + + shadow_get_vars = NewHash(); + shadow_set_vars = NewHash(); + + /* Deal with inheritance */ + List *baselist = Getattr(n, "bases"); + if (baselist) { + Iterator base = First(baselist); + while (base.item && GetFlag(base.item, "feature:ignore")) { + base = Next(base); + } + base = Next(base); + if (base.item) { + /* Warn about multiple inheritance for additional base class(es) */ + while (base.item) { + if (GetFlag(base.item, "feature:ignore")) { + base = Next(base); + continue; + } + String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); + String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); + Swig_warning(WARN_PHP_MULTIPLE_INHERITANCE, input_file, line_number, + "Warning for %s, base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, baseclassname); + base = Next(base); + } + } + } + } + + classnode = n; + Language::classHandler(n); + classnode = 0; + + if (shadow) { + List *baselist = Getattr(n, "bases"); + Iterator ki, base; + + if (baselist) { + base = First(baselist); + while (base.item && GetFlag(base.item, "feature:ignore")) { + base = Next(base); + } + } else { + base.item = NULL; + } + + if (Getattr(n, "abstracts") && !GetFlag(n, "feature:notabstract")) { + Printf(s_phpclasses, "abstract "); + } + + Printf(s_phpclasses, "class %s%s ", prefix, shadow_classname); + String *baseclass = NULL; + if (base.item && Getattr(base.item, "module")) { + baseclass = Getattr(base.item, "sym:name"); + if (!baseclass) + baseclass = Getattr(base.item, "name"); + Printf(s_phpclasses, "extends %s%s ", prefix, baseclass); + } else if (GetFlag(n, "feature:exceptionclass")) { + Append(s_phpclasses, "extends Exception "); + } + { + Node *node = NewHash(); + Setattr(node, "type", Getattr(n, "name")); + Setfile(node, Getfile(n)); + Setline(node, Getline(n)); + String * interfaces = Swig_typemap_lookup("phpinterfaces", node, "", 0); + if (interfaces) { + Printf(s_phpclasses, "implements %s ", interfaces); + } + Delete(node); + } + Printf(s_phpclasses, "{\n\tpublic $%s=null;\n", SWIG_PTR); + if (!baseclass) { + // Only store this in the base class (NB !baseclass means we *are* + // a base class...) + Printf(s_phpclasses, "\tprotected $%s=array();\n", SWIG_DATA); + } + + // Write property SET handlers + ki = First(shadow_set_vars); + if (ki.key) { + // This class has setters. + Printf(s_phpclasses, "\n\tfunction __set($var,$value) {\n"); + // FIXME: tune this threshold... + if (Len(shadow_set_vars) <= 2) { + // Not many setters, so avoid call_user_func. + for (; ki.key; ki = Next(ki)) { + DOH *key = ki.key; + String *iname = ki.item; + Printf(s_phpclasses, "\t\tif ($var === '%s') return %s($this->%s,$value);\n", key, iname, SWIG_PTR); + } + } else { + Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_set';\n", shadow_classname); + Printf(s_phpclasses, "\t\tif (function_exists($func)) return call_user_func($func,$this->%s,$value);\n", SWIG_PTR); + } + Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_alter_newobject($this->%s,$value);\n", module, SWIG_PTR); + if (baseclass) { + Printf(s_phpclasses, "\t\t%s%s::__set($var,$value);\n", prefix, baseclass); + } else { + Printf(s_phpclasses, "\t\t$this->%s[$var] = $value;\n", SWIG_DATA); + } + Printf(s_phpclasses, "\t}\n"); + } else { + Printf(s_phpclasses, "\n\tfunction __set($var,$value) {\n"); + Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_alter_newobject($this->%s,$value);\n", module, SWIG_PTR); + if (baseclass) { + Printf(s_phpclasses, "\t\t%s%s::__set($var,$value);\n", prefix, baseclass); + } else { + Printf(s_phpclasses, "\t\t$this->%s[$var] = $value;\n", SWIG_DATA); + } + Printf(s_phpclasses, "\t}\n"); + } + + // Write property GET handlers + ki = First(shadow_get_vars); + if (ki.key) { + // This class has getters. + Printf(s_phpclasses, "\n\tfunction __get($var) {\n"); + int non_class_getters = 0; + for (; ki.key; ki = Next(ki)) { + DOH *key = ki.key; + SwigType *d = ki.item; + if (!is_class(d)) { + ++non_class_getters; + continue; + } + Printv(s_phpclasses, "\t\tif ($var === '", key, "') return new ", prefix, Getattr(classLookup(d), "sym:name"), "(", shadow_classname, "_", key, "_get($this->", SWIG_PTR, "));\n", NIL); + } + // FIXME: tune this threshold... + if (non_class_getters <= 2) { + // Not many non-class getters, so avoid call_user_func. + for (ki = First(shadow_get_vars); non_class_getters && ki.key; ki = Next(ki)) { + DOH *key = ki.key; + SwigType *d = ki.item; + if (is_class(d)) continue; + Printv(s_phpclasses, "\t\tif ($var === '", key, "') return ", shadow_classname, "_", key, "_get($this->", SWIG_PTR, ");\n", NIL); + --non_class_getters; + } + } else { + Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_get';\n", shadow_classname); + Printf(s_phpclasses, "\t\tif (function_exists($func)) return call_user_func($func,$this->%s);\n", SWIG_PTR); + } + Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_get_newobject($this->%s);\n", module, SWIG_PTR); + if (baseclass) { + Printf(s_phpclasses, "\t\treturn %s%s::__get($var);\n", prefix, baseclass); + } else { + // Reading an unknown property name gives null in PHP. + Printf(s_phpclasses, "\t\treturn $this->%s[$var];\n", SWIG_DATA); + } + Printf(s_phpclasses, "\t}\n"); + + /* Create __isset for PHP 5.1 and later; PHP 5.0 will just ignore it. */ + /* __isset() should return true for read-only properties, so check for + * *_get() not *_set(). */ + Printf(s_phpclasses, "\n\tfunction __isset($var) {\n"); + Printf(s_phpclasses, "\t\tif (function_exists('%s_'.$var.'_get')) return true;\n", shadow_classname); + Printf(s_phpclasses, "\t\tif ($var === 'thisown') return true;\n"); + if (baseclass) { + Printf(s_phpclasses, "\t\treturn %s%s::__isset($var);\n", prefix, baseclass); + } else { + Printf(s_phpclasses, "\t\treturn array_key_exists($var, $this->%s);\n", SWIG_DATA); + } + Printf(s_phpclasses, "\t}\n"); + } else { + Printf(s_phpclasses, "\n\tfunction __get($var) {\n"); + Printf(s_phpclasses, "\t\tif ($var === 'thisown') return swig_%s_get_newobject($this->%s);\n", module, SWIG_PTR); + if (baseclass) { + Printf(s_phpclasses, "\t\treturn %s%s::__get($var);\n", prefix, baseclass); + } else { + Printf(s_phpclasses, "\t\treturn $this->%s[$var];\n", SWIG_DATA); + } + Printf(s_phpclasses, "\t}\n"); + Printf(s_phpclasses, "\n\tfunction __isset($var) {\n"); + Printf(s_phpclasses, "\t\tif ($var === 'thisown') return true;\n"); + if (baseclass) { + Printf(s_phpclasses, "\t\treturn %s%s::__isset($var);\n", prefix, baseclass); + } else { + Printf(s_phpclasses, "\t\treturn array_key_exists($var, $this->%s);\n", SWIG_DATA); + } + Printf(s_phpclasses, "\t}\n"); + } + + if (!class_has_ctor) { + Printf(s_phpclasses, "\tfunction __construct($h) {\n"); + Printf(s_phpclasses, "\t\t$this->%s=$h;\n", SWIG_PTR); + Printf(s_phpclasses, "\t}\n"); + } + + if (s_oowrappers) { + Printf(s_phpclasses, "%s", s_oowrappers); + Delete(s_oowrappers); + s_oowrappers = NULL; + } + class_has_ctor = false; + + Printf(s_phpclasses, "}\n\n"); + + Delete(shadow_classname); + shadow_classname = NULL; + + Delete(shadow_set_vars); + shadow_set_vars = NULL; + Delete(shadow_get_vars); + shadow_get_vars = NULL; + } + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * memberfunctionHandler() + * ------------------------------------------------------------ */ + + virtual int memberfunctionHandler(Node *n) { + wrapperType = memberfn; + Language::memberfunctionHandler(n); + wrapperType = standard; + + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * membervariableHandler() + * ------------------------------------------------------------ */ + + virtual int membervariableHandler(Node *n) { + wrapperType = membervar; + Language::membervariableHandler(n); + wrapperType = standard; + + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * staticmembervariableHandler() + * ------------------------------------------------------------ */ + + virtual int staticmembervariableHandler(Node *n) { + wrapperType = staticmembervar; + Language::staticmembervariableHandler(n); + wrapperType = standard; + + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * staticmemberfunctionHandler() + * ------------------------------------------------------------ */ + + virtual int staticmemberfunctionHandler(Node *n) { + wrapperType = staticmemberfn; + Language::staticmemberfunctionHandler(n); + wrapperType = standard; + + return SWIG_OK; + } + + int abstractConstructorHandler(Node *) { + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * constructorHandler() + * ------------------------------------------------------------ */ + + virtual int constructorHandler(Node *n) { + constructors++; + if (Swig_directorclass(n)) { + String *name = GetChar(Swig_methodclass(n), "name"); + String *ctype = GetChar(Swig_methodclass(n), "classtype"); + String *sname = GetChar(Swig_methodclass(n), "sym:name"); + String *args = NewStringEmpty(); + ParmList *p = Getattr(n, "parms"); + int i; + + for (i = 0; p; p = nextSibling(p), i++) { + if (i) { + Printf(args, ", "); + } + if (Strcmp(GetChar(p, "type"), SwigType_str(GetChar(p, "type"), 0))) { + SwigType *t = Getattr(p, "type"); + Printf(args, "%s", SwigType_rcaststr(t, 0)); + if (SwigType_isreference(t)) { + Append(args, "*"); + } + } + Printf(args, "arg%d", i+1); + } + + /* director ctor code is specific for each class */ + Delete(director_ctor_code); + director_ctor_code = NewStringEmpty(); + director_prot_ctor_code = NewStringEmpty(); + Printf(director_ctor_code, "if ( arg0->type == IS_NULL ) { /* not subclassed */\n"); + Printf(director_prot_ctor_code, "if ( arg0->type == IS_NULL ) { /* not subclassed */\n"); + Printf(director_ctor_code, " %s = (%s *)new %s(%s);\n", Swig_cresult_name(), ctype, ctype, args); + Printf(director_prot_ctor_code, " SWIG_PHP_Error(E_ERROR, \"accessing abstract class or protected constructor\");\n", name, name, args); + if (i) { + Insert(args, 0, ", "); + } + Printf(director_ctor_code, "} else {\n %s = (%s *)new SwigDirector_%s(arg0 TSRMLS_CC%s);\n}\n", Swig_cresult_name(), ctype, sname, args); + Printf(director_prot_ctor_code, "} else {\n %s = (%s *)new SwigDirector_%s(arg0 TSRMLS_CC%s);\n}\n", Swig_cresult_name(), ctype, sname, args); + Delete(args); + + wrapperType = directorconstructor; + } else { + wrapperType = constructor; + } + Language::constructorHandler(n); + wrapperType = standard; + + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * CreateZendListDestructor() + * ------------------------------------------------------------ */ + //virtual int destructorHandler(Node *n) { + //} + int CreateZendListDestructor(Node *n) { + String *name = GetChar(Swig_methodclass(n), "name"); + String *iname = GetChar(n, "sym:name"); + ParmList *l = Getattr(n, "parms"); + + String *destructorname = NewStringEmpty(); + Printf(destructorname, "_%s", Swig_name_wrapper(iname)); + Setattr(classnode, "destructor", destructorname); + + Wrapper *f = NewWrapper(); + Printf(f->def, "/* This function is designed to be called by the zend list destructors */\n"); + Printf(f->def, "/* to typecast and do the actual destruction */\n"); + Printf(f->def, "static void %s(zend_rsrc_list_entry *rsrc, const char *type_name TSRMLS_DC) {\n", destructorname); + + Wrapper_add_localv(f, "value", "swig_object_wrapper *value=(swig_object_wrapper *) rsrc->ptr", NIL); + Wrapper_add_localv(f, "ptr", "void *ptr=value->ptr", NIL); + Wrapper_add_localv(f, "newobject", "int newobject=value->newobject", NIL); + + emit_parameter_variables(l, f); + emit_attach_parmmaps(l, f); + + // Get type of first arg, thing to be destructed + // Skip ignored arguments + Parm *p = l; + //while (Getattr(p,"tmap:ignore")) {p = Getattr(p,"tmap:ignore:next");} + while (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + } + SwigType *pt = Getattr(p, "type"); + + Printf(f->code, " efree(value);\n"); + Printf(f->code, " if (! newobject) return; /* can't delete it! */\n"); + Printf(f->code, " arg1 = (%s)SWIG_ZTS_ConvertResourceData(ptr,type_name,SWIGTYPE%s TSRMLS_CC);\n", SwigType_lstr(pt, 0), SwigType_manglestr(pt)); + Printf(f->code, " if (! arg1) zend_error(E_ERROR, \"%s resource already free'd\");\n", Char(name)); + + Setattr(n, "wrap:name", destructorname); + + String *actioncode = emit_action(n); + Append(f->code, actioncode); + Delete(actioncode); + + Printf(f->code, "thrown:\n"); + Append(f->code, "return;\n"); + Append(f->code, "fail:\n"); + Append(f->code, "SWIG_FAIL(TSRMLS_C);\n"); + Printf(f->code, "}\n"); + + Wrapper_print(f, s_wrappers); + DelWrapper(f); + + return SWIG_OK; + } + + /* ------------------------------------------------------------ + * memberconstantHandler() + * ------------------------------------------------------------ */ + + virtual int memberconstantHandler(Node *n) { + wrapping_member_constant = Getattr(n, "sym:name"); + Language::memberconstantHandler(n); + wrapping_member_constant = NULL; + return SWIG_OK; + } + + int classDirectorInit(Node *n) { + String *declaration = Swig_director_declaration(n); + Printf(f_directors_h, "%s\n", declaration); + Printf(f_directors_h, "public:\n"); + Delete(declaration); + return Language::classDirectorInit(n); + } + + int classDirectorEnd(Node *n) { + Printf(f_directors_h, "};\n"); + return Language::classDirectorEnd(n); + } + + int classDirectorConstructor(Node *n) { + Node *parent = Getattr(n, "parentNode"); + String *decl = Getattr(n, "decl"); + String *supername = Swig_class_name(parent); + String *classname = NewStringEmpty(); + Printf(classname, "SwigDirector_%s", supername); + + /* insert self parameter */ + Parm *p; + ParmList *superparms = Getattr(n, "parms"); + ParmList *parms = CopyParmList(superparms); + String *type = NewString("zval"); + SwigType_add_pointer(type); + p = NewParm(type, NewString("self"), n); + set_nextSibling(p, parms); + parms = p; + + if (!Getattr(n, "defaultargs")) { + // There should always be a "self" parameter first. + assert(ParmList_len(parms) > 0); + + /* constructor */ + { + Wrapper *w = NewWrapper(); + String *call; + String *basetype = Getattr(parent, "classtype"); + + // We put TSRMLS_DC after the self parameter in order to cope with + // any default parameters. + String *target = Swig_method_decl(0, decl, classname, parms, 0, 0); + const char * p = Char(target); + const char * comma = strchr(p, ','); + int ins = comma ? (int)(comma - p) : Len(target) - 1; + Insert(target, ins, " TSRMLS_DC"); + + call = Swig_csuperclass_call(0, basetype, superparms); + Printf(w->def, "%s::%s: %s, Swig::Director(self TSRMLS_CC) {", classname, target, call); + Append(w->def, "}"); + Delete(target); + Wrapper_print(w, f_directors); + Delete(call); + DelWrapper(w); + } + + /* constructor header */ + { + // We put TSRMLS_DC after the self parameter in order to cope with + // any default parameters. + String *target = Swig_method_decl(0, decl, classname, parms, 0, 1); + const char * p = Char(target); + const char * comma = strchr(p, ','); + int ins = comma ? (int)(comma - p) : Len(target) - 1; + Insert(target, ins, " TSRMLS_DC"); + + Printf(f_directors_h, " %s;\n", target); + Delete(target); + } + } + return Language::classDirectorConstructor(n); + } + + int classDirectorMethod(Node *n, Node *parent, String *super) { + int is_void = 0; + int is_pointer = 0; + String *decl = Getattr(n, "decl"); + String *returntype = Getattr(n, "type"); + String *name = Getattr(n, "name"); + String *classname = Getattr(parent, "sym:name"); + String *c_classname = Getattr(parent, "name"); + String *symname = Getattr(n, "sym:name"); + String *declaration = NewStringEmpty(); + ParmList *l = Getattr(n, "parms"); + Wrapper *w = NewWrapper(); + String *tm; + String *wrap_args = NewStringEmpty(); + String *value = Getattr(n, "value"); + String *storage = Getattr(n, "storage"); + bool pure_virtual = false; + int status = SWIG_OK; + int idx; + bool ignored_method = GetFlag(n, "feature:ignore") ? true : false; + + if (Cmp(storage, "virtual") == 0) { + if (Cmp(value, "0") == 0) { + pure_virtual = true; + } + } + + /* determine if the method returns a pointer */ + is_pointer = SwigType_ispointer_return(decl); + is_void = (Cmp(returntype, "void") == 0 && !is_pointer); + + /* virtual method definition */ + String *target; + String *pclassname = NewStringf("SwigDirector_%s", classname); + String *qualified_name = NewStringf("%s::%s", pclassname, name); + SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : Getattr(n, "classDirectorMethods:type"); + target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0); + Printf(w->def, "%s", target); + Delete(qualified_name); + Delete(target); + /* header declaration */ + target = Swig_method_decl(rtype, decl, name, l, 0, 1); + Printf(declaration, " virtual %s", target); + Delete(target); + + // Get any exception classes in the throws typemap + ParmList *throw_parm_list = 0; + + if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) { + Parm *p; + int gencomma = 0; + + Append(w->def, " throw("); + Append(declaration, " throw("); + + if (throw_parm_list) + Swig_typemap_attach_parms("throws", throw_parm_list, 0); + for (p = throw_parm_list; p; p = nextSibling(p)) { + if (Getattr(p, "tmap:throws")) { + if (gencomma++) { + Append(w->def, ", "); + Append(declaration, ", "); + } + String *str = SwigType_str(Getattr(p, "type"), 0); + Append(w->def, str); + Append(declaration, str); + Delete(str); + } + } + + Append(w->def, ")"); + Append(declaration, ")"); + } + + Append(w->def, " {"); + Append(declaration, ";\n"); + + Printf(w->code, "TSRMLS_FETCH_FROM_CTX(swig_zts_ctx);\n"); + + /* declare method return value + * if the return value is a reference or const reference, a specialized typemap must + * handle it, including declaration of c_result ($result). + */ + if (!is_void) { + if (!(ignored_method && !pure_virtual)) { + String *cres = SwigType_lstr(returntype, "c_result"); + Printf(w->code, "%s;\n", cres); + Delete(cres); + } + } + + if (ignored_method) { + if (!pure_virtual) { + if (!is_void) + Printf(w->code, "return "); + String *super_call = Swig_method_call(super, l); + Printf(w->code, "%s;\n", super_call); + Delete(super_call); + } else { + Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\" TSRMLS_CC);\n", SwigType_namestr(c_classname), + SwigType_namestr(name)); + } + } else { + /* attach typemaps to arguments (C/C++ -> PHP) */ + String *parse_args = NewStringEmpty(); + + Swig_director_parms_fixup(l); + + /* remove the wrapper 'w' since it was producing spurious temps */ + Swig_typemap_attach_parms("in", l, 0); + Swig_typemap_attach_parms("directorin", l, 0); + Swig_typemap_attach_parms("directorargout", l, w); + + Parm *p; + char source[256]; + + int outputs = 0; + if (!is_void) + outputs++; + + /* build argument list and type conversion string */ + idx = 0; + p = l; + while (p) { + if (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + continue; + } + + if (Getattr(p, "tmap:directorargout") != 0) + outputs++; + + String *pname = Getattr(p, "name"); + String *ptype = Getattr(p, "type"); + + if ((tm = Getattr(p, "tmap:directorin")) != 0) { + String *parse = Getattr(p, "tmap:directorin:parse"); + if (!parse) { + sprintf(source, "obj%d", idx++); + String *input = NewStringf("&%s", source); + Setattr(p, "emit:directorinput", input); + Replaceall(tm, "$input", input); + Delete(input); + Replaceall(tm, "$owner", "0"); + Printv(wrap_args, "zval ", source, ";\n", NIL); + Printf(wrap_args, "args[%d] = &%s;\n", idx - 1, source); + Printv(wrap_args, "INIT_ZVAL(", source, ");\n", NIL); + + Printv(wrap_args, tm, "\n", NIL); + Putc('O', parse_args); + } else { + Append(parse_args, parse); + Setattr(p, "emit:directorinput", pname); + Replaceall(tm, "$input", pname); + Replaceall(tm, "$owner", "0"); + if (Len(tm) == 0) + Append(tm, pname); + } + p = Getattr(p, "tmap:directorin:next"); + continue; + } else if (Cmp(ptype, "void")) { + Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, + "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), + SwigType_namestr(c_classname), SwigType_namestr(name)); + status = SWIG_NOWRAP; + break; + } + p = nextSibling(p); + } + + /* exception handling */ + bool error_used_in_typemap = false; + tm = Swig_typemap_lookup("director:except", n, Swig_cresult_name(), 0); + if (!tm) { + tm = Getattr(n, "feature:director:except"); + if (tm) + tm = Copy(tm); + } + if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { + if (Replaceall(tm, "$error", "error")) { + /* Only declare error if it is used by the typemap. */ + error_used_in_typemap = true; + Append(w->code, "int error;\n"); + } + } else { + Delete(tm); + tm = NULL; + } + + if (!idx) { + Printf(w->code, "zval **args = NULL;\n"); + } else { + Printf(w->code, "zval *args[%d];\n", idx); + } + Printf(w->code, "zval *%s, funcname;\n", Swig_cresult_name()); + Append(w->code, "if (!swig_self) {\n"); + Append(w->code, " SWIG_PHP_Error(E_ERROR, \"this pointer is NULL\");"); + Append(w->code, "}\n\n"); + Printf(w->code, "MAKE_STD_ZVAL(%s);\n", Swig_cresult_name()); + const char * funcname = GetChar(n, "sym:name"); + Printf(w->code, "ZVAL_STRINGL(&funcname, (char *)\"%s\", %d, 0);\n", funcname, strlen(funcname)); + + /* wrap complex arguments to zvals */ + Printv(w->code, wrap_args, NIL); + + if (error_used_in_typemap) { + Append(w->code, "error = "); + } + Append(w->code, "call_user_function(EG(function_table), (zval**)&swig_self, &funcname,"); + Printf(w->code, " %s, %d, args TSRMLS_CC);\n", Swig_cresult_name(), idx); + + if (tm) { + Printv(w->code, Str(tm), "\n", NIL); + Delete(tm); + } + + /* marshal return value from PHP to C/C++ type */ + + String *cleanup = NewStringEmpty(); + String *outarg = NewStringEmpty(); + + idx = 0; + + /* marshal return value */ + if (!is_void) { + tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); + if (tm != 0) { + Replaceall(tm, "$input", Swig_cresult_name()); + char temp[24]; + sprintf(temp, "%d", idx); + Replaceall(tm, "$argnum", temp); + + /* TODO check this */ + if (Getattr(n, "wrap:disown")) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$result", "c_result"); + Printv(w->code, tm, "\n", NIL); + Delete(tm); + } else { + Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number, + "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(returntype, 0), SwigType_namestr(c_classname), + SwigType_namestr(name)); + status = SWIG_ERROR; + } + } + + /* marshal outputs */ + for (p = l; p;) { + if ((tm = Getattr(p, "tmap:directorargout")) != 0) { + Replaceall(tm, "$result", Swig_cresult_name()); + Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); + Printv(w->code, tm, "\n", NIL); + p = Getattr(p, "tmap:directorargout:next"); + } else { + p = nextSibling(p); + } + } + + Printf(w->code, "FREE_ZVAL(%s);\n", Swig_cresult_name()); + + Delete(parse_args); + Delete(cleanup); + Delete(outarg); + } + + Append(w->code, "thrown:\n"); + if (!is_void) { + if (!(ignored_method && !pure_virtual)) { + String *rettype = SwigType_str(returntype, 0); + if (!SwigType_isreference(returntype)) { + Printf(w->code, "return (%s) c_result;\n", rettype); + } else { + Printf(w->code, "return (%s) *c_result;\n", rettype); + } + Delete(rettype); + } + } else { + Append(w->code, "return;\n"); + } + + Append(w->code, "fail:\n"); + Append(w->code, "SWIG_FAIL(TSRMLS_C);\n"); + Append(w->code, "}\n"); + + // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method + String *inline_extra_method = NewStringEmpty(); + if (dirprot_mode() && !is_public(n) && !pure_virtual) { + Printv(inline_extra_method, declaration, NIL); + String *extra_method_name = NewStringf("%sSwigPublic", name); + Replaceall(inline_extra_method, name, extra_method_name); + Replaceall(inline_extra_method, ";\n", " {\n "); + if (!is_void) + Printf(inline_extra_method, "return "); + String *methodcall = Swig_method_call(super, l); + Printv(inline_extra_method, methodcall, ";\n }\n", NIL); + Delete(methodcall); + Delete(extra_method_name); + } + + /* emit the director method */ + if (status == SWIG_OK) { + if (!Getattr(n, "defaultargs")) { + Replaceall(w->code, "$symname", symname); + Wrapper_print(w, f_directors); + Printv(f_directors_h, declaration, NIL); + Printv(f_directors_h, inline_extra_method, NIL); + } + } + + /* clean up */ + Delete(wrap_args); + Delete(pclassname); + DelWrapper(w); + return status; + } + + int classDirectorDisown(Node *) { + return SWIG_OK; + } +}; /* class PHP */ + +static PHP5 *maininstance = 0; + +// We use this function to be able to write out zend_register_list_destructor_ex +// lines for most things in the type table +// NOTE: it's a function NOT A PHP5::METHOD +extern "C" { +static void typetrace(const SwigType *ty, String *mangled, String *clientdata) { + Node *class_node; + if (!zend_types) { + zend_types = NewHash(); + } + // we want to know if the type which reduced to this has a constructor + if ((class_node = maininstance->classLookup(ty))) { + if (!Getattr(zend_types, mangled)) { + // OK it may have been set before by a different SwigType but it would + // have had the same underlying class node I think + // - it is certainly required not to have different originating class + // nodes for the same SwigType + Setattr(zend_types, mangled, class_node); + } + } else { // a non-class pointer + Setattr(zend_types, mangled, NOTCLASS); + } + if (r_prevtracefunc) + (*r_prevtracefunc) (ty, mangled, (String *) clientdata); +} +} + +/* ----------------------------------------------------------------------------- + * new_swig_php5() - Instantiate module + * ----------------------------------------------------------------------------- */ + +static Language *new_swig_php5() { + maininstance = new PHP5; + if (!r_prevtracefunc) { + r_prevtracefunc = SwigType_remember_trace(typetrace); + } else { + Printf(stderr, "php Typetrace vector already saved!\n"); + assert(0); + } + return maininstance; +} + +extern "C" Language *swig_php4(void) { + Printf(stderr, "*** -php4 is no longer supported.\n" + "*** Either upgrade to PHP5 or use SWIG 1.3.36 or earlier.\n"); + SWIG_exit(EXIT_FAILURE); + return NULL; // To avoid compiler warnings. +} + +extern "C" Language *swig_php5(void) { + return new_swig_php5(); +} diff --git a/Source/Modules/pike.cxx b/Source/Modules/pike.cxx index 22c5a638b..6a74851c8 100644 --- a/Source/Modules/pike.cxx +++ b/Source/Modules/pike.cxx @@ -149,9 +149,7 @@ public: /* Standard stuff for the SWIG runtime section */ Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGPIKE\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGPIKE\n#define SWIGPIKE\n#endif\n\n"); Printf(f_header, "#define SWIG_init pike_module_init\n"); Printf(f_header, "#define SWIG_name \"%s\"\n\n", module); diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index 808d9a365..905f02213 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -12,6 +12,7 @@ * ----------------------------------------------------------------------------- */ #include "swigmod.h" +#include #include "cparse.h" #include #include @@ -44,14 +45,16 @@ static File *f_shadow_py = 0; static String *f_shadow = 0; static String *f_shadow_begin = 0; static Hash *f_shadow_imports = 0; -static String *f_shadow_builtin_imports = 0; +static String *f_shadow_after_begin = 0; static String *f_shadow_stubs = 0; static Hash *builtin_getset = 0; +static Hash *builtin_closures = 0; static Hash *class_members = 0; static File *f_builtins = 0; static String *builtin_tp_init = 0; static String *builtin_methods = 0; static String *builtin_default_unref = 0; +static String *builtin_closures_code = 0; static String *methods; static String *class_name; @@ -172,19 +175,19 @@ static const char *usage3 = "\ Function annotation \n\ \n"; -static String *getSlot(Node *n = NULL, const char *key = NULL) { - static String *slot_default = NewString("0"); - String *val = key && *key ? Getattr(n, key) : NULL; - return val ? val : slot_default; +static String *getSlot(Node *n = NULL, const char *key = NULL, String *default_slot = NULL) { + static String *zero = NewString("0"); + String *val = n && key && *key ? Getattr(n, key) : NULL; + return val ? val : default_slot ? default_slot : zero; } -static void printSlot(File *f, const String *slotval, const char *slotname, const char *functype = NULL) { - String *slotval_override = functype ? NewStringf("(%s) %s", functype, slotval) : 0; - if (slotval_override) - slotval = slotval_override; +static void printSlot(File *f, String *slotval, const char *slotname, const char *functype = NULL) { + String *slotval_override = 0; + if (functype) + slotval = slotval_override = NewStringf("(%s) %s", functype, slotval); int len = Len(slotval); - int fieldwidth = len > 40 ? 0 : 40 - len; - Printf(f, " %s, %*s/* %s */\n", slotval, fieldwidth, "", slotname); + int fieldwidth = len > 41 ? (len > 61 ? 0 : 61 - len) : 41 - len; + Printf(f, " %s,%*s/* %s */\n", slotval, fieldwidth, "", slotname); Delete(slotval_override); } @@ -193,7 +196,7 @@ static String *getClosure(String *functype, String *wrapper, int funpack = 0) { "unaryfunc", "SWIGPY_UNARYFUNC_CLOSURE", "destructor", "SWIGPY_DESTRUCTOR_CLOSURE", "inquiry", "SWIGPY_INQUIRY_CLOSURE", - "getiterfunc", "SWIGPY_UNARYFUNC_CLOSURE", + "getiterfunc", "SWIGPY_GETITERFUNC_CLOSURE", "binaryfunc", "SWIGPY_BINARYFUNC_CLOSURE", "ternaryfunc", "SWIGPY_TERNARYFUNC_CLOSURE", "ternarycallfunc", "SWIGPY_TERNARYCALLFUNC_CLOSURE", @@ -205,7 +208,7 @@ static String *getClosure(String *functype, String *wrapper, int funpack = 0) { "objobjargproc", "SWIGPY_OBJOBJARGPROC_CLOSURE", "reprfunc", "SWIGPY_REPRFUNC_CLOSURE", "hashfunc", "SWIGPY_HASHFUNC_CLOSURE", - "iternextfunc", "SWIGPY_ITERNEXT_CLOSURE", + "iternextfunc", "SWIGPY_ITERNEXTFUNC_CLOSURE", NULL }; @@ -213,7 +216,7 @@ static String *getClosure(String *functype, String *wrapper, int funpack = 0) { "unaryfunc", "SWIGPY_UNARYFUNC_CLOSURE", "destructor", "SWIGPY_DESTRUCTOR_CLOSURE", "inquiry", "SWIGPY_INQUIRY_CLOSURE", - "getiterfunc", "SWIGPY_UNARYFUNC_CLOSURE", + "getiterfunc", "SWIGPY_GETITERFUNC_CLOSURE", "ternaryfunc", "SWIGPY_TERNARYFUNC_CLOSURE", "ternarycallfunc", "SWIGPY_TERNARYCALLFUNC_CLOSURE", "lenfunc", "SWIGPY_LENFUNC_CLOSURE", @@ -224,7 +227,7 @@ static String *getClosure(String *functype, String *wrapper, int funpack = 0) { "objobjargproc", "SWIGPY_OBJOBJARGPROC_CLOSURE", "reprfunc", "SWIGPY_REPRFUNC_CLOSURE", "hashfunc", "SWIGPY_HASHFUNC_CLOSURE", - "iternextfunc", "SWIGPY_ITERNEXT_CLOSURE", + "iternextfunc", "SWIGPY_ITERNEXTFUNC_CLOSURE", NULL }; @@ -539,6 +542,7 @@ public: fputs(usage3, stdout); } else if (strcmp(argv[i], "-py3") == 0) { py3 = 1; + Preprocessor_define("SWIGPYTHON_PY3", 0); Swig_mark_arg(i); } else if (strcmp(argv[i], "-builtin") == 0) { builtin = 1; @@ -587,6 +591,7 @@ public: * interface file to enable director generation. */ String *mod_docstring = NULL; + String *moduleimport = NULL; { Node *mod = Getattr(n, "module"); if (mod) { @@ -627,6 +632,7 @@ public: } mod_docstring = Getattr(options, "docstring"); package = Getattr(options, "package"); + moduleimport = Getattr(options, "moduleimport"); } } } @@ -650,6 +656,8 @@ public: f_directors_h = NewString(""); f_directors = NewString(""); builtin_getset = NewHash(); + builtin_closures = NewHash(); + builtin_closures_code = NewString(""); class_members = NewHash(); builtin_methods = NewString(""); builtin_default_unref = NewString("delete $self;"); @@ -684,8 +692,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGPYTHON\n"); + Printf(f_runtime, "\n\n#ifndef SWIGPYTHON\n#define SWIGPYTHON\n#endif\n\n"); if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); @@ -800,6 +807,7 @@ public: } /* If shadow classing is enabled, we're going to change the module name to "_module" */ + String *default_import_code = NewString(""); if (shadow) { String *filen = NewStringf("%s%s.py", SWIG_output_directory(), Char(module)); // If we don't have an interface then change the module name X to _X @@ -817,25 +825,31 @@ public: f_shadow = NewString(""); f_shadow_begin = NewString(""); f_shadow_imports = NewHash(); - f_shadow_builtin_imports = NewString(""); + f_shadow_after_begin = NewString(""); f_shadow_stubs = NewString(""); Swig_register_filebyname("shadow", f_shadow); Swig_register_filebyname("python", f_shadow); - if (mod_docstring && Len(mod_docstring)) { - Printv(f_shadow, "\"\"\"\n", mod_docstring, "\n\"\"\"\n\n", NIL); + if (mod_docstring) { + if (Len(mod_docstring)) { + const char *triple_double = "\"\"\""; + // follow PEP257 rules: https://www.python.org/dev/peps/pep-0257/ + // reported by pep257: https://github.com/GreenSteam/pep257 + bool multi_line_ds = Strchr(mod_docstring, '\n') != 0; + Printv(f_shadow_after_begin, "\n", triple_double, multi_line_ds ? "\n":"", mod_docstring, multi_line_ds ? "\n":"", triple_double, "\n", NIL); + } Delete(mod_docstring); mod_docstring = NULL; } - Printv(f_shadow, "\nfrom sys import version_info\n", NULL); + Printv(default_import_code, "\nfrom sys import version_info as _swig_python_version_info\n", NULL); if (!builtin && fastproxy) { - Printv(f_shadow, "if version_info >= (3, 0, 0):\n", NULL); - Printf(f_shadow, tab4 "new_instancemethod = lambda func, inst, cls: %s.SWIG_PyInstanceMethod_New(func)\n", module); - Printv(f_shadow, "else:\n", NULL); - Printv(f_shadow, tab4, "from new import instancemethod as new_instancemethod\n", NULL); + Printv(default_import_code, "if _swig_python_version_info >= (3, 0, 0):\n", NULL); + Printf(default_import_code, tab4 "new_instancemethod = lambda func, inst, cls: %s.SWIG_PyInstanceMethod_New(func)\n", module); + Printv(default_import_code, "else:\n", NULL); + Printv(default_import_code, tab4, "from new import instancemethod as new_instancemethod\n", NULL); } /* Import the C-extension module. This should be a relative import, @@ -846,39 +860,87 @@ public: * in 2.6, and fail in 2.7 onwards), but the relative import syntax * isn't available in python 2.4 or earlier, so we have to write some * code conditional on the python version. + * + * For python 2.7.0 and newer, first determine the shadow wrappers package + * based on the __name__ it was given by the importer that loaded it. + * Then construct a name for the module based on the package name and the + * module name (we know the module name). Use importlib to try and load + * it. If an attempt to load the module with importlib fails with an + * ImportError then fallback and try and load just the module name from + * the global namespace. */ - Printv(f_shadow, "if version_info >= (2, 6, 0):\n", NULL); - Printv(f_shadow, tab4, "def swig_import_helper():\n", NULL); - Printv(f_shadow, tab8, "from os.path import dirname\n", NULL); - Printv(f_shadow, tab8, "import imp\n", NULL); - Printv(f_shadow, tab8, "fp = None\n", NULL); - Printv(f_shadow, tab8, "try:\n", NULL); - Printf(f_shadow, tab4 tab8 "fp, pathname, description = imp.find_module('%s', [dirname(__file__)])\n", module); - Printf(f_shadow, tab8 "except ImportError:\n"); + Printv(default_import_code, "if _swig_python_version_info >= (2, 7, 0):\n", NULL); + Printv(default_import_code, tab4, "def swig_import_helper():\n", NULL); + Printv(default_import_code, tab8, "import importlib\n", NULL); + Printv(default_import_code, tab8, "pkg = __name__.rpartition('.')[0]\n", NULL); + Printf(default_import_code, tab8 "mname = '.'.join((pkg, '%s')).lstrip('.')\n", module); + Printv(default_import_code, tab8, "try:\n", NULL); + Printv(default_import_code, tab8, tab4, "return importlib.import_module(mname)\n", NULL); + Printv(default_import_code, tab8, "except ImportError:\n", NULL); + Printf(default_import_code, tab8 tab4 "return importlib.import_module('%s')\n", module); + Printf(default_import_code, tab4 "%s = swig_import_helper()\n", module); + Printv(default_import_code, tab4, "del swig_import_helper\n", NULL); + Printv(default_import_code, "elif _swig_python_version_info >= (2, 6, 0):\n", NULL); + Printv(default_import_code, tab4, "def swig_import_helper():\n", NULL); + Printv(default_import_code, tab8, "from os.path import dirname\n", NULL); + Printv(default_import_code, tab8, "import imp\n", NULL); + Printv(default_import_code, tab8, "fp = None\n", NULL); + Printv(default_import_code, tab8, "try:\n", NULL); + Printf(default_import_code, tab4 tab8 "fp, pathname, description = imp.find_module('%s', [dirname(__file__)])\n", module); + Printf(default_import_code, tab8 "except ImportError:\n"); /* At here, the module may already loaded, so simply import it. */ - Printf(f_shadow, tab4 tab8 "import %s\n", module); - Printf(f_shadow, tab4 tab8 "return %s\n", module); - Printv(f_shadow, tab8 "if fp is not None:\n", NULL); - Printv(f_shadow, tab4 tab8 "try:\n", NULL); - Printf(f_shadow, tab8 tab8 "_mod = imp.load_module('%s', fp, pathname, description)\n", module); - Printv(f_shadow, tab4 tab8, "finally:\n", NULL); - Printv(f_shadow, tab8 tab8, "fp.close()\n", NULL); - Printv(f_shadow, tab4 tab8, "return _mod\n", NULL); - Printf(f_shadow, tab4 "%s = swig_import_helper()\n", module); - Printv(f_shadow, tab4, "del swig_import_helper\n", NULL); - Printv(f_shadow, "else:\n", NULL); - Printf(f_shadow, tab4 "import %s\n", module); - - /* Delete the version_info symbol since we don't use it elsewhere in the - * module. */ - Printv(f_shadow, "del version_info\n", NULL); + Printf(default_import_code, tab4 tab8 "import %s\n", module); + Printf(default_import_code, tab4 tab8 "return %s\n", module); + Printv(default_import_code, tab8 "try:\n", NULL); + /* imp.load_module() handles fp being None. */ + Printf(default_import_code, tab4 tab8 "_mod = imp.load_module('%s', fp, pathname, description)\n", module); + Printv(default_import_code, tab8, "finally:\n", NULL); + Printv(default_import_code, tab4 tab8 "if fp is not None:\n", NULL); + Printv(default_import_code, tab8 tab8, "fp.close()\n", NULL); + Printv(default_import_code, tab8, "return _mod\n", NULL); + Printf(default_import_code, tab4 "%s = swig_import_helper()\n", module); + Printv(default_import_code, tab4, "del swig_import_helper\n", NULL); + Printv(default_import_code, "else:\n", NULL); + Printf(default_import_code, tab4 "import %s\n", module); if (builtin) { - Printf(f_shadow, "from %s import *\n", module); + /* + * Pull in all the attributes from the C module. + * + * An alternative approach to doing this if/else chain was + * proposed by Michael Thon. Someone braver than I may try it out. + * I fear some current swig user may depend on some side effect + * of from _foo import * + * + * for attr in _foo.__all__: + * globals()[attr] = getattr(_foo, attr) + * + */ + Printf(default_import_code, "# pull in all the attributes from %s\n", module); + Printv(default_import_code, "if __name__.rpartition('.')[0] != '':\n", NULL); + Printv(default_import_code, tab4, "if _swig_python_version_info >= (2, 7, 0):\n", NULL); + Printv(default_import_code, tab8, "try:\n", NULL); + Printf(default_import_code, tab8 tab4 "from .%s import *\n", module); + Printv(default_import_code, tab8 "except ImportError:\n", NULL); + Printf(default_import_code, tab8 tab4 "from %s import *\n", module); + Printv(default_import_code, tab4, "else:\n", NULL); + Printf(default_import_code, tab8 "from %s import *\n", module); + Printv(default_import_code, "else:\n", NULL); + Printf(default_import_code, tab4 "from %s import *\n", module); } + + /* Delete the _swig_python_version_info symbol since we don't use it elsewhere in the + * module. */ + Printv(default_import_code, "del _swig_python_version_info\n\n", NULL); + if (modern || !classic) { Printv(f_shadow, "try:\n", tab4, "_swig_property = property\n", "except NameError:\n", tab4, "pass # Python < 2.2 doesn't have 'property'.\n\n", NULL); } + + /* Need builtins to qualify names like Exception that might also be + defined in this module (try both Python 3 and Python 2 names) */ + Printv(f_shadow, "try:\n", tab4, "import builtins as __builtin__\n", "except ImportError:\n", tab4, "import __builtin__\n", NULL); + /* if (!modern) */ /* always needed, a class can be forced to be no-modern, such as an exception */ { @@ -912,32 +974,23 @@ public: "\n", "def _swig_setattr(self, class_type, name, value):\n", tab4, "return _swig_setattr_nondynamic(self, class_type, name, value, 0)\n\n", NIL); Printv(f_shadow, - "\n", "def _swig_getattr_nondynamic(self, class_type, name, static=1):\n", + "\n", "def _swig_getattr(self, class_type, name):\n", tab4, "if (name == \"thisown\"):\n", tab8, "return self.this.own()\n", tab4, "method = class_type.__swig_getmethods__.get(name, None)\n", tab4, "if method:\n", tab8, "return method(self)\n", - tab4, "if (not static):\n", - tab4, tab4, "return object.__getattr__(self, name)\n", - tab4, "else:\n", - tab4, tab4, "raise AttributeError(name)\n\n", - "def _swig_getattr(self, class_type, name):\n", tab4, "return _swig_getattr_nondynamic(self, class_type, name, 0)\n\n", NIL); + tab4, "raise AttributeError(\"'%s' object has no attribute '%s'\" % (class_type.__name__, name))\n\n", NIL); Printv(f_shadow, "\n", "def _swig_repr(self):\n", tab4, "try:\n", tab8, "strthis = \"proxy of \" + self.this.__repr__()\n", - tab4, "except:\n", tab8, "strthis = \"\"\n", tab4, "return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n", NIL); + tab4, "except __builtin__.Exception:\n", tab8, "strthis = \"\"\n", tab4, "return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n", NIL); - if (!classic) { - /* Usage of types.ObjectType is deprecated. - * But don't sure wether this would broken old Python? - */ + if (!classic && !modern) { Printv(f_shadow, -// "import types\n", "try:\n", -// " _object = types.ObjectType\n", - tab4, "_object = object\n", tab4, "_newclass = 1\n", "except AttributeError:\n", tab4, "class _object:\n", tab8, "pass\n", tab4, "_newclass = 0\n", -// "del types\n", - "\n\n", NIL); + tab4, "_object = object\n", tab4, "_newclass = 1\n", + "except __builtin__.Exception:\n", + tab4, "class _object:\n", tab8, "pass\n", tab4, "_newclass = 0\n\n", NIL); } } if (modern) { @@ -955,7 +1008,7 @@ public: if (directorsEnabled()) { // Try loading weakref.proxy, which is only available in Python 2.1 and higher Printv(f_shadow, - "try:\n", tab4, "import weakref\n", tab4, "weakref_proxy = weakref.proxy\n", "except:\n", tab4, "weakref_proxy = lambda x: x\n", "\n\n", NIL); + "try:\n", tab4, "import weakref\n", tab4, "weakref_proxy = weakref.proxy\n", "except __builtin__.Exception:\n", tab4, "weakref_proxy = lambda x: x\n", "\n\n", NIL); } } // Include some information in the code @@ -1022,11 +1075,19 @@ public: if (shadow) { Swig_banner_target_lang(f_shadow_py, "#"); - if (!modern) { + if (!modern && !classic) { Printv(f_shadow, "# This file is compatible with both classic and new-style classes.\n", NIL); } - Printv(f_shadow_py, "\n", f_shadow_begin, "\n", NIL); - Printv(f_shadow_py, "\n", f_shadow_builtin_imports, "\n", NIL); + if (Len(f_shadow_begin) > 0) + Printv(f_shadow_py, "\n", f_shadow_begin, "\n", NIL); + if (Len(f_shadow_after_begin) > 0) + Printv(f_shadow_py, f_shadow_after_begin, "\n", NIL); + if (moduleimport) { + Replaceall(moduleimport, "$module", module); + Printv(f_shadow_py, "\n", moduleimport, "\n", NIL); + } else { + Printv(f_shadow_py, default_import_code, NIL); + } Printv(f_shadow_py, f_shadow, "\n", NIL); Printv(f_shadow_py, f_shadow_stubs, "\n", NIL); Delete(f_shadow_py); @@ -1050,6 +1111,11 @@ public: Printf(f_begin, "static PyTypeObject *builtin_bases[%d];\n\n", max_bases + 2); Wrapper_pretty_print(f_init, f_begin); + Delete(default_import_code); + Delete(f_shadow_after_begin); + Delete(f_shadow_imports); + Delete(f_shadow_begin); + Delete(f_shadow); Delete(f_header); Delete(f_wrappers); Delete(f_builtins); @@ -1229,13 +1295,14 @@ public: Printf(out, "import %s%s%s%s\n", apkg, *Char(apkg) ? "." : "", pfx, mod); Delete(apkg); } else { - if (py3) { - if (py3_rlen1) - Printf(out, "from . import %.*s\n", py3_rlen1, rpkg); - Printf(out, "from .%s import %s%s\n", rpkg, pfx, mod); - } else { - Printf(out, "import %s%s%s%s\n", rpkg, *Char(rpkg) ? "." : "", pfx, mod); - } + Printf(out, "from sys import version_info as _swig_python_version_info\n"); + Printf(out, "if _swig_python_version_info >= (2, 7, 0):\n"); + if (py3_rlen1) + Printf(out, tab4 "from . import %.*s\n", py3_rlen1, rpkg); + Printf(out, tab4 "from .%s import %s%s\n", rpkg, pfx, mod); + Printf(out, "else:\n"); + Printf(out, tab4 "import %s%s%s%s\n", rpkg, *Char(rpkg) ? "." : "", pfx, mod); + Printf(out, "del _swig_python_version_info\n"); Delete(rpkg); } return out; @@ -1325,7 +1392,7 @@ public: /* ------------------------------------------------------------ * import_name_string() - * ------------------------------------------------------------ */ + * ------------------------------------------------------------ */ static String *import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) { if (!relativeimport) { @@ -1357,7 +1424,7 @@ public: String *_import = import_directive_string(package, pkg, modname, "_"); if (!GetFlagAttr(f_shadow_imports, _import)) { String *import = import_directive_string(package, pkg, modname); - Printf(builtin ? f_shadow_builtin_imports : f_shadow, "%s", import); + Printf(builtin ? f_shadow_after_begin : f_shadow, "%s", import); Delete(import); SetFlag(f_shadow_imports, _import); } @@ -1371,9 +1438,10 @@ public: /* ------------------------------------------------------------ * funcCall() - * Emit shadow code to call a function in the extension - * module. Using proper argument and calling style for - * given node n. + * + * Emit shadow code to call a function in the extension + * module. Using proper argument and calling style for + * given node n. * ------------------------------------------------------------ */ String *funcCall(String *name, String *parms) { String *str = NewString(""); @@ -1382,12 +1450,15 @@ public: return str; } - /* ------------------------------------------------------------ - * pythoncode() - Output python code into the shadow file + * indent_pythoncode() + * + * Format (indent) Python code. + * Remove leading whitespace from 'code' and re-indent using + * the indentation string in 'indent'. * ------------------------------------------------------------ */ - String *pythoncode(String *code, const_String_or_char_ptr indent, String * file, int line) { + String *indent_pythoncode(const String *code, const_String_or_char_ptr indent, String *file, int line, const char *directive_name) { String *out = NewString(""); String *temp; char *t; @@ -1409,7 +1480,7 @@ public: // Line number within the pythoncode. int py_line = 0; - String * initial = 0; + String *initial = 0; Iterator si; /* Get the initial indentation. Skip lines which only contain whitespace @@ -1427,7 +1498,7 @@ public: const char *c = Char(si.item); int i; for (i = 0; isspace((unsigned char)c[i]); i++) { - // Scan forward until we find a non-space (which may be a nul byte). + // Scan forward until we find a non-space (which may be a null byte). } char ch = c[i]; if (ch && ch != '#') { @@ -1449,7 +1520,7 @@ public: int i; for (i = 0; isspace((unsigned char)c[i]); i++) { - // Scan forward until we find a non-space (which may be a nul byte). + // Scan forward until we find a non-space (which may be a null byte). } char ch = c[i]; if (!ch) { @@ -1474,7 +1545,7 @@ public: if (i < Len(initial)) { // There's non-whitespace in the initial prefix of this line. - Swig_error(file, line, "Line indented less than expected (line %d of pythoncode)\n", py_line); + Swig_error(file, line, "Line indented less than expected (line %d of %s) as no line should be indented less than the indentation in line 1\n", py_line, directive_name); Printv(out, indent, c, "\n", NIL); } else { if (memcmp(c, Char(initial), Len(initial)) == 0) { @@ -1483,7 +1554,7 @@ public: continue; } Swig_warning(WARN_PYTHON_INDENT_MISMATCH, - file, line, "Whitespace prefix doesn't match (line %d of pythoncode)\n", py_line); + file, line, "Whitespace indentation is inconsistent compared to earlier lines (line %d of %s)\n", py_line, directive_name); // To avoid gratuitously breaking interface files which worked with // SWIG <= 3.0.5, we remove a prefix of the same number of bytes for // lines which start with different whitespace to the line we got @@ -1495,6 +1566,72 @@ public: return out; } + /* ------------------------------------------------------------ + * indent_docstring() + * + * Format (indent) a Python docstring. + * Remove leading whitespace from 'code' and re-indent using + * the indentation string in 'indent'. + * ------------------------------------------------------------ */ + + String *indent_docstring(const String *code, const_String_or_char_ptr indent) { + String *out = NewString(""); + String *temp; + char *t; + if (!indent) + indent = ""; + + temp = NewString(code); + + t = Char(temp); + if (*t == '{') { + Delitem(temp, 0); + Delitem(temp, DOH_END); + } + + /* Split the input text into lines */ + List *clist = SplitLines(temp); + Delete(temp); + + Iterator si; + + int truncate_characters_count = INT_MAX; + for (si = First(clist); si.item; si = Next(si)) { + const char *c = Char(si.item); + int i; + for (i = 0; isspace((unsigned char)c[i]); i++) { + // Scan forward until we find a non-space (which may be a null byte). + } + char ch = c[i]; + if (ch) { + // Found a line which isn't just whitespace + if (i < truncate_characters_count) + truncate_characters_count = i; + } + } + + if (truncate_characters_count == INT_MAX) + truncate_characters_count = 0; + + for (si = First(clist); si.item; si = Next(si)) { + const char *c = Char(si.item); + + int i; + for (i = 0; isspace((unsigned char)c[i]); i++) { + // Scan forward until we find a non-space (which may be a null byte). + } + char ch = c[i]; + if (!ch) { + // Line is just whitespace - emit an empty line. + Putc('\n', out); + continue; + } + + Printv(out, indent, c + truncate_characters_count, "\n", NIL); + } + Delete(clist); + return out; + } /* ------------------------------------------------------------ * autodoc level declarations @@ -1530,8 +1667,9 @@ public: /* ------------------------------------------------------------ * have_docstring() - * Check if there is a docstring directive and it has text, - * or there is an autodoc flag set + * + * Check if there is a docstring directive and it has text, + * or there is an autodoc flag set * ------------------------------------------------------------ */ bool have_docstring(Node *n) { @@ -1552,7 +1690,7 @@ public: * Return new string to be deleted by caller (never NIL but * may be empty if there is no docstring). * ------------------------------------------------------------ */ - String *build_combined_docstring(Node *n, autodoc_t ad_type) { + String *build_combined_docstring(Node *n, autodoc_t ad_type, const String *indent = "") { String *docstr = Getattr(n, "feature:docstring"); if (docstr && Len(docstr)) { docstr = Copy(docstr); @@ -1599,20 +1737,40 @@ public: if (!docstr) docstr = NewString(""); + // If there is more than one line then make docstrings like this: + // + // """ + // This is line1 + // And here is line2 followed by the rest of them + // """ + // + // otherwise, put it all on a single line + if (Strchr(docstr, '\n')) + { + String *tmp = NewString(""); + Append(tmp, "\n"); + Append(tmp, indent_docstring(docstr, indent)); + Append(tmp, indent); + Delete(docstr); + docstr = tmp; + } + return docstr; } /* ------------------------------------------------------------ * docstring() - * Get the docstring text enclosed in triple double quotes. + * + * Get the docstring text, stripping off {} if necessary, + * and enclose in triple double quotes. If autodoc is also + * set then it will build a combined docstring. * ------------------------------------------------------------ */ - String *docstring(Node *n, autodoc_t ad_type) { - String *docstr = build_combined_docstring(n, ad_type); + String *docstring(Node *n, autodoc_t ad_type, const String *indent) { + String *docstr = build_combined_docstring(n, ad_type, indent); if (!Len(docstr)) return docstr; - // Notice that all comments are created as raw strings (prefix "r"), // because '\' is used often in comments, but may break Python module from // loading. For example, in doxy comment one may write path in quotes: @@ -1626,7 +1784,6 @@ public: Append(doc, "r\"\"\""); Append(doc, docstr); Append(doc, "\"\"\""); - Delete(docstr); return doc; @@ -1634,8 +1791,9 @@ public: /* ------------------------------------------------------------ * cdocstring() - * Get the docstring text as it would appear in C-language - * source code (but without quotes around it). + * + * Get the docstring text as it would appear in C-language + * source code (but without quotes around it). * ------------------------------------------------------------ */ String *cdocstring(Node *n, autodoc_t ad_type) @@ -1643,7 +1801,7 @@ public: String *ds = build_combined_docstring(n, ad_type); Replaceall(ds, "\\", "\\\\"); Replaceall(ds, "\"", "\\\""); - Replaceall(ds, "\n", "\\n\"\n\t\""); + Replaceall(ds, "\n", "\\n\"\n\t\t\""); return ds; } @@ -1664,7 +1822,8 @@ public: /* ----------------------------------------------------------------------------- * addMissingParameterNames() - * For functions that have not had nameless parameters set in the Language class. + * + * For functions that have not had nameless parameters set in the Language class. * * Inputs: * plist - entire parameter list @@ -1689,8 +1848,9 @@ public: /* ------------------------------------------------------------ * make_autodocParmList() - * Generate the documentation for the function parameters - * Parameters: + * + * Generate the documentation for the function parameters + * Parameters: * func_annotation: Function annotation support * ------------------------------------------------------------ */ @@ -1773,8 +1933,9 @@ public: Append(doc, name); if (pdoc) { if (!pdocs) - pdocs = NewString("\nParameters:\n"); - Printf(pdocs, " %s\n", pdoc); + // numpydoc style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt + pdocs = NewString("\nParameters\n----------\n"); + Printf(pdocs, "%s\n", pdoc); } // Write the function annotation if (func_annotation) @@ -1797,12 +1958,13 @@ public: /* ------------------------------------------------------------ * make_autodoc() - * Build a docstring for the node, using parameter and other - * info in the parse tree. If the value of the autodoc - * attribute is "0" then do not include parameter types, if - * it is "1" (the default) then do. If it has some other - * value then assume it is supplied by the extension writer - * and use it directly. + * + * Build a docstring for the node, using parameter and other + * info in the parse tree. If the value of the autodoc + * attribute is "0" then do not include parameter types, if + * it is "1" (the default) then do. If it has some other + * value then assume it is supplied by the extension writer + * and use it directly. * ------------------------------------------------------------ */ String *make_autodoc(Node *n, autodoc_t ad_type) { @@ -1869,9 +2031,9 @@ public: Delete(rname); } else { if (CPlusPlus) { - Printf(doc, "Proxy of C++ %s class", real_classname); + Printf(doc, "Proxy of C++ %s class.", real_classname); } else { - Printf(doc, "Proxy of C %s struct", real_classname); + Printf(doc, "Proxy of C %s struct.", real_classname); } } } @@ -1948,9 +2110,10 @@ public: } /* ------------------------------------------------------------ - * convertDoubleValue() - * Check if the given string looks like a decimal floating point constant - * and return it if it does, otherwise return NIL. + * convertDoubleValue() + * + * Check if the given string looks like a decimal floating point constant + * and return it if it does, otherwise return NIL. * ------------------------------------------------------------ */ String *convertDoubleValue(String *v) { const char *const s = Char(v); @@ -1971,7 +2134,7 @@ public: // Disregard optional "f" suffix, it can be just dropped in Python as it // uses doubles for everything anyhow. - for (char* p = end; *p != '\0'; ++p) { + for (char * p = end; *p != '\0'; ++p) { switch (*p) { case 'f': case 'F': @@ -1992,8 +2155,9 @@ public: /* ------------------------------------------------------------ * convertValue() - * Check if string v can be a Python value literal or a - * constant. Return NIL if it isn't. + * + * Check if string v can be a Python value literal or a + * constant. Return NIL if it isn't. * ------------------------------------------------------------ */ String *convertValue(String *v, SwigType *type) { const char *const s = Char(v); @@ -2016,7 +2180,7 @@ public: // combination of "l" and "u", but not anything else (again, stuff like // "LL" could be handled, but we don't bother to do it currently). bool seen_long = false; - for (char* p = end; *p != '\0'; ++p) { + for (char * p = end; *p != '\0'; ++p) { switch (*p) { case 'l': case 'L': @@ -2115,12 +2279,13 @@ public: /* ------------------------------------------------------------ * is_representable_as_pyargs() - * Check if the function parameters default argument values - * can be represented in Python. * - * If this method returns false, the parameters will be translated - * to a generic "*args" which allows us to deal with default values - * at C++ code level where they can always be handled. + * Check if the function parameters default argument values + * can be represented in Python. + * + * If this method returns false, the parameters will be translated + * to a generic "*args" which allows us to deal with default values + * at C++ code level where they can always be handled. * ------------------------------------------------------------ */ bool is_representable_as_pyargs(Node *n) { ParmList *plist = CopyParmList(Getattr(n, "parms")); @@ -2162,9 +2327,10 @@ public: /* ------------------------------------------------------------ * is_real_overloaded() - * Check if the function is overloaded, but not just have some - * siblings generated due to the original function have - * default arguments. + * + * Check if the function is overloaded, but not just have some + * siblings generated due to the original function have + * default arguments. * ------------------------------------------------------------ */ bool is_real_overloaded(Node *n) { Node *h = Getattr(n, "sym:overloaded"); @@ -2188,8 +2354,9 @@ public: /* ------------------------------------------------------------ * make_pyParmList() - * Generate parameter list for Python functions or methods, - * reuse make_autodocParmList() to do so. + * + * Generate parameter list for Python functions or methods, + * reuse make_autodocParmList() to do so. * ------------------------------------------------------------ */ String *make_pyParmList(Node *n, bool in_class, bool is_calling, int kw) { /* Get the original function for a defaultargs copy, @@ -2235,7 +2402,8 @@ public: /* ------------------------------------------------------------ * have_pythonprepend() - * Check if there is a %pythonprepend directive and it has text + * + * Check if there is a %pythonprepend directive and it has text * ------------------------------------------------------------ */ bool have_pythonprepend(Node *n) { @@ -2245,7 +2413,8 @@ public: /* ------------------------------------------------------------ * pythonprepend() - * Get the %pythonprepend code, stripping off {} if neccessary + * + * Get the %pythonprepend code, stripping off {} if necessary * ------------------------------------------------------------ */ String *pythonprepend(Node *n) { @@ -2260,7 +2429,8 @@ public: /* ------------------------------------------------------------ * have_pythonappend() - * Check if there is a %pythonappend directive and it has text + * + * Check if there is a %pythonappend directive and it has text * ------------------------------------------------------------ */ bool have_pythonappend(Node *n) { @@ -2272,7 +2442,8 @@ public: /* ------------------------------------------------------------ * pythonappend() - * Get the %pythonappend code, stripping off {} if neccessary + * + * Get the %pythonappend code, stripping off {} if necessary * ------------------------------------------------------------ */ String *pythonappend(Node *n) { @@ -2290,7 +2461,8 @@ public: /* ------------------------------------------------------------ * have_addtofunc() - * Check if there is a %addtofunc directive and it has text + * + * Check if there is a %addtofunc directive and it has text * ------------------------------------------------------------ */ bool have_addtofunc(Node *n) { @@ -2300,8 +2472,9 @@ public: /* ------------------------------------------------------------ * returnTypeAnnotation() - * Helper function for constructing the function annotation - * of the returning type, return a empty string for Python 2.x + * + * Helper function for constructing the function annotation + * of the returning type, return a empty string for Python 2.x * ------------------------------------------------------------ */ String *returnTypeAnnotation(Node *n) { String *ret = 0; @@ -2334,9 +2507,10 @@ public: /* ------------------------------------------------------------ * emitFunctionShadowHelper() - * Refactoring some common code out of functionWrapper and - * dispatchFunction that writes the proxy code for non-member - * functions. + * + * Refactoring some common code out of functionWrapper and + * dispatchFunction that writes the proxy code for non-member + * functions. * ------------------------------------------------------------ */ void emitFunctionShadowHelper(Node *n, File *f_dest, String *name, int kw) { @@ -2345,18 +2519,18 @@ public: /* Make a wrapper function to insert the code into */ Printv(f_dest, "\ndef ", name, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); if (have_docstring(n)) - Printv(f_dest, tab4, docstring(n, AUTODOC_FUNC), "\n", NIL); + Printv(f_dest, tab4, docstring(n, AUTODOC_FUNC, tab4), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_dest, pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_dest, indent_pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL); if (have_pythonappend(n)) { Printv(f_dest, tab4 "val = ", funcCall(name, callParms), "\n", NIL); - Printv(f_dest, pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_dest, indent_pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL); Printv(f_dest, tab4 "return val\n", NIL); } else { Printv(f_dest, tab4 "return ", funcCall(name, callParms), "\n", NIL); } - if (Getattr(n, "feature:python:callback") || !have_addtofunc(n)) { + if (!have_addtofunc(n)) { /* If there is no addtofunc directive then just assign from the extension module (for speed up) */ Printv(f_dest, name, " = ", module, ".", name, "\n", NIL); } @@ -2365,7 +2539,8 @@ public: /* ------------------------------------------------------------ * check_kwargs() - * check if using kwargs is allowed for this Node + * + * check if using kwargs is allowed for this Node * ------------------------------------------------------------ */ int check_kwargs(Node *n) const { @@ -2398,18 +2573,12 @@ public: if (!n) { Append(methods, "NULL"); - } else if (Getattr(n, "feature:callback")) { - if (have_docstring(n)) { - String *ds = cdocstring(n, AUTODOC_FUNC); - Printf(methods, "(char *)\"%s\\nswig_ptr: %s\"", ds, Getattr(n, "feature:callback:name")); - Delete(ds); - } else { - Printf(methods, "(char *)\"swig_ptr: %s\"", Getattr(n, "feature:callback:name")); - } } else if (have_docstring(n)) { String *ds = cdocstring(n, AUTODOC_FUNC); Printf(methods, "(char *)\"%s\"", ds); Delete(ds); + } else if (Getattr(n, "feature:callback")) { + Printf(methods, "(char *)\"swig_ptr: %s\"", Getattr(n, "feature:callback:name")); } else { Append(methods, "NULL"); } @@ -2445,15 +2614,15 @@ public: Printv(f->def, linkage, builtin_ctor ? "int " : "PyObject *", wname, "(PyObject *self, PyObject *args) {", NIL); - Wrapper_add_local(f, "argc", "int argc"); - Printf(tmp, "PyObject *argv[%d]", maxargs + 1); + Wrapper_add_local(f, "argc", "Py_ssize_t argc"); + Printf(tmp, "PyObject *argv[%d] = {0}", maxargs + 1); Wrapper_add_local(f, "argv", tmp); if (!fastunpack) { - Wrapper_add_local(f, "ii", "int ii"); + Wrapper_add_local(f, "ii", "Py_ssize_t ii"); if (maxargs - (add_self ? 1 : 0) > 0) Append(f->code, "if (!PyTuple_Check(args)) SWIG_fail;\n"); - Append(f->code, "argc = args ? (int)PyObject_Length(args) : 0;\n"); + Append(f->code, "argc = args ? PyObject_Length(args) : 0;\n"); if (add_self) Append(f->code, "argv[0] = self;\n"); Printf(f->code, "for (ii = 0; (ii < %d) && (ii < argc); ii++) {\n", add_self ? maxargs - 1 : maxargs); @@ -2699,7 +2868,8 @@ public: int noargs = funpack && (tuple_required == 0 && tuple_arguments == 0); int onearg = funpack && (tuple_required == 1 && tuple_arguments == 1); - if (builtin && funpack && !overname && !builtin_ctor && !GetFlag(n, "feature:compactdefaultargs")) { + if (builtin && funpack && !overname && !builtin_ctor && + !(GetFlag(n, "feature:compactdefaultargs") && (tuple_arguments > tuple_required || varargs))) { String *argattr = NewStringf("%d", tuple_arguments); Setattr(n, "python:argcount", argattr); Delete(argattr); @@ -3248,18 +3418,21 @@ public: } if (in_class && builtin) { - /* Handle operator overloads overloads for builtin types */ + /* Handle operator overloads for builtin types */ String *slot = Getattr(n, "feature:python:slot"); if (slot) { String *func_type = Getattr(n, "feature:python:slot:functype"); String *closure_decl = getClosure(func_type, wrapper_name, overname ? 0 : funpack); String *feature_name = NewStringf("feature:python:%s", slot); - String *closure_name = Copy(wrapper_name); + String *closure_name = 0; if (closure_decl) { - if (!Getattr(n, "sym:overloaded") || !Getattr(n, "sym:nextSibling")) - Printv(f_wrappers, closure_decl, "\n\n", NIL); - Append(closure_name, "_closure"); + closure_name = NewStringf("%s_%s_closure", wrapper_name, func_type); + if (!GetFlag(builtin_closures, closure_name)) + Printf(builtin_closures_code, "%s /* defines %s */\n\n", closure_decl, closure_name); + SetFlag(builtin_closures, closure_name); Delete(closure_decl); + } else { + closure_name = Copy(wrapper_name); } if (func_type) { String *s = NewStringf("(%s) %s", func_type, closure_name); @@ -3319,7 +3492,7 @@ public: Python dictionary. */ if (!have_globals) { - Printf(f_init, "\t PyDict_SetItemString(md,(char*)\"%s\", SWIG_globals());\n", global_name); + Printf(f_init, "\t PyDict_SetItemString(md,(char *)\"%s\", SWIG_globals());\n", global_name); if (builtin) Printf(f_init, "\t SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", global_name); have_globals = 1; @@ -3407,9 +3580,9 @@ public: Wrapper_print(getf, f_wrappers); /* Now add this to the variable linking mechanism */ - Printf(f_init, "\t SWIG_addvarlink(SWIG_globals(),(char*)\"%s\",%s, %s);\n", iname, vargetname, varsetname); + Printf(f_init, "\t SWIG_addvarlink(SWIG_globals(),(char *)\"%s\",%s, %s);\n", iname, vargetname, varsetname); if (builtin && shadow && !assignable && !in_class) { - Printf(f_init, "\t PyDict_SetItemString(md, (char*)\"%s\", PyObject_GetAttrString(SWIG_globals(), \"%s\"));\n", iname, iname); + Printf(f_init, "\t PyDict_SetItemString(md, (char *)\"%s\", PyObject_GetAttrString(SWIG_globals(), \"%s\"));\n", iname, iname); Printf(f_init, "\t SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", iname); } Delete(vargetname); @@ -3425,6 +3598,28 @@ public: * constantWrapper() * ------------------------------------------------------------ */ + /* Determine if the node requires the _swigconstant code to be generated */ + bool needs_swigconstant(Node *n) { + SwigType *type = Getattr(n, "type"); + SwigType *qtype = SwigType_typedef_resolve_all(type); + SwigType *uqtype = SwigType_strip_qualifiers(qtype); + bool result = false; + + /* Note, that we need special handling for function pointers, as + * SwigType_base(fptr) does not return the underlying pointer-to-function + * type but the return-type of function. */ + if(!SwigType_isfunction(uqtype) && !SwigType_isfunctionpointer(uqtype)) { + SwigType *basetype = SwigType_base(uqtype); + result = SwigType_isclass(basetype) != 0; + Delete(basetype); + } + + Delete(qtype); + Delete(uqtype); + + return result; + } + virtual int constantWrapper(Node *n) { String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); @@ -3467,19 +3662,26 @@ public: Replaceall(tm, "$source", value); Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); - if (!builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER)) && (!in_class || !Getattr(n, "feature:python:callback"))) { - // Generate method which registers the new constant + if (needs_swigconstant(n) && !builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER)) && (!in_class || !Getattr(n, "feature:python:callback"))) { + // Generate `*_swigconstant()` method which registers the new constant. + // + // *_swigconstant methods are required for constants of class type. + // Class types are registered in shadow file (see *_swigregister). The + // instances of class must be created (registered) after the type is + // registered, so we can't let SWIG_init() to register constants of + // class type (the SWIG_init() is called before shadow classes are + // defined and registered). Printf(f_wrappers, "SWIGINTERN PyObject *%s_swigconstant(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", iname); Printf(f_wrappers, tab2 "PyObject *module;\n", tm); Printf(f_wrappers, tab2 "PyObject *d;\n"); if (modernargs) { if (fastunpack) { - Printf(f_wrappers, tab2 "if (!SWIG_Python_UnpackTuple(args,(char*)\"swigconstant\", 1, 1,&module)) return NULL;\n"); + Printf(f_wrappers, tab2 "if (!SWIG_Python_UnpackTuple(args,(char *)\"swigconstant\", 1, 1,&module)) return NULL;\n"); } else { - Printf(f_wrappers, tab2 "if (!PyArg_UnpackTuple(args,(char*)\"swigconstant\", 1, 1,&module)) return NULL;\n"); + Printf(f_wrappers, tab2 "if (!PyArg_UnpackTuple(args,(char *)\"swigconstant\", 1, 1,&module)) return NULL;\n"); } } else { - Printf(f_wrappers, tab2 "if (!PyArg_ParseTuple(args,(char*)\"O:swigconstant\", &module)) return NULL;\n"); + Printf(f_wrappers, tab2 "if (!PyArg_ParseTuple(args,(char *)\"O:swigconstant\", &module)) return NULL;\n"); } Printf(f_wrappers, tab2 "d = PyModule_GetDict(module);\n"); Printf(f_wrappers, tab2 "if (!d) return NULL;\n"); @@ -3515,11 +3717,13 @@ public: } if (f_s) { - Printv(f_s, "\n",NIL); - Printv(f_s, module, ".", iname, "_swigconstant(",module,")\n", NIL); + if(needs_swigconstant(n)) { + Printv(f_s, "\n",NIL); + Printv(f_s, module, ".", iname, "_swigconstant(",module,")\n", NIL); + } Printv(f_s, iname, " = ", module, ".", iname, "\n", NIL); if (have_docstring(n)) - Printv(f_s, docstring(n, AUTODOC_CONST), "\n", NIL); + Printv(f_s, docstring(n, AUTODOC_CONST, tab4), "\n", NIL); } } return SWIG_OK; @@ -3634,13 +3838,13 @@ public: Node *parent = Swig_methodclass(n); String *basetype = Getattr(parent, "classtype"); Wrapper *w = NewWrapper(); - Printf(w->def, "SwigDirector_%s::SwigDirector_%s(PyObject* self) : Swig::Director(self) { \n", classname, classname); + Printf(w->def, "SwigDirector_%s::SwigDirector_%s(PyObject *self) : Swig::Director(self) { \n", classname, classname); Printf(w->def, " SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype); Append(w->def, "}\n"); Wrapper_print(w, f_directors); DelWrapper(w); } - Printf(f_directors_h, " SwigDirector_%s(PyObject* self);\n", classname); + Printf(f_directors_h, " SwigDirector_%s(PyObject *self);\n", classname); Delete(classname); return Language::classDirectorDefaultConstructor(n); } @@ -3814,9 +4018,14 @@ public: String *pmname = SwigType_manglestr(pname); String *templ = NewStringf("SwigPyBuiltin_%s", mname); int funpack = modernargs && fastunpack; + static String *tp_new = NewString("PyType_GenericNew"); Printv(f_init, " SwigPyBuiltin_SetMetaType(builtin_pytype, metatype);\n", NIL); - Printf(f_init, " builtin_pytype->tp_new = PyType_GenericNew;\n"); + + // We can’t statically initialize a structure member with a function defined in another C module + // So this is done in the initialization function instead, see https://docs.python.org/2/extending/newtypes.html + Printf(f_init, " builtin_pytype->tp_new = %s;\n", getSlot(n, "feature:python:tp_new", tp_new)); + Printv(f_init, " builtin_base_count = 0;\n", NIL); List *baselist = Getattr(n, "bases"); if (baselist) { @@ -3830,8 +4039,8 @@ public: SwigType_add_pointer(base_name); String *base_mname = SwigType_manglestr(base_name); Printf(f_init, " builtin_basetype = SWIG_MangledTypeQuery(\"%s\");\n", base_mname); - Printv(f_init, " if (builtin_basetype && builtin_basetype->clientdata && ((SwigPyClientData*) builtin_basetype->clientdata)->pytype) {\n", NIL); - Printv(f_init, " builtin_bases[builtin_base_count++] = ((SwigPyClientData*) builtin_basetype->clientdata)->pytype;\n", NIL); + Printv(f_init, " if (builtin_basetype && builtin_basetype->clientdata && ((SwigPyClientData *) builtin_basetype->clientdata)->pytype) {\n", NIL); + Printv(f_init, " builtin_bases[builtin_base_count++] = ((SwigPyClientData *) builtin_basetype->clientdata)->pytype;\n", NIL); Printv(f_init, " } else {\n", NIL); Printf(f_init, " PyErr_SetString(PyExc_TypeError, \"Could not create type '%s' as base '%s' has not been initialized.\\n\");\n", symname, bname); Printv(f_init, "#if PY_VERSION_HEX >= 0x03000000\n", NIL); @@ -3853,13 +4062,7 @@ public: // Check for non-public destructor, in which case tp_dealloc will issue // a warning and allow the memory to leak. Any class that doesn't explicitly // have a private/protected destructor has an implicit public destructor. - String *tp_dealloc = Getattr(n, "feature:python:tp_dealloc"); - if (tp_dealloc) { - Printf(f, "SWIGPY_DESTRUCTOR_CLOSURE(%s)\n", tp_dealloc); - tp_dealloc = NewStringf("%s_closure", tp_dealloc); - } else { - tp_dealloc = NewString("SwigPyBuiltin_BadDealloc"); - } + static String *tp_dealloc_bad = NewString("SwigPyBuiltin_BadDealloc"); String *getset_name = NewStringf("%s_getset", templ); String *methods_name = NewStringf("%s_methods", templ); @@ -3881,12 +4084,12 @@ public: String *gspair = NewStringf("%s_%s_getset", symname, memname); Printf(f, "static SwigPyGetSet %s = { %s, %s };\n", gspair, getter ? getter : "0", setter ? setter : "0"); String *entry = - NewStringf("{ (char*) \"%s\", (getter) %s, (setter) %s, (char*)\"%s.%s\", (void*) &%s }\n", memname, getter_closure, + NewStringf("{ (char *) \"%s\", (getter) %s, (setter) %s, (char *)\"%s.%s\", (void *) &%s }\n", memname, getter_closure, setter_closure, name, memname, gspair); if (GetFlag(mgetset, "static")) { Printf(f, "static PyGetSetDef %s_def = %s;\n", gspair, entry); Printf(f_init, "static_getset = SwigPyStaticVar_new_getset(metatype, &%s_def);\n", gspair); - Printf(f_init, "PyDict_SetItemString(d, static_getset->d_getset->name, (PyObject*) static_getset);\n", memname); + Printf(f_init, "PyDict_SetItemString(d, static_getset->d_getset->name, (PyObject *) static_getset);\n", memname); Printf(f_init, "Py_DECREF(static_getset);\n"); } else { Printf(getset_def, " %s,\n", entry); @@ -3954,10 +4157,17 @@ public: quoted_symname = NewStringf("\"%s\"", symname); } String *quoted_tp_doc_str = NewStringf("\"%s\"", getSlot(n, "feature:python:tp_doc")); - char const *tp_init = builtin_tp_init ? Char(builtin_tp_init) : Swig_directorclass(n) ? "0" : "SwigPyBuiltin_BadInit"; + String *tp_init = NewString(builtin_tp_init ? Char(builtin_tp_init) : Swig_directorclass(n) ? "0" : "SwigPyBuiltin_BadInit"); String *tp_flags = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES"); - String *py3_tp_flags = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE"); + String *tp_flags_py3 = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE"); + static String *tp_basicsize = NewStringf("sizeof(SwigPyObject)"); + static String *tp_dictoffset_default = NewString("offsetof(SwigPyObject, dict)"); + static String *tp_hash = NewString("SwigPyObject_hash"); + String *tp_as_number = NewStringf("&%s_type.as_number", templ); + String *tp_as_sequence = NewStringf("&%s_type.as_sequence", templ); + String *tp_as_mapping = NewStringf("&%s_type.as_mapping", templ); + String *tp_as_buffer = NewStringf("&%s_type.as_buffer", templ); Printf(f, "static PyHeapTypeObject %s_type = {\n", templ); @@ -3970,9 +4180,9 @@ public: printSlot(f, getSlot(), "ob_size"); Printv(f, "#endif\n", NIL); printSlot(f, quoted_symname, "tp_name"); - printSlot(f, "sizeof(SwigPyObject)", "tp_basicsize"); + printSlot(f, getSlot(n, "feature:python:tp_basicsize", tp_basicsize), "tp_basicsize"); printSlot(f, getSlot(n, "feature:python:tp_itemsize"), "tp_itemsize"); - printSlot(f, tp_dealloc, "tp_dealloc", "destructor"); + printSlot(f, getSlot(n, "feature:python:tp_dealloc", tp_dealloc_bad), "tp_dealloc", "destructor"); printSlot(f, getSlot(n, "feature:python:tp_print"), "tp_print", "printfunc"); printSlot(f, getSlot(n, "feature:python:tp_getattr"), "tp_getattr", "getattrfunc"); printSlot(f, getSlot(n, "feature:python:tp_setattr"), "tp_setattr", "setattrfunc"); @@ -3982,19 +4192,19 @@ public: printSlot(f, getSlot(n, "feature:python:tp_compare"), "tp_compare", "cmpfunc"); Printv(f, "#endif\n", NIL); printSlot(f, getSlot(n, "feature:python:tp_repr"), "tp_repr", "reprfunc"); - Printf(f, " &%s_type.as_number, /* tp_as_number */\n", templ); - Printf(f, " &%s_type.as_sequence, /* tp_as_sequence */\n", templ); - Printf(f, " &%s_type.as_mapping, /* tp_as_mapping */\n", templ); - printSlot(f, getSlot(n, "feature:python:tp_hash"), "tp_hash", "hashfunc"); + printSlot(f, getSlot(n, "feature:python:tp_as_number", tp_as_number), "tp_as_number"); + printSlot(f, getSlot(n, "feature:python:tp_as_sequence", tp_as_sequence), "tp_as_sequence"); + printSlot(f, getSlot(n, "feature:python:tp_as_mapping", tp_as_mapping), "tp_as_mapping"); + printSlot(f, getSlot(n, "feature:python:tp_hash", tp_hash), "tp_hash", "hashfunc"); printSlot(f, getSlot(n, "feature:python:tp_call"), "tp_call", "ternaryfunc"); printSlot(f, getSlot(n, "feature:python:tp_str"), "tp_str", "reprfunc"); printSlot(f, getSlot(n, "feature:python:tp_getattro"), "tp_getattro", "getattrofunc"); printSlot(f, getSlot(n, "feature:python:tp_setattro"), "tp_setattro", "setattrofunc"); - Printf(f, " &%s_type.as_buffer, /* tp_as_buffer */\n", templ); + printSlot(f, getSlot(n, "feature:python:tp_as_buffer", tp_as_buffer), "tp_as_buffer"); Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL); - printSlot(f, py3_tp_flags, "tp_flags"); + printSlot(f, getSlot(n, "feature:python:tp_flags", tp_flags_py3), "tp_flags"); Printv(f, "#else\n", NIL); - printSlot(f, tp_flags, "tp_flags"); + printSlot(f, getSlot(n, "feature:python:tp_flags", tp_flags), "tp_flags"); Printv(f, "#endif\n", NIL); if (have_docstring(n)) { String *ds = cdocstring(n, AUTODOC_CLASS); @@ -4008,34 +4218,55 @@ public: } printSlot(f, getSlot(n, "feature:python:tp_traverse"), "tp_traverse", "traverseproc"); printSlot(f, getSlot(n, "feature:python:tp_clear"), "tp_clear", "inquiry"); - printSlot(f, richcompare_func, "feature:python:tp_richcompare", "richcmpfunc"); + printSlot(f, getSlot(n, "feature:python:tp_richcompare", richcompare_func), "tp_richcompare", "richcmpfunc"); printSlot(f, getSlot(n, "feature:python:tp_weaklistoffset"), "tp_weaklistoffset"); printSlot(f, getSlot(n, "feature:python:tp_iter"), "tp_iter", "getiterfunc"); printSlot(f, getSlot(n, "feature:python:tp_iternext"), "tp_iternext", "iternextfunc"); - printSlot(f, methods_name, "tp_methods"); + printSlot(f, getSlot(n, "feature:python:tp_methods", methods_name), "tp_methods"); printSlot(f, getSlot(n, "feature:python:tp_members"), "tp_members"); - printSlot(f, getset_name, "tp_getset"); + printSlot(f, getSlot(n, "feature:python:tp_getset", getset_name), "tp_getset"); printSlot(f, getSlot(n, "feature:python:tp_base"), "tp_base"); printSlot(f, getSlot(n, "feature:python:tp_dict"), "tp_dict"); printSlot(f, getSlot(n, "feature:python:tp_descr_get"), "tp_descr_get", "descrgetfunc"); printSlot(f, getSlot(n, "feature:python:tp_descr_set"), "tp_descr_set", "descrsetfunc"); - Printf(f, " (Py_ssize_t)offsetof(SwigPyObject, dict), /* tp_dictoffset */\n"); - printSlot(f, tp_init, "tp_init", "initproc"); + printSlot(f, getSlot(n, "feature:python:tp_dictoffset", tp_dictoffset_default), "tp_dictoffset", "Py_ssize_t"); + printSlot(f, getSlot(n, "feature:python:tp_init", tp_init), "tp_init", "initproc"); printSlot(f, getSlot(n, "feature:python:tp_alloc"), "tp_alloc", "allocfunc"); - printSlot(f, "0", "tp_new", "newfunc"); + printSlot(f, getSlot(), "tp_new", "newfunc"); printSlot(f, getSlot(n, "feature:python:tp_free"), "tp_free", "freefunc"); - printSlot(f, getSlot(), "tp_is_gc", "inquiry"); - printSlot(f, getSlot(), "tp_bases", "PyObject*"); - printSlot(f, getSlot(), "tp_mro", "PyObject*"); - printSlot(f, getSlot(), "tp_cache", "PyObject*"); - printSlot(f, getSlot(), "tp_subclasses", "PyObject*"); - printSlot(f, getSlot(), "tp_weaklist", "PyObject*"); - printSlot(f, getSlot(), "tp_del", "destructor"); + printSlot(f, getSlot(n, "feature:python:tp_is_gc"), "tp_is_gc", "inquiry"); + printSlot(f, getSlot(n, "feature:python:tp_bases"), "tp_bases", "PyObject *"); + printSlot(f, getSlot(n, "feature:python:tp_mro"), "tp_mro", "PyObject *"); + printSlot(f, getSlot(n, "feature:python:tp_cache"), "tp_cache", "PyObject *"); + printSlot(f, getSlot(n, "feature:python:tp_subclasses"), "tp_subclasses", "PyObject *"); + printSlot(f, getSlot(n, "feature:python:tp_weaklist"), "tp_weaklist", "PyObject *"); + printSlot(f, getSlot(n, "feature:python:tp_del"), "tp_del", "destructor"); Printv(f, "#if PY_VERSION_HEX >= 0x02060000\n", NIL); printSlot(f, getSlot(n, "feature:python:tp_version_tag"), "tp_version_tag", "int"); Printv(f, "#endif\n", NIL); + Printv(f, "#if PY_VERSION_HEX >= 0x03040000\n", NIL); + printSlot(f, getSlot(n, "feature:python:tp_finalize"), "tp_finalize", "destructor"); + Printv(f, "#endif\n", NIL); + Printv(f, "#ifdef COUNT_ALLOCS\n", NIL); + printSlot(f, getSlot(n, "feature:python:tp_allocs"), "tp_allocs", "Py_ssize_t"); + printSlot(f, getSlot(n, "feature:python:tp_frees"), "tp_frees", "Py_ssize_t"); + printSlot(f, getSlot(n, "feature:python:tp_maxalloc"), "tp_maxalloc", "Py_ssize_t"); + Printv(f, "#if PY_VERSION_HEX >= 0x02050000\n", NIL); + printSlot(f, getSlot(n, "feature:python:tp_prev"), "tp_prev"); + Printv(f, "#endif\n", NIL); + printSlot(f, getSlot(n, "feature:python:tp_next"), "tp_next"); + Printv(f, "#endif\n", NIL); Printf(f, " },\n"); + // PyAsyncMethods as_async + Printv(f, "#if PY_VERSION_HEX >= 0x03050000\n", NIL); + Printf(f, " {\n"); + printSlot(f, getSlot(n, "feature:python:am_await"), "am_await", "unaryfunc"); + printSlot(f, getSlot(n, "feature:python:am_aiter"), "am_aiter", "unaryfunc"); + printSlot(f, getSlot(n, "feature:python:am_anext"), "am_anext", "unaryfunc"); + Printf(f, " },\n"); + Printv(f, "#endif\n", NIL); + // PyNumberMethods as_number Printf(f, " {\n"); printSlot(f, getSlot(n, "feature:python:nb_add"), "nb_add", "binaryfunc"); @@ -4062,7 +4293,7 @@ public: Printv(f, "#endif\n", NIL); printSlot(f, getSlot(n, "feature:python:nb_int"), "nb_int", "unaryfunc"); Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL); - printSlot(f, getSlot(n, "feature:python:nb_reserved"), "nb_reserved", "void*"); + printSlot(f, getSlot(n, "feature:python:nb_reserved"), "nb_reserved", "void *"); Printv(f, "#else\n", NIL); printSlot(f, getSlot(n, "feature:python:nb_long"), "nb_long", "unaryfunc"); Printv(f, "#endif\n", NIL); @@ -4085,12 +4316,16 @@ public: printSlot(f, getSlot(n, "feature:python:nb_inplace_xor"), "nb_inplace_xor", "binaryfunc"); printSlot(f, getSlot(n, "feature:python:nb_inplace_or"), "nb_inplace_or", "binaryfunc"); printSlot(f, getSlot(n, "feature:python:nb_floor_divide"), "nb_floor_divide", "binaryfunc"); - printSlot(f, getSlot(n, "feature:python:nb_true_divide"), "nb_true_divide", "binaryfunc"); + printSlot(f, getSlot(n, "feature:python:nb_divide"), "nb_true_divide", "binaryfunc"); printSlot(f, getSlot(n, "feature:python:nb_inplace_floor_divide"), "nb_inplace_floor_divide", "binaryfunc"); - printSlot(f, getSlot(n, "feature:python:nb_inplace_true_divide"), "nb_inplace_true_divide", "binaryfunc"); + printSlot(f, getSlot(n, "feature:python:nb_inplace_divide"), "nb_inplace_true_divide", "binaryfunc"); Printv(f, "#if PY_VERSION_HEX >= 0x02050000\n", NIL); printSlot(f, getSlot(n, "feature:python:nb_index"), "nb_index", "unaryfunc"); Printv(f, "#endif\n", NIL); + Printv(f, "#if PY_VERSION_HEX >= 0x03050000\n", NIL); + printSlot(f, getSlot(n, "feature:python:nb_matrix_multiply"), "nb_matrix_multiply", "binaryfunc"); + printSlot(f, getSlot(n, "feature:python:nb_inplace_matrix_multiply"), "nb_inplace_matrix_multiply", "binaryfunc"); + Printv(f, "#endif\n", NIL); Printf(f, " },\n"); // PyMappingMethods as_mapping; @@ -4107,13 +4342,13 @@ public: printSlot(f, getSlot(n, "feature:python:sq_repeat"), "sq_repeat", "ssizeargfunc"); printSlot(f, getSlot(n, "feature:python:sq_item"), "sq_item", "ssizeargfunc"); Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL); - printSlot(f, getSlot(n, "feature:was_sq_slice"), "was_sq_slice", "void*"); + printSlot(f, getSlot(n, "feature:python:was_sq_slice"), "was_sq_slice", "void *"); Printv(f, "#else\n", NIL); printSlot(f, getSlot(n, "feature:python:sq_slice"), "sq_slice", "ssizessizeargfunc"); Printv(f, "#endif\n", NIL); printSlot(f, getSlot(n, "feature:python:sq_ass_item"), "sq_ass_item", "ssizeobjargproc"); Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL); - printSlot(f, getSlot(n, "feature:was_sq_ass_slice"), "was_sq_ass_slice", "void*"); + printSlot(f, getSlot(n, "feature:python:was_sq_ass_slice"), "was_sq_ass_slice", "void *"); Printv(f, "#else\n", NIL); printSlot(f, getSlot(n, "feature:python:sq_ass_slice"), "sq_ass_slice", "ssizessizeobjargproc"); Printv(f, "#endif\n", NIL); @@ -4136,31 +4371,33 @@ public: Printv(f, "#endif\n", NIL); Printf(f, " },\n"); - // PyObject *ht_name, *ht_slots - printSlot(f, getSlot(n, "feature:python:ht_name"), "ht_name", "PyObject*"); - printSlot(f, getSlot(n, "feature:python:ht_slots"), "ht_slots", "PyObject*"); + // PyObject *ht_name, *ht_slots, *ht_qualname; + printSlot(f, getSlot(n, "feature:python:ht_name"), "ht_name", "PyObject *"); + printSlot(f, getSlot(n, "feature:python:ht_slots"), "ht_slots", "PyObject *"); + Printv(f, "#if PY_VERSION_HEX >= 0x03030000\n", NIL); + printSlot(f, getSlot(n, "feature:python:ht_qualname"), "ht_qualname", "PyObject *"); + + // struct _dictkeysobject *ht_cached_keys; + printSlot(f, getSlot(n, "feature:python:ht_cached_keys"), "ht_cached_keys"); + Printv(f, "#endif\n", NIL); Printf(f, "};\n\n"); String *clientdata = NewString(""); Printf(clientdata, "&%s_clientdata", templ); SwigType_remember_mangleddata(pmname, clientdata); - String *smartptr = Getattr(n, "feature:smartptr"); - if (smartptr) { - SwigType *spt = Swig_cparse_type(smartptr); - SwigType *smart = SwigType_typedef_resolve_all(spt); + SwigType *smart = Swig_cparse_smartptr(n); + if (smart) { SwigType_add_pointer(smart); String *smart_pmname = SwigType_manglestr(smart); SwigType_remember_mangleddata(smart_pmname, clientdata); - Delete(spt); - Delete(smart); Delete(smart_pmname); } String *clientdata_klass = NewString("0"); if (GetFlag(n, "feature:implicitconv")) { Clear(clientdata_klass); - Printf(clientdata_klass, "(PyObject*) &%s_type", templ); + Printf(clientdata_klass, "(PyObject *) &%s_type", templ); } Printf(f, "SWIGINTERN SwigPyClientData %s_clientdata = {%s, 0, 0, 0, 0, 0, (PyTypeObject *)&%s_type};\n\n", templ, clientdata_klass, templ); @@ -4174,21 +4411,26 @@ public: Printv(f_init, "#endif\n", NIL); Printv(f_init, " }\n", NIL); Printv(f_init, " Py_INCREF(builtin_pytype);\n", NIL); - Printf(f_init, " PyModule_AddObject(m, \"%s\", (PyObject*) builtin_pytype);\n", symname); + Printf(f_init, " PyModule_AddObject(m, \"%s\", (PyObject *)builtin_pytype);\n", symname); Printf(f_init, " SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", symname); Printv(f_init, " d = md;\n", NIL); Delete(clientdata); + Delete(smart); Delete(rname); Delete(pname); Delete(mname); Delete(pmname); Delete(templ); - Delete(tp_dealloc); Delete(tp_flags); - Delete(py3_tp_flags); + Delete(tp_flags_py3); + Delete(tp_as_buffer); + Delete(tp_as_mapping); + Delete(tp_as_sequence); + Delete(tp_as_number); Delete(quoted_symname); Delete(quoted_tp_doc_str); + Delete(tp_init); Delete(clientdata_klass); Delete(richcompare_func); Delete(getset_name); @@ -4312,9 +4554,9 @@ public: // write docstrings if requested if (have_docstring(n)) { - String *str = docstring(n, AUTODOC_CLASS); + String *str = docstring(n, AUTODOC_CLASS, tab4); if (str && Len(str)) - Printv(f_shadow, tab4, str, "\n", NIL); + Printv(f_shadow, tab4, str, "\n\n", NIL); } if (!modern) { @@ -4363,7 +4605,7 @@ public: SwigType_add_pointer(p_real_classname); String *mangle = SwigType_manglestr(p_real_classname); String *descriptor = NewStringf("SWIGTYPE%s", mangle); - Printv(none_comparison, "self->ob_type != ((SwigPyClientData*) (", descriptor, ")->clientdata)->pytype", NIL); + Printv(none_comparison, "self->ob_type != ((SwigPyClientData *)(", descriptor, ")->clientdata)->pytype", NIL); Delete(descriptor); Delete(mangle); Delete(p_real_classname); @@ -4378,34 +4620,29 @@ public: /* Complete the class */ if (shadow) { /* Generate a class registration function */ - String *smartptr = Getattr(n, "feature:smartptr"); // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers) - SwigType *smart = 0; - if (smartptr) { - SwigType *cpt = Swig_cparse_type(smartptr); - if (cpt) { - smart = SwigType_typedef_resolve_all(cpt); - Delete(cpt); - } else { - // TODO: report line number of where the feature comes from - Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, real_classname); - } - } + // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers) + SwigType *smart = Swig_cparse_smartptr(n); SwigType *ct = Copy(smart ? smart : real_classname); SwigType_add_pointer(ct); SwigType *realct = Copy(real_classname); SwigType_add_pointer(realct); SwigType_remember(realct); - if (!builtin) { + if (builtin) { + Printv(f_wrappers, builtin_closures_code, NIL); + Delete(builtin_closures_code); + builtin_closures_code = NewString(""); + Clear(builtin_closures); + } else { Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL); Printv(f_wrappers, " PyObject *obj;\n", NIL); if (modernargs) { if (fastunpack) { - Printv(f_wrappers, " if (!SWIG_Python_UnpackTuple(args,(char*)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL); + Printv(f_wrappers, " if (!SWIG_Python_UnpackTuple(args,(char *)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL); } else { - Printv(f_wrappers, " if (!PyArg_UnpackTuple(args,(char*)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL); + Printv(f_wrappers, " if (!PyArg_UnpackTuple(args,(char *)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL); } } else { - Printv(f_wrappers, " if (!PyArg_ParseTuple(args,(char*)\"O:swigregister\", &obj)) return NULL;\n", NIL); + Printv(f_wrappers, " if (!PyArg_ParseTuple(args,(char *)\"O:swigregister\", &obj)) return NULL;\n", NIL); } Printv(f_wrappers, @@ -4458,11 +4695,11 @@ public: if (!modern) { Printv(f_shadow_file, tab8, "try:\n", tab8, tab4, "self.this.append(this)\n", - tab8, "except:\n", tab8, tab4, "self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL); + tab8, "except __builtin__.Exception:\n", tab8, tab4, "self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL); } else { Printv(f_shadow_file, tab8, "try:\n", tab8, tab4, "self.this.append(this)\n", - tab8, "except:\n", tab8, tab4, "self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL); + tab8, "except __builtin__.Exception:\n", tab8, tab4, "self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL); } } @@ -4548,13 +4785,13 @@ public: int argcount = Getattr(n, "python:argcount") ? atoi(Char(Getattr(n, "python:argcount"))) : 2; String *ds = have_docstring(n) ? cdocstring(n, AUTODOC_METHOD) : NewString(""); if (check_kwargs(n)) { - Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_VARARGS|METH_KEYWORDS, (char*) \"%s\" },\n", symname, wname, ds); + Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_VARARGS|METH_KEYWORDS, (char *) \"%s\" },\n", symname, wname, ds); } else if (argcount == 0) { - Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_NOARGS, (char*) \"%s\" },\n", symname, wname, ds); + Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_NOARGS, (char *) \"%s\" },\n", symname, wname, ds); } else if (argcount == 1) { - Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_O, (char*) \"%s\" },\n", symname, wname, ds); + Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_O, (char *) \"%s\" },\n", symname, wname, ds); } else { - Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_VARARGS, (char*) \"%s\" },\n", symname, wname, ds); + Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, METH_VARARGS, (char *) \"%s\" },\n", symname, wname, ds); } Delete(fullname); Delete(wname); @@ -4573,7 +4810,7 @@ public: have_repr = 1; } if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n)); + String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n), "%feature(\"shadow\")"); String *pyaction = NewStringf("%s.%s", module, fullname); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4592,15 +4829,15 @@ public: } else { Printv(f_shadow, "\n", tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); if (have_docstring(n)) - Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD), "\n", NIL); + Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD, tab8), "\n", NIL); if (have_pythonprepend(n)) { fproxy = 0; - Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL); } if (have_pythonappend(n)) { fproxy = 0; Printv(f_shadow, tab8, "val = ", funcCall(fullname, callParms), "\n", NIL); - Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL); Printv(f_shadow, tab8, "return val\n\n", NIL); } else { Printv(f_shadow, tab8, "return ", funcCall(fullname, callParms), "\n\n", NIL); @@ -4655,7 +4892,7 @@ public: Append(pyflags, "METH_VARARGS"); if (have_docstring(n)) { String *ds = cdocstring(n, AUTODOC_STATICFUNC); - Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, %s, (char*) \"%s\" },\n", symname, wname, pyflags, ds); + Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, %s, (char *) \"%s\" },\n", symname, wname, pyflags, ds); Delete(ds); } else { Printf(builtin_methods, " { \"%s\", (PyCFunction) %s, %s, \"\" },\n", symname, wname, pyflags); @@ -4672,41 +4909,35 @@ public: } if (shadow) { - if (!classic && !Getattr(n, "feature:python:callback") && have_addtofunc(n)) { + if (!Getattr(n, "feature:python:callback") && have_addtofunc(n)) { int kw = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0; String *parms = make_pyParmList(n, false, false, kw); String *callParms = make_pyParmList(n, false, true, kw); Printv(f_shadow, "\n", tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); if (have_docstring(n)) - Printv(f_shadow, tab8, docstring(n, AUTODOC_STATICFUNC), "\n", NIL); + Printv(f_shadow, tab8, docstring(n, AUTODOC_STATICFUNC, tab8), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL); if (have_pythonappend(n)) { Printv(f_shadow, tab8, "val = ", funcCall(Swig_name_member(NSPACE_TODO, class_name, symname), callParms), "\n", NIL); - Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL); Printv(f_shadow, tab8, "return val\n\n", NIL); } else { Printv(f_shadow, tab8, "return ", funcCall(Swig_name_member(NSPACE_TODO, class_name, symname), callParms), "\n\n", NIL); } - if (!modern) - Printv(f_shadow, tab4, "if _newclass:\n", tab4, NIL); Printv(f_shadow, tab4, symname, " = staticmethod(", symname, ")\n", NIL); - - if (!modern) { - Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = lambda x: ", symname, "\n", NIL); - } - } else { - if (!modern) { - Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = lambda x: ", module, ".", Swig_name_member(NSPACE_TODO, class_name, symname), "\n", - NIL); - } if (!classic) { if (!modern) Printv(f_shadow, tab4, "if _newclass:\n", tab4, NIL); Printv(f_shadow, tab4, symname, " = staticmethod(", module, ".", Swig_name_member(NSPACE_TODO, class_name, symname), ")\n", NIL); } + if (classic || !modern) { + if (!classic) + Printv(f_shadow, tab4, "else:\n", tab4, NIL); + Printv(f_shadow, tab4, symname, " = ", module, ".", Swig_name_member(NSPACE_TODO, class_name, symname), "\n", NIL); + } } } return SWIG_OK; @@ -4768,7 +4999,7 @@ public: if (!have_constructor && handled_as_init) { if (!builtin) { if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n)); + String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n), "%feature(\"shadow\")"); String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(NSPACE_TODO, symname)); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4795,19 +5026,19 @@ public: Printv(f_shadow, "\n", tab4, "def __init__(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); if (have_docstring(n)) - Printv(f_shadow, tab8, docstring(n, AUTODOC_CTOR), "\n", NIL); + Printv(f_shadow, tab8, docstring(n, AUTODOC_CTOR, tab8), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL); Printv(f_shadow, pass_self, NIL); if (fastinit) { Printv(f_shadow, tab8, module, ".", class_name, "_swiginit(self, ", funcCall(Swig_name_construct(NSPACE_TODO, symname), callParms), ")\n", NIL); } else { Printv(f_shadow, tab8, "this = ", funcCall(Swig_name_construct(NSPACE_TODO, symname), callParms), "\n", - tab8, "try:\n", tab8, tab4, "self.this.append(this)\n", tab8, "except:\n", tab8, tab4, "self.this = this\n", NIL); + tab8, "try:\n", tab8, tab4, "self.this.append(this)\n", tab8, "except __builtin__.Exception:\n", tab8, tab4, "self.this = this\n", NIL); } if (have_pythonappend(n)) - Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n\n", NIL); Delete(pass_self); } have_constructor = 1; @@ -4816,7 +5047,7 @@ public: /* Hmmm. We seem to be creating a different constructor. We're just going to create a function for it. */ if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), "", Getfile(n), Getline(n)); + String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), "", Getfile(n), Getline(n), "%feature(\"shadow\")"); String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(NSPACE_TODO, symname)); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4828,9 +5059,9 @@ public: Printv(f_shadow_stubs, "\ndef ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); if (have_docstring(n)) - Printv(f_shadow_stubs, tab4, docstring(n, AUTODOC_CTOR), "\n", NIL); + Printv(f_shadow_stubs, tab4, docstring(n, AUTODOC_CTOR, tab4), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow_stubs, pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow_stubs, indent_pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL); String *subfunc = NULL; /* if (builtin) @@ -4843,7 +5074,7 @@ public: Printv(f_shadow_stubs, tab4, "val.thisown = 1\n", NIL); #endif if (have_pythonappend(n)) - Printv(f_shadow_stubs, pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow_stubs, indent_pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL); Printv(f_shadow_stubs, tab4, "return val\n", NIL); Delete(subfunc); } @@ -4863,12 +5094,10 @@ public: if (builtin && in_class) { Node *cls = Swig_methodclass(n); + // Use the destructor for the tp_dealloc slot unless a user overrides it with another method if (!Getattr(cls, "feature:python:tp_dealloc")) { - String *dealloc = Swig_name_destroy(NSPACE_TODO, symname); - String *wdealloc = Swig_name_wrapper(dealloc); - Setattr(cls, "feature:python:tp_dealloc", wdealloc); - Delete(wdealloc); - Delete(dealloc); + Setattr(n, "feature:python:slot", "tp_dealloc"); + Setattr(n, "feature:python:slot:functype", "destructor"); } } @@ -4880,7 +5109,7 @@ public: if (shadow) { if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n)); + String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n), "%feature(\"shadow\")"); String *pyaction = NewStringf("%s.%s", module, Swig_name_destroy(NSPACE_TODO, symname)); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4896,17 +5125,17 @@ public: } Printv(f_shadow, tab4, "def __del__(self):\n", NIL); if (have_docstring(n)) - Printv(f_shadow, tab8, docstring(n, AUTODOC_DTOR), "\n", NIL); + Printv(f_shadow, tab8, docstring(n, AUTODOC_DTOR, tab8), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL); #ifdef USE_THISOWN Printv(f_shadow, tab8, "try:\n", NIL); Printv(f_shadow, tab8, tab4, "if self.thisown:", module, ".", Swig_name_destroy(NSPACE_TODO, symname), "(self)\n", NIL); - Printv(f_shadow, tab8, "except: pass\n", NIL); + Printv(f_shadow, tab8, "except __builtin__.Exception: pass\n", NIL); #else #endif if (have_pythonappend(n)) - Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); + Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL); Printv(f_shadow, tab8, "pass\n", NIL); Printv(f_shadow, "\n", NIL); } @@ -5070,7 +5299,7 @@ public: } else if (shadow) { Printv(f_shadow, tab4, symname, " = ", module, ".", Swig_name_member(NSPACE_TODO, class_name, symname), "\n", NIL); if (have_docstring(n)) - Printv(f_shadow, tab4, docstring(n, AUTODOC_CONST), "\n", NIL); + Printv(f_shadow, tab4, docstring(n, AUTODOC_CONST, tab4), "\n", NIL); } return SWIG_OK; } @@ -5088,12 +5317,12 @@ public: if (!ImportMode && (Cmp(section, "python") == 0 || Cmp(section, "shadow") == 0)) { if (shadow) { - String *pycode = pythoncode(code, shadow_indent, Getfile(n), Getline(n)); + String *pycode = indent_pythoncode(code, shadow_indent, Getfile(n), Getline(n), "%pythoncode or %insert(\"python\") block"); Printv(f_shadow, pycode, NIL); Delete(pycode); } } else if (!ImportMode && (Cmp(section, "pythonbegin") == 0)) { - String *pycode = pythoncode(code, "", Getfile(n), Getline(n)); + String *pycode = indent_pythoncode(code, "", Getfile(n), Getline(n), "%pythonbegin or %insert(\"pythonbegin\") block"); Printv(f_shadow_begin, pycode, NIL); Delete(pycode); } else { @@ -5450,9 +5679,9 @@ int PYTHON::classDirectorMethod(Node *n, Node *parent, String *super) { Append(w->code, "}\n"); Append(w->code, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n"); Printf(w->code, "const size_t swig_method_index = %d;\n", director_method_index++); - Printf(w->code, "const char * const swig_method_name = \"%s\";\n", pyname); + Printf(w->code, "const char *const swig_method_name = \"%s\";\n", pyname); - Append(w->code, "PyObject* method = swig_get_method(swig_method_index, swig_method_name);\n"); + Append(w->code, "PyObject *method = swig_get_method(swig_method_index, swig_method_name);\n"); if (Len(parse_args) > 0) { if (use_parse || !modernargs) { Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, (char *)\"(%s)\" %s);\n", Swig_cresult_name(), parse_args, arglist); @@ -5462,7 +5691,7 @@ int PYTHON::classDirectorMethod(Node *n, Node *parent, String *super) { } else { if (modernargs) { Append(w->code, "swig::SwigVar_PyObject args = PyTuple_New(0);\n"); - Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_Call(method, (PyObject*) args, NULL);\n", Swig_cresult_name()); + Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_Call(method, (PyObject *) args, NULL);\n", Swig_cresult_name()); } else { Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, NULL, NULL);\n", Swig_cresult_name()); } diff --git a/Source/Modules/r.cxx b/Source/Modules/r.cxx index 0e8e23063..bd1b9107e 100644 --- a/Source/Modules/r.cxx +++ b/Source/Modules/r.cxx @@ -793,9 +793,7 @@ int R::top(Node *n) { Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGR\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGR\n#define SWIGR\n#endif\n\n"); Swig_banner_target_lang(s_init, "#"); @@ -1066,7 +1064,7 @@ int R::OutputMemberReferenceMethod(String *className, int isSet, if (!isSet && varaccessor > 0) { Printf(f->code, "%svaccessors = c(", tab8); - int vcount = 0; + int first = 1; for(j = 0; j < numMems; j+=3) { String *item = Getitem(el, j); String *dup = Getitem(el, j + 1); @@ -1074,8 +1072,8 @@ int R::OutputMemberReferenceMethod(String *className, int isSet, ptr = &ptr[Len(dup) - 3]; if (!strcmp(ptr, "get")) { - vcount++; - Printf(f->code, "'%s'%s", item, vcount < varaccessor ? ", " : ""); + Printf(f->code, "%s'%s'", first ? "" : ", ", item); + first = 0; } } Printf(f->code, ");\n"); @@ -1181,6 +1179,9 @@ int R::OutputArrayMethod(String *className, List *el, File *out) { tdname is the typedef of the enumeration, i.e. giving its name. *************************************************************/ int R::enumDeclaration(Node *n) { + if (getCurrentClass() && (cplus_mode != PUBLIC)) + return SWIG_NOWRAP; + String *name = Getattr(n, "name"); String *tdname = Getattr(n, "tdname"); @@ -1481,11 +1482,12 @@ List * R::Swig_overload_rank(Node *n, Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[i].n), Getline(nodes[i].n), "using non-const method %s instead.\n", Swig_name_decl(nodes[i].n)); } else { - if (!Getattr(nodes[j].n, "overload:ignore")) + if (!Getattr(nodes[j].n, "overload:ignore")) { Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n), "Overloaded method %s ignored,\n", Swig_name_decl(nodes[j].n)); Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[i].n), Getline(nodes[i].n), "using %s instead.\n", Swig_name_decl(nodes[i].n)); + } } } nodes[j].error = 1; @@ -1498,11 +1500,12 @@ List * R::Swig_overload_rank(Node *n, Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[i].n), Getline(nodes[i].n), "using non-const method %s instead.\n", Swig_name_decl(nodes[i].n)); } else { - if (!Getattr(nodes[j].n, "overload:ignore")) + if (!Getattr(nodes[j].n, "overload:ignore")) { Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n), "Overloaded method %s ignored,\n", Swig_name_decl(nodes[j].n)); Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[i].n), Getline(nodes[i].n), "using %s instead.\n", Swig_name_decl(nodes[i].n)); + } } } nodes[j].error = 1; @@ -1520,11 +1523,12 @@ List * R::Swig_overload_rank(Node *n, Swig_warning(WARN_LANG_OVERLOAD_SHADOW, Getfile(nodes[i].n), Getline(nodes[i].n), "as it is shadowed by %s.\n", Swig_name_decl(nodes[i].n)); } else { - if (!Getattr(nodes[j].n, "overload:ignore")) + if (!Getattr(nodes[j].n, "overload:ignore")) { Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n), "Overloaded method %s ignored,\n", Swig_name_decl(nodes[j].n)); Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[i].n), Getline(nodes[i].n), "using %s instead.\n", Swig_name_decl(nodes[i].n)); + } } nodes[j].error = 1; } @@ -2093,6 +2097,13 @@ int R::functionWrapper(Node *n) { } } + /* See if there is any return cleanup code */ + if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); + Delete(tm); + } + Printv(f->code, UnProtectWrapupCode, NIL); /*If the user gave us something to convert the result in */ diff --git a/Source/Modules/ruby.cxx b/Source/Modules/ruby.cxx index 4b45b87ca..2a3128472 100644 --- a/Source/Modules/ruby.cxx +++ b/Source/Modules/ruby.cxx @@ -232,7 +232,7 @@ private: /* ------------------------------------------------------------ * docstring() - * Get the docstring text, stripping off {} if neccessary, + * Get the docstring text, stripping off {} if necessary, * and enclose in triple double quotes. If autodoc is also * set then it will build a combined docstring. * ------------------------------------------------------------ */ @@ -1011,6 +1011,8 @@ public: virtual int top(Node *n) { + String *mod_docstring = NULL; + /** * See if any Ruby module options have been specified as options * to the %module directive. @@ -1032,6 +1034,7 @@ public: multipleInheritance = true; director_multiple_inheritance = 1; } + mod_docstring = Getattr(options, "docstring"); } } @@ -1097,8 +1100,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGRUBY\n"); + Printf(f_runtime, "\n\n#ifndef SWIGRUBY\n#define SWIGRUBY\n#endif\n\n"); if (directorsEnabled()) { Printf(f_runtime, "#define SWIG_DIRECTORS\n"); @@ -1147,6 +1149,15 @@ public: Printf(f_header, "#define SWIG_init Init_%s\n", feature); Printf(f_header, "#define SWIG_name \"%s\"\n\n", module); + + if (mod_docstring) { + if (Len(mod_docstring)) { + Printf(f_header, "/*\n Document-module: %s\n\n%s\n*/\n", module, mod_docstring); + } + Delete(mod_docstring); + mod_docstring = NULL; + } + Printf(f_header, "static VALUE %s;\n", modvar); /* Start generating the initialization function */ @@ -1535,7 +1546,8 @@ public: /* Finish argument marshalling */ Printf(kwargs, " NULL }"); if (allow_kwargs) { - Printv(f->locals, tab4, "const char *kwnames[] = ", kwargs, ";\n", NIL); +// kwarg support not implemented +// Printv(f->locals, tab4, "const char *kwnames[] = ", kwargs, ";\n", NIL); } /* Trailing varargs */ @@ -1740,11 +1752,13 @@ public: /* Now write the wrapper function itself */ if (current == CONSTRUCTOR_ALLOCATE) { + Printv(f->def, "SWIGINTERN VALUE\n", NIL); Printf(f->def, "#ifdef HAVE_RB_DEFINE_ALLOC_FUNC\n"); - Printv(f->def, "SWIGINTERN VALUE\n", wname, "(VALUE self) {", NIL); + Printv(f->def, wname, "(VALUE self)\n", NIL); Printf(f->def, "#else\n"); - Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL); + Printv(f->def, wname, "(int argc, VALUE *argv, VALUE self)\n", NIL); Printf(f->def, "#endif\n"); + Printv(f->def, "{\n", NIL); } else if (current == CONSTRUCTOR_INITIALIZE) { Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL); if (!varargs) { @@ -1830,10 +1844,19 @@ public: Wrapper_add_local(f, "classname", classname); } if (action) { - Printf(action, "\nDATA_PTR(self) = %s;", Swig_cresult_name()); - if (GetFlag(pn, "feature:trackobjects")) { - Printf(action, "\nSWIG_RubyAddTracking(%s, self);", Swig_cresult_name()); + SwigType *smart = Swig_cparse_smartptr(pn); + String *result_name = NewStringf("%s%s", smart ? "smart" : "", Swig_cresult_name()); + if (smart) { + String *result_var = NewStringf("%s *%s = 0", SwigType_namestr(smart), result_name); + Wrapper_add_local(f, result_name, result_var); + Printf(action, "\n%s = new %s(%s);", result_name, SwigType_namestr(smart), Swig_cresult_name()); } + Printf(action, "\nDATA_PTR(self) = %s;", result_name); + if (GetFlag(pn, "feature:trackobjects")) { + Printf(action, "\nSWIG_RubyAddTracking(%s, self);", result_name); + } + Delete(result_name); + Delete(smart); } } @@ -1921,11 +1944,17 @@ public: /* Extra code needed for new and initialize methods */ if (current == CONSTRUCTOR_ALLOCATE) { + Node *pn = Swig_methodclass(n); + SwigType *smart = Swig_cparse_smartptr(pn); + if (smart) + SwigType_add_pointer(smart); + String *classtype = smart ? smart : t; need_result = 1; - Printf(f->code, "VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE%s);\n", Char(SwigType_manglestr(t))); + Printf(f->code, "VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE%s);\n", Char(SwigType_manglestr(classtype))); Printf(f->code, "#ifndef HAVE_RB_DEFINE_ALLOC_FUNC\n"); Printf(f->code, "rb_obj_call_init(vresult, argc, argv);\n"); Printf(f->code, "#endif\n"); + Delete(smart); } else if (current == CONSTRUCTOR_INITIALIZE) { need_result = 1; } @@ -2094,13 +2123,11 @@ public: // Generate prototype list, go to first node Node *sibl = n; - String* type = SwigType_str(Getattr(sibl,"type"),NULL); - while (Getattr(sibl, "sym:previousSibling")) sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up // Constructors will be treated specially - const bool isCtor = Cmp(Getattr(sibl,"feature:new"), "1") == 0; + const bool isCtor = (!Cmp(Getattr(sibl, "nodeType"), "constructor")); const bool isMethod = ( Cmp(Getattr(sibl, "ismember"), "1") == 0 && (!isCtor) ); @@ -2122,7 +2149,11 @@ public: String *protoTypes = NewString(""); do { Append( protoTypes, "\n\" "); - if ( !isCtor ) Printv( protoTypes, type, " ", NIL ); + if (!isCtor) { + SwigType *type = SwigType_str(Getattr(sibl, "type"), NULL); + Printv(protoTypes, type, " ", NIL); + Delete(type); + } Printv(protoTypes, methodName, NIL ); Parm* p = Getattr(sibl, "wrap:parms"); if (p && (current == MEMBER_FUNC || current == MEMBER_VAR || @@ -2143,7 +2174,6 @@ public: Append(f->code, "\nreturn Qnil;\n"); Delete(methodName); - Delete(type); Delete(protoTypes); Printv(f->code, "}\n", NIL); @@ -2424,19 +2454,23 @@ public: SwigType *btype = NewString(basename); SwigType_add_pointer(btype); SwigType_remember(btype); + SwigType *smart = Swig_cparse_smartptr(base.item); + if (smart) { + SwigType_add_pointer(smart); + SwigType_remember(smart); + } + String *bmangle = SwigType_manglestr(smart ? smart : btype); if (multipleInheritance) { - String *bmangle = SwigType_manglestr(btype); Insert(bmangle, 0, "((swig_class *) SWIGTYPE"); Append(bmangle, "->clientdata)->mImpl"); Printv(klass->init, "rb_include_module(", klass->mImpl, ", ", bmangle, ");\n", NIL); - Delete(bmangle); } else { - String *bmangle = SwigType_manglestr(btype); Insert(bmangle, 0, "((swig_class *) SWIGTYPE"); Append(bmangle, "->clientdata)->klass"); Replaceall(klass->init, "$super", bmangle); - Delete(bmangle); } + Delete(bmangle); + Delete(smart); Delete(btype); } base = Next(base); @@ -2453,7 +2487,7 @@ public: String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); Swig_warning(WARN_RUBY_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Ruby.\n", proxyclassname, baseclassname); + "Warning for %s, base %s ignored. Multiple inheritance is not supported in Ruby.\n", proxyclassname, baseclassname); base = Next(base); } } @@ -2537,9 +2571,15 @@ public: SwigType *tt = NewString(name); SwigType_add_pointer(tt); SwigType_remember(tt); - String *tm = SwigType_manglestr(tt); + SwigType *smart = Swig_cparse_smartptr(n); + if (smart) { + SwigType_add_pointer(smart); + SwigType_remember(smart); + } + String *tm = SwigType_manglestr(smart ? smart : tt); Printf(klass->init, "SWIG_TypeClientData(SWIGTYPE%s, (void *) &SwigClass%s);\n", tm, valid_name); Delete(tm); + Delete(smart); Delete(tt); Delete(valid_name); @@ -2718,7 +2758,9 @@ public: String *pname0 = Swig_cparm_name(0, 0); Printv(freefunc, "free_", klass->mname, NIL); - Printv(freebody, "SWIGINTERN void\n", freefunc, "(", klass->type, " *", pname0, ") {\n", tab4, NIL); + Printv(freebody, "SWIGINTERN void\n", freefunc, "(void *self) {\n", NIL); + Printv(freebody, tab4, klass->type, " *", pname0, " = (", klass->type, " *)self;\n", NIL); + Printv(freebody, tab4, NIL); /* Check to see if object tracking is activated for the class that owns this destructor. */ @@ -2971,6 +3013,7 @@ public: Printf(rescue->code, "if (%s == 0) ", depthCountName); Printv(rescue->code, Str(tm), "\n", NIL); Printv(rescue->code, "rb_exc_raise(error);\n", NIL); + Printv(rescue->code, "return Qnil;\n", NIL); Printv(rescue->code, "}", NIL); } @@ -3431,6 +3474,7 @@ public: *--------------------------------------------------------------------*/ bool kwargsSupport() const { + // kwargs support isn't actually implemented, but changing to return false may break something now as it turns on compactdefaultargs return true; } }; /* class RUBY */ diff --git a/Source/Modules/scilab.cxx b/Source/Modules/scilab.cxx index dd0645bd2..5997b5876 100644 --- a/Source/Modules/scilab.cxx +++ b/Source/Modules/scilab.cxx @@ -195,8 +195,7 @@ public: /* Output module initialization code */ Swig_banner(beginSection); - Printf(runtimeSection, "\n#define SWIGSCILAB\n"); - Printf(runtimeSection, "\n"); + Printf(runtimeSection, "\n\n#ifndef SWIGSCILAB\n#define SWIGSCILAB\n#endif\n\n"); // Gateway header source merged with wrapper source in nobuilder mode if (!generateBuilder) @@ -327,6 +326,7 @@ public: bool isLastOverloaded = isOverloaded && !Getattr(node, "sym:nextSibling"); if (!isOverloaded && !addSymbol(functionName, node)) { + DelWrapper(wrapper); return SWIG_ERROR; } @@ -412,7 +412,7 @@ public: emit_return_variable(node, functionReturnType, wrapper); /* Return the function value if necessary */ - String *functionReturnTypemap = Swig_typemap_lookup_out("out", node, "result", wrapper, functionActionCode); + String *functionReturnTypemap = Swig_typemap_lookup_out("out", node, Swig_cresult_name(), wrapper, functionActionCode); if (functionReturnTypemap) { // Result is actually the position of output value on stack if (Len(functionReturnTypemap) > 0) { @@ -471,6 +471,13 @@ public: } } + /* See if there is any return cleanup code */ + String *tm; + if ((tm = Swig_typemap_lookup("ret", node, Swig_cresult_name(), 0))) { + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(wrapper->code, "%s\n", tm); + Delete(tm); + } /* Close the function(ok) */ Printv(wrapper->code, "return SWIG_OK;\n", NIL); @@ -634,7 +641,10 @@ public: /* Add function to builder table */ addFunctionToScilab(scilabSetFunctionName, setFunctionName); + + DelWrapper(setFunctionWrapper); } + DelWrapper(getFunctionWrapper); return SWIG_OK; } @@ -661,7 +671,7 @@ public: if (isConstant || isEnum) { if (isEnum) { Setattr(node, "type", "double"); - constantValue = Getattr(node, "enumvalue"); + constantValue = Getattr(node, "value"); } constantTypemap = Swig_typemap_lookup("scilabconstcode", node, nodeName, 0); @@ -885,7 +895,7 @@ public: Printf(builderCode, "libs = [];\n"); // Flags from command line arguments - Printf(builderCode, "cflags = [];\n"); + Printf(builderCode, "cflags = \"\";\n"); for (int i = 0; i < Len(cflags); i++) { String *cflag = Getitem(cflags, i); Printf(builderCode, "cflags = cflags + \" %s\";\n", cflag); @@ -901,7 +911,7 @@ public: } } } else { - Printf(builderCode, "ldflags = [];\n"); + Printf(builderCode, "ldflags = \"\";\n"); } // External script to set flags @@ -1027,7 +1037,7 @@ public: Printf(gatewayHeaderV5, ",\n"); Printf(gatewayHeaderV5, " {(Myinterfun)sci_gateway, (GT)%s, (char *)\"%s\"}", wrapperFunctionName, scilabFunctionName); - Printf(gatewayHeaderV6, "if (wcscmp(pwstFuncName, L\"%s\") == 0) { addCFunction((wchar_t *)L\"%s\", &%s, (wchar_t *)MODULE_NAME); }\n", scilabFunctionName, scilabFunctionName, wrapperFunctionName); + Printf(gatewayHeaderV6, "if (wcscmp(pwstFuncName, L\"%s\") == 0) { addCStackFunction((wchar_t *)L\"%s\", &%s, (wchar_t *)MODULE_NAME); }\n", scilabFunctionName, scilabFunctionName, wrapperFunctionName); } /* ----------------------------------------------------------------------- diff --git a/Source/Modules/swigmain.cxx b/Source/Modules/swigmain.cxx index b7b5d66ee..397677fc5 100644 --- a/Source/Modules/swigmain.cxx +++ b/Source/Modules/swigmain.cxx @@ -36,6 +36,7 @@ extern "C" { Language *swig_java(void); Language *swig_php(void); Language *swig_php4(void); + Language *swig_php5(void); Language *swig_ocaml(void); Language *swig_octave(void); Language *swig_pike(void); @@ -83,9 +84,10 @@ static swig_module modules[] = { {"-octave", swig_octave, "Octave"}, {"-perl", swig_perl5, "Perl"}, {"-perl5", swig_perl5, 0}, - {"-php", swig_php, "PHP"}, + {"-php", swig_php5, 0}, {"-php4", swig_php4, 0}, - {"-php5", swig_php, 0}, + {"-php5", swig_php5, "PHP5"}, + {"-php7", swig_php, "PHP7"}, {"-pike", swig_pike, "Pike"}, {"-python", swig_python, "Python"}, {"-r", swig_r, "R (aka GNU S)"}, diff --git a/Source/Modules/swigmod.h b/Source/Modules/swigmod.h index 311fd514c..4bb2c29f8 100644 --- a/Source/Modules/swigmod.h +++ b/Source/Modules/swigmod.h @@ -18,12 +18,6 @@ #include "preprocessor.h" #include "swigwarn.h" -#if !defined(HAVE_BOOL) -typedef int bool; -#define true ((bool)1) -#define false ((bool)0) -#endif - #define NOT_VIRTUAL 0 #define PLAIN_VIRTUAL 1 #define PURE_VIRTUAL 2 @@ -220,8 +214,9 @@ public: /* Miscellaneous */ virtual int validIdentifier(String *s); /* valid identifier? */ virtual int addSymbol(const String *s, const Node *n, const_String_or_char_ptr scope = ""); /* Add symbol */ + virtual int addInterfaceSymbol(const String *interface_name, Node *n, const_String_or_char_ptr scope = ""); virtual void dumpSymbols(); - virtual Node *symbolLookup(String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */ + virtual Node *symbolLookup(const String *s, const_String_or_char_ptr scope = ""); /* Symbol lookup */ virtual Hash* symbolAddScope(const_String_or_char_ptr scope); virtual Hash* symbolScopeLookup(const_String_or_char_ptr scope); virtual Hash* symbolScopePseudoSymbolLookup(const_String_or_char_ptr scope); @@ -435,19 +430,24 @@ extern "C" { } /* Contracts */ - void Swig_contracts(Node *n); void Swig_contract_mode_set(int flag); int Swig_contract_mode_get(); /* Browser */ - void Swig_browser(Node *n, int); void Swig_default_allocators(Node *n); void Swig_process_types(Node *n); + +/* Nested classes */ void Swig_nested_process_classes(Node *n); void Swig_nested_name_unnamed_c_structs(Node *n); +/* Interface feature */ +void Swig_interface_feature_enable(); +void Swig_interface_propagate_methods(Node *n); + +/* Miscellaneous */ template class save_value { T _value; T& _value_ptr; diff --git a/Source/Modules/tcl8.cxx b/Source/Modules/tcl8.cxx index 2e32fc808..1227af79c 100644 --- a/Source/Modules/tcl8.cxx +++ b/Source/Modules/tcl8.cxx @@ -165,9 +165,7 @@ public: Swig_banner(f_begin); - Printf(f_runtime, "\n"); - Printf(f_runtime, "#define SWIGTCL\n"); - Printf(f_runtime, "\n"); + Printf(f_runtime, "\n\n#ifndef SWIGTCL\n#define SWIGTCL\n#endif\n\n"); /* Set the module name, namespace, and prefix */ @@ -968,7 +966,7 @@ public: Printf(f_wrappers, ",0"); } Printv(f_wrappers, ", swig_", mangled_classname, "_methods, swig_", mangled_classname, "_attributes, swig_", mangled_classname, "_bases,", - "swig_", mangled_classname, "_base_names, &swig_module };\n", NIL); + "swig_", mangled_classname, "_base_names, &swig_module, SWIG_TCL_HASHTABLE_INIT };\n", NIL); if (!itcl) { Printv(cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_", mangled_classname, diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index 3e323f910..bf8028c29 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -224,7 +224,7 @@ class TypePass:private Dispatcher { if (tname) Delete(tname); if (!bcls) { - if (!clsforward) { + if (!clsforward && !GetFlag(cls, "feature:ignore")) { if (ispublic && !Getmeta(bname, "already_warned")) { Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(bname), Getline(bname), "Nothing known about base class '%s'. Ignored.\n", SwigType_namestr(bname)); if (Strchr(bname, '<')) { @@ -254,41 +254,44 @@ class TypePass:private Dispatcher { Node *bclass = n; /* Getattr(n,"class"); */ Hash *scopes = Getattr(bclass, "typescope"); SwigType_inherit(clsname, bname, cast, 0); - String *smartptr = Getattr(first, "feature:smartptr"); - if (smartptr) { - SwigType *smart = 0; - SwigType *spt = Swig_cparse_type(smartptr); - if (spt) { - smart = SwigType_typedef_resolve_all(spt); - Delete(spt); - /* Record a (fake) inheritance relationship between smart pointer - and smart pointer to base class, so that smart pointer upcasts - are automatically generated. */ - SwigType *bsmart = Copy(smart); - SwigType *rclsname = SwigType_typedef_resolve_all(clsname); - SwigType *rbname = SwigType_typedef_resolve_all(bname); - Replaceall(bsmart, rclsname, rbname); - Delete(rclsname); - Delete(rbname); - String *smartnamestr = SwigType_namestr(smart); - String *bsmartnamestr = SwigType_namestr(bsmart); - /* construct casting code */ - String *convcode = NewStringf("\n *newmemory = SWIG_CAST_NEW_MEMORY;\n return (void *) new %s(*(%s *)$from);\n", bsmartnamestr, smartnamestr); - Delete(bsmartnamestr); - Delete(smartnamestr); - /* setup inheritance relationship between smart pointer templates */ - SwigType_inherit(smart, bsmart, 0, convcode); - if (!GetFlag(bclass, "feature:smartptr")) - Swig_warning(WARN_LANG_SMARTPTR_MISSING, Getfile(first), Getline(first), "Base class '%s' of '%s' is not similarly marked as a smart pointer.\n", SwigType_namestr(Getattr(bclass, "name")), SwigType_namestr(Getattr(first, "name"))); - Delete(convcode); - Delete(bsmart); + if (ispublic && !GetFlag(bclass, "feature:ignore")) { + String *smartptr = Getattr(first, "feature:smartptr"); + if (smartptr) { + SwigType *smart = Swig_cparse_smartptr(first); + if (smart) { + /* Record a (fake) inheritance relationship between smart pointer + and smart pointer to base class, so that smart pointer upcasts + are automatically generated. */ + SwigType *bsmart = Copy(smart); + SwigType *rclsname = SwigType_typedef_resolve_all(clsname); + SwigType *rbname = SwigType_typedef_resolve_all(bname); + int replace_count = Replaceall(bsmart, rclsname, rbname); + if (replace_count == 0) { + // If no replacement made, it will be because rclsname is fully resolved, but the + // type in the smartptr feature used a typedef or not fully resolved name. + String *firstname = Getattr(first, "name"); + Replaceall(bsmart, firstname, rbname); + } + Delete(rclsname); + Delete(rbname); + String *smartnamestr = SwigType_namestr(smart); + String *bsmartnamestr = SwigType_namestr(bsmart); + /* construct casting code */ + String *convcode = NewStringf("\n *newmemory = SWIG_CAST_NEW_MEMORY;\n return (void *) new %s(*(%s *)$from);\n", bsmartnamestr, smartnamestr); + Delete(bsmartnamestr); + Delete(smartnamestr); + /* setup inheritance relationship between smart pointer templates */ + SwigType_inherit(smart, bsmart, 0, convcode); + if (!GetFlag(bclass, "feature:smartptr")) + Swig_warning(WARN_LANG_SMARTPTR_MISSING, Getfile(first), Getline(first), "Base class '%s' of '%s' is not similarly marked as a smart pointer.\n", SwigType_namestr(Getattr(bclass, "name")), SwigType_namestr(Getattr(first, "name"))); + Delete(convcode); + Delete(bsmart); + } Delete(smart); } else { - Swig_error(Getfile(first), Getline(first), "Invalid type (%s) in 'smartptr' feature for class %s.\n", SwigType_namestr(smartptr), SwigType_namestr(clsname)); + if (GetFlag(bclass, "feature:smartptr")) + Swig_warning(WARN_LANG_SMARTPTR_MISSING, Getfile(first), Getline(first), "Derived class '%s' of '%s' is not similarly marked as a smart pointer.\n", SwigType_namestr(Getattr(first, "name")), SwigType_namestr(Getattr(bclass, "name"))); } - } else { - if (GetFlag(bclass, "feature:smartptr")) - Swig_warning(WARN_LANG_SMARTPTR_MISSING, Getfile(first), Getline(first), "Derived class '%s' of '%s' is not similarly marked as a smart pointer.\n", SwigType_namestr(Getattr(first, "name")), SwigType_namestr(Getattr(bclass, "name"))); } if (!importmode) { String *btype = Copy(bname); @@ -563,6 +566,10 @@ class TypePass:private Dispatcher { SwigType_typedef_class(rname); Delete(rname); /* SwigType_typedef_class(name); */ + } else if (Strcmp(ttype, "cdecl") == 0) { + String *rname = SwigType_typedef_resolve_all(name); + SwigType_typedef_class(rname); + Delete(rname); } return SWIG_OK; } diff --git a/Source/Modules/xml.cxx b/Source/Modules/xml.cxx index 45b7f7a89..5f090561a 100644 --- a/Source/Modules/xml.cxx +++ b/Source/Modules/xml.cxx @@ -81,9 +81,11 @@ public: virtual int top(Node *n) { if (out == 0) { String *outfile = Getattr(n, "outfile"); - Replaceall(outfile, ".cxx", ".xml"); - Replaceall(outfile, ".cpp", ".xml"); - Replaceall(outfile, ".c", ".xml"); + String *ext = Swig_file_extension(outfile); + // If there's an extension, ext will include the ".". + Delslice(outfile, Len(outfile) - Len(ext), DOH_END); + Delete(ext); + Append(outfile, ".xml"); out = NewFile(outfile, "w", SWIG_output_files()); if (!out) { FileErrorDisplay(outfile); @@ -142,8 +144,8 @@ public: Xml_print_kwargs(Getattr(obj, k)); } else if (Cmp(k, "parms") == 0 || Cmp(k, "pattern") == 0) { Xml_print_parmlist(Getattr(obj, k)); - } else if (Cmp(k, "catchlist") == 0) { - Xml_print_parmlist(Getattr(obj, k), "catchlist"); + } else if (Cmp(k, "catchlist") == 0 || Cmp(k, "templateparms") == 0) { + Xml_print_parmlist(Getattr(obj, k), Char(k)); } else { DOH *o; print_indent(0); diff --git a/Source/Swig/include.c b/Source/Swig/include.c index 08226a25c..94df338f0 100644 --- a/Source/Swig/include.c +++ b/Source/Swig/include.c @@ -291,6 +291,7 @@ int Swig_insert_file(const_String_or_char_ptr filename, File *outfile) { while ((nbytes = Read(f, buffer, 4096)) > 0) { Write(outfile, buffer, nbytes); } + fclose(f); return 0; } diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index 11c14d900..e3710beac 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -309,6 +309,7 @@ int Swig_storage_isstatic(Node *n) { * Swig_string_escape() * * Takes a string object and produces a string with escape codes added to it. + * Octal escaping is used. * ----------------------------------------------------------------------------- */ String *Swig_string_escape(String *s) { @@ -342,6 +343,43 @@ String *Swig_string_escape(String *s) { return ns; } +/* ----------------------------------------------------------------------------- + * Swig_string_hexescape() + * + * Takes a string object and produces a string with escape codes added to it. + * Hex escaping is used. + * ----------------------------------------------------------------------------- */ + +String *Swig_string_hexescape(String *s) { + String *ns; + int c; + ns = NewStringEmpty(); + + while ((c = Getc(s)) != EOF) { + if (c == '\n') { + Printf(ns, "\\n"); + } else if (c == '\r') { + Printf(ns, "\\r"); + } else if (c == '\t') { + Printf(ns, "\\t"); + } else if (c == '\\') { + Printf(ns, "\\\\"); + } else if (c == '\'') { + Printf(ns, "\\'"); + } else if (c == '\"') { + Printf(ns, "\\\""); + } else if (c == ' ') { + Putc(c, ns); + } else if (!isgraph(c)) { + if (c < 0) + c += UCHAR_MAX + 1; + Printf(ns, "\\x%X", c); + } else { + Putc(c, ns); + } + } + return ns; +} /* ----------------------------------------------------------------------------- * Swig_string_upper() @@ -1147,6 +1185,39 @@ String *Swig_string_strip(String *s) { return ns; } +/* ----------------------------------------------------------------------------- + * Swig_string_rstrip() + * + * Strip given suffix from identifiers + * + * Printf(stderr,"%(rstrip:[Cls])s","HelloCls") -> Hello + * ----------------------------------------------------------------------------- */ + +String *Swig_string_rstrip(String *s) { + String *ns; + int len = Len(s); + if (!len) { + ns = NewString(s); + } else { + const char *cs = Char(s); + const char *ce = Strchr(cs, ']'); + if (*cs != '[' || !ce) { + ns = NewString(s); + } else { + String *fmt = NewStringf("%%.%ds", ce-cs-1); + String *suffix = NewStringf(fmt, cs+1); + int suffix_len = Len(suffix); + if (0 == Strncmp(cs+len-suffix_len, suffix, suffix_len)) { + int copy_len = len-suffix_len-(ce+1-cs); + ns = NewStringWithSize(ce+1, copy_len); + } else { + ns = NewString(ce+1); + } + } + } + return ns; +} + /* ----------------------------------------------------------------------------- * Swig_offset_string() * @@ -1328,7 +1399,7 @@ String *replace_captures(int num_captures, const char *input, String *subst, int * * Executes a regular expression substitution. For example: * - * Printf(stderr,"gsl%(regex:/GSL_.*_/\\1/)s","GSL_Hello_") -> gslHello + * Printf(stderr,"gsl%(regex:/GSL_(.*)_/\\1/)s", "GSL_Hello_") -> gslHello * ----------------------------------------------------------------------------- */ String *Swig_string_regex(String *s) { const int pcre_options = 0; @@ -1403,6 +1474,7 @@ int Swig_is_generated_overload(Node *n) { void Swig_init() { /* Set some useful string encoding methods */ DohEncoding("escape", Swig_string_escape); + DohEncoding("hexescape", Swig_string_hexescape); DohEncoding("upper", Swig_string_upper); DohEncoding("lower", Swig_string_lower); DohEncoding("title", Swig_string_title); @@ -1414,6 +1486,7 @@ void Swig_init() { DohEncoding("command", Swig_string_command); DohEncoding("schemify", Swig_string_schemify); DohEncoding("strip", Swig_string_strip); + DohEncoding("rstrip", Swig_string_rstrip); DohEncoding("regex", Swig_string_regex); /* aliases for the case encoders */ diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 2d1effa18..ea059aa28 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -50,6 +50,13 @@ void Swig_name_unregister(const_String_or_char_ptr method) { } } +/* Return naming format for the specified method or the default format if none was explicitly registered */ +static String* get_naming_format_for(const char *method, const char *def_format) { + String* f = naming_hash ? Getattr(naming_hash, method) : NULL; + + return f ? Copy(f) : NewString(def_format); +} + static int name_mangle(String *r) { char *c; int special; @@ -172,18 +179,8 @@ String *Swig_name_mangle(const_String_or_char_ptr s) { * ----------------------------------------------------------------------------- */ String *Swig_name_wrapper(const_String_or_char_ptr fname) { - String *r; - String *f; + String *r = get_naming_format_for("wrapper", "_wrap_%f"); - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "wrapper"); - if (!f) { - Append(r, "_wrap_%f"); - } else { - Append(r, f); - } Replace(r, "%f", fname, DOH_REPLACE_ANY); name_mangle(r); return r; @@ -198,20 +195,11 @@ String *Swig_name_wrapper(const_String_or_char_ptr fname) { String *Swig_name_member(const_String_or_char_ptr nspace, const_String_or_char_ptr classname, const_String_or_char_ptr membername) { String *r; - String *f; String *rclassname; char *cname; rclassname = SwigType_namestr(classname); - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "member"); - if (!f) { - Append(r, "%n%c_%m"); - } else { - Append(r, f); - } + r = get_naming_format_for("member", "%n%c_%m"); cname = Char(rclassname); if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) { cname = strchr(cname, ' ') + 1; @@ -231,23 +219,12 @@ String *Swig_name_member(const_String_or_char_ptr nspace, const_String_or_char_p * ----------------------------------------------------------------------------- */ String *Swig_name_get(const_String_or_char_ptr nspace, const_String_or_char_ptr vname) { - String *r; - String *f; + String *r = get_naming_format_for("get", "%n%v_get"); #ifdef SWIG_DEBUG Printf(stdout, "Swig_name_get: '%s'\n", vname); #endif - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "get"); - if (!f) { - Append(r, "%n%v_get"); - } else { - Append(r, f); - } - replace_nspace(r, nspace); Replace(r, "%v", vname, DOH_REPLACE_ANY); /* name_mangle(r); */ @@ -261,18 +238,7 @@ String *Swig_name_get(const_String_or_char_ptr nspace, const_String_or_char_ptr * ----------------------------------------------------------------------------- */ String *Swig_name_set(const_String_or_char_ptr nspace, const_String_or_char_ptr vname) { - String *r; - String *f; - - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "set"); - if (!f) { - Append(r, "%n%v_set"); - } else { - Append(r, f); - } + String *r = get_naming_format_for("set", "%n%v_set"); replace_nspace(r, nspace); Replace(r, "%v", vname, DOH_REPLACE_ANY); @@ -280,6 +246,26 @@ String *Swig_name_set(const_String_or_char_ptr nspace, const_String_or_char_ptr return r; } +/* Common implementation of all Swig_name_() functions below. */ +static String *make_full_name_for(const char *method, const char *def_format, const_String_or_char_ptr nspace, const_String_or_char_ptr classname) { + String *r; + String *rclassname; + char *cname; + + rclassname = SwigType_namestr(classname); + r = get_naming_format_for(method, def_format); + + cname = Char(rclassname); + if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) { + cname = strchr(cname, ' ') + 1; + } + + replace_nspace(r, nspace); + Replace(r, "%c", cname, DOH_REPLACE_ANY); + Delete(rclassname); + return r; +} + /* ----------------------------------------------------------------------------- * Swig_name_construct() * @@ -287,31 +273,7 @@ String *Swig_name_set(const_String_or_char_ptr nspace, const_String_or_char_ptr * ----------------------------------------------------------------------------- */ String *Swig_name_construct(const_String_or_char_ptr nspace, const_String_or_char_ptr classname) { - String *r; - String *f; - String *rclassname; - char *cname; - - rclassname = SwigType_namestr(classname); - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "construct"); - if (!f) { - Append(r, "new_%n%c"); - } else { - Append(r, f); - } - - cname = Char(rclassname); - if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) { - cname = strchr(cname, ' ') + 1; - } - - replace_nspace(r, nspace); - Replace(r, "%c", cname, DOH_REPLACE_ANY); - Delete(rclassname); - return r; + return make_full_name_for("construct", "new_%n%c", nspace, classname); } @@ -322,31 +284,7 @@ String *Swig_name_construct(const_String_or_char_ptr nspace, const_String_or_cha * ----------------------------------------------------------------------------- */ String *Swig_name_copyconstructor(const_String_or_char_ptr nspace, const_String_or_char_ptr classname) { - String *r; - String *f; - String *rclassname; - char *cname; - - rclassname = SwigType_namestr(classname); - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "copy"); - if (!f) { - Append(r, "copy_%n%c"); - } else { - Append(r, f); - } - - cname = Char(rclassname); - if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) { - cname = strchr(cname, ' ') + 1; - } - - replace_nspace(r, nspace); - Replace(r, "%c", cname, DOH_REPLACE_ANY); - Delete(rclassname); - return r; + return make_full_name_for("copy", "copy_%n%c", nspace, classname); } /* ----------------------------------------------------------------------------- @@ -356,30 +294,7 @@ String *Swig_name_copyconstructor(const_String_or_char_ptr nspace, const_String_ * ----------------------------------------------------------------------------- */ String *Swig_name_destroy(const_String_or_char_ptr nspace, const_String_or_char_ptr classname) { - String *r; - String *f; - String *rclassname; - char *cname; - rclassname = SwigType_namestr(classname); - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "destroy"); - if (!f) { - Append(r, "delete_%n%c"); - } else { - Append(r, f); - } - - cname = Char(rclassname); - if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) { - cname = strchr(cname, ' ') + 1; - } - - replace_nspace(r, nspace); - Replace(r, "%c", cname, DOH_REPLACE_ANY); - Delete(rclassname); - return r; + return make_full_name_for("destroy", "delete_%n%c", nspace, classname); } @@ -390,30 +305,7 @@ String *Swig_name_destroy(const_String_or_char_ptr nspace, const_String_or_char_ * ----------------------------------------------------------------------------- */ String *Swig_name_disown(const_String_or_char_ptr nspace, const_String_or_char_ptr classname) { - String *r; - String *f; - String *rclassname; - char *cname; - rclassname = SwigType_namestr(classname); - r = NewStringEmpty(); - if (!naming_hash) - naming_hash = NewHash(); - f = Getattr(naming_hash, "disown"); - if (!f) { - Append(r, "disown_%n%c"); - } else { - Append(r, f); - } - - cname = Char(rclassname); - if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) { - cname = strchr(cname, ' ') + 1; - } - - replace_nspace(r, nspace); - Replace(r, "%c", cname, DOH_REPLACE_ANY); - Delete(rclassname); - return r; + return make_full_name_for("disown", "disown_%n%c", nspace, classname); } @@ -466,8 +358,7 @@ static DOH *get_object(Hash *n, String *decl) { return rn; } -static -DOH *name_object_get(Hash *namehash, String *tname, SwigType *decl, SwigType *ncdecl) { +static DOH *name_object_get(Hash *namehash, String *tname, SwigType *decl, SwigType *ncdecl) { DOH *rn = 0; Hash *n = Getattr(namehash, tname); if (n) { @@ -513,7 +404,17 @@ DOH *Swig_name_object_get(Hash *namehash, String *prefix, String *name, SwigType } Delete(cls); } - /* A template-based class lookup, check name first */ + /* Lookup a name within a templated-based class */ + if (!rn) { + String *t_name = SwigType_istemplate_templateprefix(prefix); + if (t_name) { + Clear(tname); + Printf(tname, "%s::%s", t_name, name); + rn = name_object_get(namehash, tname, decl, ncdecl); + Delete(t_name); + } + } + /* Lookup a template-based name within a class */ if (!rn) { String *t_name = SwigType_istemplate_templateprefix(name); if (t_name) @@ -646,8 +547,7 @@ static void merge_features(Hash *features, Node *n) { * the declaration, decl. * ----------------------------------------------------------------------------- */ -static -void features_get(Hash *features, const String *tname, SwigType *decl, SwigType *ncdecl, Node *node) { +static void features_get(Hash *features, const String *tname, SwigType *decl, SwigType *ncdecl, Node *node) { Node *n = Getattr(features, tname); #ifdef SWIG_DEBUG Printf(stdout, " features_get: %s\n", tname); @@ -844,41 +744,41 @@ void Swig_feature_set(Hash *features, const_String_or_char_ptr name, SwigType *d * ----------------------------------------------------------------------------- */ static Hash *namewarn_hash = 0; -Hash *Swig_name_namewarn_hash() { +static Hash *name_namewarn_hash() { if (!namewarn_hash) namewarn_hash = NewHash(); return namewarn_hash; } static Hash *rename_hash = 0; -Hash *Swig_name_rename_hash() { +static Hash *name_rename_hash() { if (!rename_hash) rename_hash = NewHash(); return rename_hash; } static List *namewarn_list = 0; -List *Swig_name_namewarn_list() { +static List *name_namewarn_list() { if (!namewarn_list) namewarn_list = NewList(); return namewarn_list; } static List *rename_list = 0; -List *Swig_name_rename_list() { +static List *name_rename_list() { if (!rename_list) rename_list = NewList(); return rename_list; } /* ----------------------------------------------------------------------------- - * int Swig_need_name_warning(Node *n) + * int need_name_warning(Node *n) * * Detects if a node needs name warnings * * ----------------------------------------------------------------------------- */ -int Swig_need_name_warning(Node *n) { +static int need_name_warning(Node *n) { int need = 1; /* We don't use name warnings for: @@ -1061,13 +961,13 @@ int Swig_need_protected(Node *n) { } /* ----------------------------------------------------------------------------- - * void Swig_name_nameobj_add() + * void name_nameobj_add() * * Add nameobj (rename/namewarn) * * ----------------------------------------------------------------------------- */ -static List *Swig_make_attrlist(const char *ckey) { +static List *make_attrlist(const char *ckey) { List *list = NewList(); const char *cattr = strchr(ckey, '$'); if (cattr) { @@ -1089,7 +989,7 @@ static List *Swig_make_attrlist(const char *ckey) { return list; } -static void Swig_name_object_attach_keys(const char *keys[], Hash *nameobj) { +static void name_object_attach_keys(const char *keys[], Hash *nameobj) { Node *kw = nextSibling(nameobj); List *matchlist = 0; while (kw) { @@ -1105,7 +1005,7 @@ static void Swig_name_object_attach_keys(const char *keys[], Hash *nameobj) { || (isregexmatch = (strncmp(ckey, "regexmatch", 10) == 0)) || (isnotmatch = isregexmatch = (strncmp(ckey, "notregexmatch", 13) == 0))) { Hash *mi = NewHash(); - List *attrlist = Swig_make_attrlist(ckey); + List *attrlist = make_attrlist(ckey); if (!matchlist) matchlist = NewList(); Setattr(mi, "value", Getattr(kw, "value")); @@ -1135,7 +1035,7 @@ static void Swig_name_object_attach_keys(const char *keys[], Hash *nameobj) { } } -void Swig_name_nameobj_add(Hash *name_hash, List *name_list, String *prefix, String *name, SwigType *decl, Hash *nameobj) { +static void name_nameobj_add(Hash *name_hash, List *name_list, String *prefix, String *name, SwigType *decl, Hash *nameobj) { String *nname = 0; if (name && Len(name)) { String *target_fmt = Getattr(nameobj, "targetfmt"); @@ -1164,13 +1064,13 @@ void Swig_name_nameobj_add(Hash *name_hash, List *name_list, String *prefix, Str } /* ----------------------------------------------------------------------------- - * int Swig_name_match_nameobj() + * int name_match_nameobj() * * Apply and check the nameobj's math list to the node * * ----------------------------------------------------------------------------- */ -static DOH *Swig_get_lattr(Node *n, List *lattr) { +static DOH *get_lattr(Node *n, List *lattr) { DOH *res = 0; int ilen = Len(lattr); int i; @@ -1192,7 +1092,7 @@ static DOH *Swig_get_lattr(Node *n, List *lattr) { #ifdef HAVE_PCRE #include -int Swig_name_regexmatch_value(Node *n, String *pattern, String *s) { +static int name_regexmatch_value(Node *n, String *pattern, String *s) { pcre *compiled_pat; const char *err; int errpos; @@ -1224,7 +1124,7 @@ int Swig_name_regexmatch_value(Node *n, String *pattern, String *s) { #else /* !HAVE_PCRE */ -int Swig_name_regexmatch_value(Node *n, String *pattern, String *s) { +static int name_regexmatch_value(Node *n, String *pattern, String *s) { (void)pattern; (void)s; Swig_error("SWIG", Getline(n), @@ -1234,7 +1134,7 @@ int Swig_name_regexmatch_value(Node *n, String *pattern, String *s) { #endif /* HAVE_PCRE/!HAVE_PCRE */ -int Swig_name_match_value(String *mvalue, String *value) { +static int name_match_value(String *mvalue, String *value) { #if defined(SWIG_USE_SIMPLE_MATCHOR) int match = 0; char *cvalue = Char(value); @@ -1260,12 +1160,11 @@ int Swig_name_match_value(String *mvalue, String *value) { #endif } - -int Swig_name_match_nameobj(Hash *rn, Node *n) { +static int name_match_nameobj(Hash *rn, Node *n) { int match = 1; List *matchlist = Getattr(rn, "matchlist"); #ifdef SWIG_DEBUG - Printf(stdout, "Swig_name_match_nameobj: %s\n", Getattr(n, "name")); + Printf(stdout, "name_match_nameobj: %s\n", Getattr(n, "name")); #endif if (matchlist) { int ilen = Len(matchlist); @@ -1273,14 +1172,14 @@ int Swig_name_match_nameobj(Hash *rn, Node *n) { for (i = 0; match && (i < ilen); ++i) { Node *mi = Getitem(matchlist, i); List *lattr = Getattr(mi, "attrlist"); - String *nval = Swig_get_lattr(n, lattr); + String *nval = get_lattr(n, lattr); int notmatch = GetFlag(mi, "notmatch"); int regexmatch = GetFlag(mi, "regexmatch"); match = 0; if (nval) { String *kwval = Getattr(mi, "value"); - match = regexmatch ? Swig_name_regexmatch_value(n, kwval, nval) - : Swig_name_match_value(kwval, nval); + match = regexmatch ? name_regexmatch_value(n, kwval, nval) + : name_match_value(kwval, nval); #ifdef SWIG_DEBUG Printf(stdout, "val %s %s %d %d \n", nval, kwval, match, ilen); #endif @@ -1290,19 +1189,19 @@ int Swig_name_match_nameobj(Hash *rn, Node *n) { } } #ifdef SWIG_DEBUG - Printf(stdout, "Swig_name_match_nameobj: %d\n", match); + Printf(stdout, "name_match_nameobj: %d\n", match); #endif return match; } /* ----------------------------------------------------------------------------- - * Hash *Swig_name_nameobj_lget() + * Hash *name_nameobj_lget() * * Get a nameobj (rename/namewarn) from the list of filters * * ----------------------------------------------------------------------------- */ -Hash *Swig_name_nameobj_lget(List *namelist, Node *n, String *prefix, String *name, String *decl) { +static Hash *name_nameobj_lget(List *namelist, Node *n, String *prefix, String *name, String *decl) { Hash *res = 0; if (namelist) { int len = Len(namelist); @@ -1313,7 +1212,7 @@ Hash *Swig_name_nameobj_lget(List *namelist, Node *n, String *prefix, String *na String *rdecl = Getattr(rn, "decl"); if (rdecl && (!decl || !Equal(rdecl, decl))) { continue; - } else if (Swig_name_match_nameobj(rn, n)) { + } else if (name_match_nameobj(rn, n)) { String *tname = Getattr(rn, "targetname"); if (tname) { String *sfmt = Getattr(rn, "sourcefmt"); @@ -1336,8 +1235,8 @@ Hash *Swig_name_nameobj_lget(List *namelist, Node *n, String *prefix, String *na DohIncref(name); } } - match = regextarget ? Swig_name_regexmatch_value(n, tname, sname) - : Swig_name_match_value(tname, sname); + match = regextarget ? name_regexmatch_value(n, tname, sname) + : name_match_value(tname, sname); Delete(sname); } else { /* Applying the renaming rule may fail if it contains a %(regex)s expression that doesn't match the given name. */ @@ -1367,23 +1266,23 @@ Hash *Swig_name_nameobj_lget(List *namelist, Node *n, String *prefix, String *na void Swig_name_namewarn_add(String *prefix, String *name, SwigType *decl, Hash *namewrn) { const char *namewrn_keys[] = { "rename", "error", "fullname", "sourcefmt", "targetfmt", 0 }; - Swig_name_object_attach_keys(namewrn_keys, namewrn); - Swig_name_nameobj_add(Swig_name_namewarn_hash(), Swig_name_namewarn_list(), prefix, name, decl, namewrn); + name_object_attach_keys(namewrn_keys, namewrn); + name_nameobj_add(name_namewarn_hash(), name_namewarn_list(), prefix, name, decl, namewrn); } /* ----------------------------------------------------------------------------- - * Hash *Swig_name_namewarn_get() + * Hash *name_namewarn_get() * * Return the namewarn object, if there is one. * * ----------------------------------------------------------------------------- */ -Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl) { +static Hash *name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl) { if (!namewarn_hash && !namewarn_list) return 0; if (n) { /* Return in the obvious cases */ - if (!name || !Swig_need_name_warning(n)) { + if (!name || !need_name_warning(n)) { return 0; } else { String *access = Getattr(n, "access"); @@ -1395,11 +1294,11 @@ Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *de } if (name) { /* Check to see if the name is in the hash */ - Hash *wrn = Swig_name_object_get(Swig_name_namewarn_hash(), prefix, name, decl); - if (wrn && !Swig_name_match_nameobj(wrn, n)) + Hash *wrn = Swig_name_object_get(name_namewarn_hash(), prefix, name, decl); + if (wrn && !name_match_nameobj(wrn, n)) wrn = 0; if (!wrn) { - wrn = Swig_name_nameobj_lget(Swig_name_namewarn_list(), n, prefix, name, decl); + wrn = name_nameobj_lget(name_namewarn_list(), n, prefix, name, decl); } if (wrn && Getattr(wrn, "error")) { if (n) { @@ -1422,7 +1321,7 @@ Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *de * ----------------------------------------------------------------------------- */ String *Swig_name_warning(Node *n, String *prefix, String *name, SwigType *decl) { - Hash *wrn = Swig_name_namewarn_get(n, prefix, name, decl); + Hash *wrn = name_namewarn_get(n, prefix, name, decl); return (name && wrn) ? Getattr(wrn, "name") : 0; } @@ -1434,7 +1333,7 @@ String *Swig_name_warning(Node *n, String *prefix, String *name, SwigType *decl) * ----------------------------------------------------------------------------- */ static void single_rename_add(String *prefix, String *name, SwigType *decl, Hash *newname) { - Swig_name_nameobj_add(Swig_name_rename_hash(), Swig_name_rename_list(), prefix, name, decl, newname); + name_nameobj_add(name_rename_hash(), name_rename_list(), prefix, name, decl, newname); } /* Add a new rename. Works much like new_feature including default argument handling. */ @@ -1443,7 +1342,7 @@ void Swig_name_rename_add(String *prefix, String *name, SwigType *decl, Hash *ne ParmList *declparms = declaratorparms; const char *rename_keys[] = { "fullname", "sourcefmt", "targetfmt", "continue", "regextarget", 0 }; - Swig_name_object_attach_keys(rename_keys, newname); + name_object_attach_keys(rename_keys, newname); /* Add the name */ single_rename_add(prefix, name, decl, newname); @@ -1556,11 +1455,10 @@ String *Swig_name_make(Node *n, String *prefix, const_String_or_char_ptr cname, } } - if (rename_hash || rename_list || namewarn_hash || namewarn_list) { - Hash *rn = Swig_name_object_get(Swig_name_rename_hash(), prefix, name, decl); - if (!rn || !Swig_name_match_nameobj(rn, n)) { - rn = Swig_name_nameobj_lget(Swig_name_rename_list(), n, prefix, name, decl); + Hash *rn = Swig_name_object_get(name_rename_hash(), prefix, name, decl); + if (!rn || !name_match_nameobj(rn, n)) { + rn = name_nameobj_lget(name_rename_list(), n, prefix, name, decl); if (rn) { String *sfmt = Getattr(rn, "sourcefmt"); int fullname = GetFlag(rn, "fullname"); @@ -1596,7 +1494,7 @@ String *Swig_name_make(Node *n, String *prefix, const_String_or_char_ptr cname, } } nname = result ? result : name; - wrn = Swig_name_namewarn_get(n, prefix, nname, decl); + wrn = name_namewarn_get(n, prefix, nname, decl); if (wrn) { String *rename = Getattr(wrn, "rename"); if (rename) { @@ -1641,14 +1539,14 @@ String *Swig_name_make(Node *n, String *prefix, const_String_or_char_ptr cname, /* ----------------------------------------------------------------------------- * void Swig_name_inherit() * - * Inherit namewarn,rename, and feature objects + * Inherit namewarn, rename, and feature objects * * ----------------------------------------------------------------------------- */ void Swig_name_inherit(String *base, String *derived) { /* Printf(stdout,"base = '%s', derived = '%s'\n", base, derived); */ - Swig_name_object_inherit(Swig_name_rename_hash(), base, derived); - Swig_name_object_inherit(Swig_name_namewarn_hash(), base, derived); + Swig_name_object_inherit(name_rename_hash(), base, derived); + Swig_name_object_inherit(name_namewarn_hash(), base, derived); Swig_name_object_inherit(Swig_cparse_features(), base, derived); } diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index ea30dceba..5c5fbe8e9 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -283,13 +283,11 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern void Swig_naming_init(void); extern void Swig_name_namewarn_add(String *prefix, String *name, SwigType *decl, Hash *namewrn); - extern Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl); extern void Swig_name_rename_add(String *prefix, String *name, SwigType *decl, Hash *namewrn, ParmList *declaratorparms); extern void Swig_name_inherit(String *base, String *derived); extern List *Swig_make_inherit_list(String *clsname, List *names, String *Namespaceprefix); extern void Swig_inherit_base_symbols(List *bases); extern int Swig_need_protected(Node *n); - extern int Swig_need_name_warning(Node *n); extern int Swig_need_redefined_warn(Node *a, Node *b, int InClass); extern String *Swig_name_make(Node *n, String *prefix, const_String_or_char_ptr cname, SwigType *decl, String *oldname); @@ -411,8 +409,6 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern String *Swig_typemap_lookup(const_String_or_char_ptr tmap_method, Node *n, const_String_or_char_ptr lname, Wrapper *f); extern String *Swig_typemap_lookup_out(const_String_or_char_ptr tmap_method, Node *n, const_String_or_char_ptr lname, Wrapper *f, String *actioncode); - extern void Swig_typemap_new_scope(void); - extern Hash *Swig_typemap_pop_scope(void); extern void Swig_typemap_attach_parms(const_String_or_char_ptr tmap_method, ParmList *parms, Wrapper *f); diff --git a/Source/Swig/tree.c b/Source/Swig/tree.c index d817f1a85..78c04dc90 100644 --- a/Source/Swig/tree.c +++ b/Source/Swig/tree.c @@ -68,7 +68,7 @@ void Swig_print_node(Node *obj) { Node *cobj; print_indent(0); - Printf(stdout, "+++ %s ----------------------------------------\n", nodeType(obj)); + Printf(stdout, "+++ %s - %p ----------------------------------------\n", nodeType(obj), obj); ki = First(obj); while (ki.key) { String *k = ki.key; diff --git a/Source/Swig/typemap.c b/Source/Swig/typemap.c index 23b1e80e9..ab2a8c0df 100644 --- a/Source/Swig/typemap.c +++ b/Source/Swig/typemap.c @@ -59,13 +59,9 @@ static void replace_embedded_typemap(String *s, ParmList *parm_sublist, Wrapper * * ----------------------------------------------------------------------------- */ -#define MAX_SCOPE 32 +static Hash *typemaps; - -static Hash *typemaps[MAX_SCOPE]; -static int tm_scope = 0; - -static Hash *get_typemap(int tm_scope, const SwigType *type) { +static Hash *get_typemap(const SwigType *type) { Hash *tm = 0; SwigType *dtype = 0; SwigType *hashtype; @@ -79,7 +75,7 @@ static Hash *get_typemap(int tm_scope, const SwigType *type) { /* remove unary scope operator (::) prefix indicating global scope for looking up in the hashmap */ hashtype = SwigType_remove_global_scope_prefix(type); - tm = Getattr(typemaps[tm_scope], hashtype); + tm = Getattr(typemaps, hashtype); Delete(dtype); Delete(hashtype); @@ -87,7 +83,7 @@ static Hash *get_typemap(int tm_scope, const SwigType *type) { return tm; } -static void set_typemap(int tm_scope, const SwigType *type, Hash **tmhash) { +static void set_typemap(const SwigType *type, Hash **tmhash) { SwigType *hashtype = 0; Hash *new_tm = 0; assert(*tmhash == 0); @@ -96,7 +92,7 @@ static void set_typemap(int tm_scope, const SwigType *type, Hash **tmhash) { String *ty = Swig_symbol_template_deftype(rty, 0); String *tyq = Swig_symbol_type_qualify(ty, 0); hashtype = SwigType_remove_global_scope_prefix(tyq); - *tmhash = Getattr(typemaps[tm_scope], hashtype); + *tmhash = Getattr(typemaps, hashtype); Delete(rty); Delete(tyq); Delete(ty); @@ -111,7 +107,7 @@ static void set_typemap(int tm_scope, const SwigType *type, Hash **tmhash) { } /* note that the unary scope operator (::) prefix indicating global scope has been removed from the type */ - Setattr(typemaps[tm_scope], hashtype, *tmhash); + Setattr(typemaps, hashtype, *tmhash); Delete(hashtype); Delete(new_tm); @@ -125,12 +121,7 @@ static void set_typemap(int tm_scope, const SwigType *type, Hash **tmhash) { * ----------------------------------------------------------------------------- */ void Swig_typemap_init() { - int i; - for (i = 0; i < MAX_SCOPE; i++) { - typemaps[i] = 0; - } - typemaps[0] = NewHash(); - tm_scope = 0; + typemaps = NewHash(); } static String *typemap_method_name(const_String_or_char_ptr tmap_method) { @@ -160,32 +151,6 @@ static String *typemap_method_name(const_String_or_char_ptr tmap_method) { return s; } -#if 0 -/* ----------------------------------------------------------------------------- - * Swig_typemap_new_scope() - * - * Create a new typemap scope - * ----------------------------------------------------------------------------- */ - -void Swig_typemap_new_scope() { - tm_scope++; - typemaps[tm_scope] = NewHash(); -} - -/* ----------------------------------------------------------------------------- - * Swig_typemap_pop_scope() - * - * Pop the last typemap scope off - * ----------------------------------------------------------------------------- */ - -Hash *Swig_typemap_pop_scope() { - if (tm_scope > 0) { - return typemaps[tm_scope--]; - } - return 0; -} -#endif - /* ----------------------------------------------------------------------------- * typemap_register() * @@ -216,9 +181,9 @@ static void typemap_register(const_String_or_char_ptr tmap_method, ParmList *par pname = Getattr(parms, "name"); /* See if this type has been seen before */ - tm = get_typemap(tm_scope, type); + tm = get_typemap(type); if (!tm) { - set_typemap(tm_scope, type, &tm); + set_typemap(type, &tm); } if (pname) { /* See if parameter has been seen before */ @@ -311,15 +276,12 @@ void Swig_typemap_register(const_String_or_char_ptr tmap_method, ParmList *parms /* ----------------------------------------------------------------------------- * typemap_get() * - * Retrieve typemap information from current scope. + * Retrieve typemap information. * ----------------------------------------------------------------------------- */ -static Hash *typemap_get(SwigType *type, const_String_or_char_ptr name, int scope) { +static Hash *typemap_get(SwigType *type, const_String_or_char_ptr name) { Hash *tm, *tm1; - /* See if this type has been seen before */ - if ((scope < 0) || (scope > tm_scope)) - return 0; - tm = get_typemap(scope, type); + tm = get_typemap(type); if (!tm) { return 0; } @@ -342,51 +304,48 @@ int Swig_typemap_copy(const_String_or_char_ptr tmap_method, ParmList *srcparms, Parm *p; String *pname; SwigType *ptype; - int ts = tm_scope; String *tm_methods, *multi_tmap_method; if (ParmList_len(parms) != ParmList_len(srcparms)) return -1; tm_method = typemap_method_name(tmap_method); - while (ts >= 0) { - p = srcparms; - tm_methods = NewString(tm_method); - while (p) { - ptype = Getattr(p, "type"); - pname = Getattr(p, "name"); + p = srcparms; + tm_methods = NewString(tm_method); + while (p) { + ptype = Getattr(p, "type"); + pname = Getattr(p, "name"); - /* Lookup the type */ - tm = typemap_get(ptype, pname, ts); - if (!tm) - break; + /* Lookup the type */ + tm = typemap_get(ptype, pname); + if (!tm) + break; - tm = Getattr(tm, tm_methods); - if (!tm) - break; + tm = Getattr(tm, tm_methods); + if (!tm) + break; - /* Got a match. Look for next typemap */ - multi_tmap_method = NewStringf("%s-%s+%s:", tm_methods, ptype, pname); - Delete(tm_methods); - tm_methods = multi_tmap_method; - p = nextSibling(p); - } + /* Got a match. Look for next typemap */ + multi_tmap_method = NewStringf("%s-%s+%s:", tm_methods, ptype, pname); Delete(tm_methods); - - if (!p && tm) { - /* Got some kind of match */ - String *parms_str = ParmList_str_multibrackets(parms); - String *srcparms_str = ParmList_str_multibrackets(srcparms); - String *source_directive = NewStringf("typemap(%s) %s = %s", tmap_method, parms_str, srcparms_str); - - typemap_register(tmap_method, parms, Getattr(tm, "code"), Getattr(tm, "locals"), Getattr(tm, "kwargs"), source_directive); - - Delete(source_directive); - Delete(srcparms_str); - Delete(parms_str); - return 0; - } - ts--; + tm_methods = multi_tmap_method; + p = nextSibling(p); } + Delete(tm_methods); + + if (!p && tm) { + /* Got some kind of match */ + String *parms_str = ParmList_str_multibrackets(parms); + String *srcparms_str = ParmList_str_multibrackets(srcparms); + String *source_directive = NewStringf("typemap(%s) %s = %s", tmap_method, parms_str, srcparms_str); + + typemap_register(tmap_method, parms, Getattr(tm, "code"), Getattr(tm, "locals"), Getattr(tm, "kwargs"), source_directive); + + Delete(source_directive); + Delete(srcparms_str); + Delete(parms_str); + return 0; + } + /* Not found */ return -1; @@ -411,7 +370,7 @@ void Swig_typemap_clear(const_String_or_char_ptr tmap_method, ParmList *parms) { while (p) { type = Getattr(p, "type"); name = Getattr(p, "name"); - tm = typemap_get(type, name, tm_scope); + tm = typemap_get(type, name); if (!tm) return; p = nextSibling(p); @@ -452,7 +411,6 @@ int Swig_typemap_apply(ParmList *src, ParmList *dest) { String *ssig, *dsig; Parm *p, *np, *lastp, *dp, *lastdp = 0; int narg = 0; - int ts = tm_scope; SwigType *type = 0, *name; Hash *tm, *sm; int match = 0; @@ -480,9 +438,9 @@ int Swig_typemap_apply(ParmList *src, ParmList *dest) { /* make sure a typemap node exists for the last destination node */ type = Getattr(lastdp, "type"); - tm = get_typemap(tm_scope, type); + tm = get_typemap(type); if (!tm) { - set_typemap(tm_scope, type, &tm); + set_typemap(type, &tm); } name = Getattr(lastdp, "name"); if (name) { @@ -501,69 +459,65 @@ int Swig_typemap_apply(ParmList *src, ParmList *dest) { type = Getattr(lastp, "type"); name = Getattr(lastp, "name"); - while (ts >= 0) { + /* See if there is a matching typemap in this scope */ + sm = typemap_get(type, name); - /* See if there is a matching typemap in this scope */ - sm = typemap_get(type, name, ts); + /* if there is not matching, look for a typemap in the + original typedef, if any, like in: - /* if there is not matching, look for a typemap in the - original typedef, if any, like in: - - typedef unsigned long size_t; - ... - %apply(size_t) {my_size}; ==> %apply(unsigned long) {my_size}; - */ - if (!sm) { - SwigType *ntype = SwigType_typedef_resolve(type); - if (ntype && (Cmp(ntype, type) != 0)) { - sm = typemap_get(ntype, name, ts); - } - Delete(ntype); + typedef unsigned long size_t; + ... + %apply(size_t) {my_size}; ==> %apply(unsigned long) {my_size}; + */ + if (!sm) { + SwigType *ntype = SwigType_typedef_resolve(type); + if (ntype && (Cmp(ntype, type) != 0)) { + sm = typemap_get(ntype, name); } + Delete(ntype); + } - if (sm) { - /* Got a typemap. Need to only merge attributes for methods that match our signature */ - Iterator ki; - match = 1; - for (ki = First(sm); ki.key; ki = Next(ki)) { - /* Check for a signature match with the source signature */ - if ((count_args(ki.key) == narg) && (Strstr(ki.key, ssig))) { - String *oldm; - /* A typemap we have to copy */ - String *nkey = Copy(ki.key); - Replace(nkey, ssig, dsig, DOH_REPLACE_ANY); + if (sm) { + /* Got a typemap. Need to only merge attributes for methods that match our signature */ + Iterator ki; + match = 1; + for (ki = First(sm); ki.key; ki = Next(ki)) { + /* Check for a signature match with the source signature */ + if ((count_args(ki.key) == narg) && (Strstr(ki.key, ssig))) { + String *oldm; + /* A typemap we have to copy */ + String *nkey = Copy(ki.key); + Replace(nkey, ssig, dsig, DOH_REPLACE_ANY); - /* Make sure the typemap doesn't already exist in the target map */ + /* Make sure the typemap doesn't already exist in the target map */ - oldm = Getattr(tm, nkey); - if (!oldm || (!Getattr(tm, "code"))) { - String *code; - ParmList *locals; - ParmList *kwargs; - Hash *sm1 = ki.item; + oldm = Getattr(tm, nkey); + if (!oldm || (!Getattr(tm, "code"))) { + String *code; + ParmList *locals; + ParmList *kwargs; + Hash *sm1 = ki.item; - code = Getattr(sm1, "code"); - locals = Getattr(sm1, "locals"); - kwargs = Getattr(sm1, "kwargs"); - if (code) { - String *src_str = ParmList_str_multibrackets(src); - String *dest_str = ParmList_str_multibrackets(dest); - String *source_directive = NewStringf("apply %s { %s }", src_str, dest_str); + code = Getattr(sm1, "code"); + locals = Getattr(sm1, "locals"); + kwargs = Getattr(sm1, "kwargs"); + if (code) { + String *src_str = ParmList_str_multibrackets(src); + String *dest_str = ParmList_str_multibrackets(dest); + String *source_directive = NewStringf("apply %s { %s }", src_str, dest_str); - Replace(nkey, dsig, "", DOH_REPLACE_ANY); - Replace(nkey, "tmap:", "", DOH_REPLACE_ANY); - typemap_register(nkey, dest, code, locals, kwargs, source_directive); + Replace(nkey, dsig, "", DOH_REPLACE_ANY); + Replace(nkey, "tmap:", "", DOH_REPLACE_ANY); + typemap_register(nkey, dest, code, locals, kwargs, source_directive); - Delete(source_directive); - Delete(dest_str); - Delete(src_str); - } + Delete(source_directive); + Delete(dest_str); + Delete(src_str); } - Delete(nkey); } + Delete(nkey); } } - ts--; } Delete(ssig); Delete(dsig); @@ -597,7 +551,7 @@ void Swig_typemap_clear_apply(Parm *parms) { } p = np; } - tm = get_typemap(tm_scope, Getattr(lastp, "type")); + tm = get_typemap(Getattr(lastp, "type")); if (!tm) { Delete(tsig); return; @@ -711,7 +665,6 @@ static Hash *typemap_search(const_String_or_char_ptr tmap_method, SwigType *type SwigType *primitive = 0; SwigType *ctype = 0; SwigType *ctype_unstripped = 0; - int ts; int isarray; const String *cname = 0; const String *cqualifiedname = 0; @@ -722,90 +675,86 @@ static Hash *typemap_search(const_String_or_char_ptr tmap_method, SwigType *type cname = name; if ((qualifiedname) && Len(qualifiedname)) cqualifiedname = qualifiedname; - ts = tm_scope; if (debug_display) { String *typestr = SwigType_str(type, cqualifiedname ? cqualifiedname : cname); Swig_diagnostic(Getfile(node), Getline(node), "Searching for a suitable '%s' typemap for: %s\n", tmap_method, typestr); Delete(typestr); } - while (ts >= 0) { - ctype = Copy(type); - ctype_unstripped = Copy(ctype); - while (ctype) { - /* Try to get an exact type-match */ - tm = get_typemap(ts, ctype); - result = typemap_search_helper(debug_display, tm, tm_method, ctype, cqualifiedname, cname, &backup); - if (result && Getattr(result, "code")) - goto ret_result; + ctype = Copy(type); + ctype_unstripped = Copy(ctype); + while (ctype) { + /* Try to get an exact type-match */ + tm = get_typemap(ctype); + result = typemap_search_helper(debug_display, tm, tm_method, ctype, cqualifiedname, cname, &backup); + if (result && Getattr(result, "code")) + goto ret_result; - { - /* Look for the type reduced to just the template prefix - for templated types without the template parameter list being specified */ - SwigType *template_prefix = SwigType_istemplate_only_templateprefix(ctype); - if (template_prefix) { - tm = get_typemap(ts, template_prefix); - result = typemap_search_helper(debug_display, tm, tm_method, template_prefix, cqualifiedname, cname, &backup); - Delete(template_prefix); - if (result && Getattr(result, "code")) - goto ret_result; - } - } - - /* look for [ANY] arrays */ - isarray = SwigType_isarray(ctype); - if (isarray) { - /* If working with arrays, strip away all of the dimensions and replace with "ANY". - See if that generates a match */ - SwigType *noarrays = strip_arrays(ctype); - tm = get_typemap(ts, noarrays); - result = typemap_search_helper(debug_display, tm, tm_method, noarrays, cqualifiedname, cname, &backup); - Delete(noarrays); + { + /* Look for the type reduced to just the template prefix - for templated types without the template parameter list being specified */ + SwigType *template_prefix = SwigType_istemplate_only_templateprefix(ctype); + if (template_prefix) { + tm = get_typemap(template_prefix); + result = typemap_search_helper(debug_display, tm, tm_method, template_prefix, cqualifiedname, cname, &backup); + Delete(template_prefix); if (result && Getattr(result, "code")) goto ret_result; } - - /* No match so far - try with a qualifier stripped (strip one qualifier at a time until none remain) - * The order of stripping in SwigType_strip_single_qualifier is used to provide some sort of consistency - * with the default (SWIGTYPE) typemap matching rules for the first qualifier to be stripped. */ - { - SwigType *oldctype = ctype; - ctype = SwigType_strip_single_qualifier(oldctype); - if (!Equal(ctype, oldctype)) { - Delete(oldctype); - continue; - } - Delete(oldctype); - } - - /* Once all qualifiers are stripped try resolve a typedef */ - { - SwigType *oldctype = ctype; - ctype = SwigType_typedef_resolve(ctype_unstripped); - Delete(oldctype); - ctype_unstripped = Copy(ctype); - } } - /* Hmmm. Well, no match seems to be found at all. See if there is some kind of default (SWIGTYPE) mapping */ - - primitive = SwigType_default_create(type); - while (primitive) { - tm = get_typemap(ts, primitive); - result = typemap_search_helper(debug_display, tm, tm_method, primitive, cqualifiedname, cname, &backup); + /* look for [ANY] arrays */ + isarray = SwigType_isarray(ctype); + if (isarray) { + /* If working with arrays, strip away all of the dimensions and replace with "ANY". + See if that generates a match */ + SwigType *noarrays = strip_arrays(ctype); + tm = get_typemap(noarrays); + result = typemap_search_helper(debug_display, tm, tm_method, noarrays, cqualifiedname, cname, &backup); + Delete(noarrays); if (result && Getattr(result, "code")) goto ret_result; + } - { - SwigType *nprim = SwigType_default_deduce(primitive); - Delete(primitive); - primitive = nprim; + /* No match so far - try with a qualifier stripped (strip one qualifier at a time until none remain) + * The order of stripping in SwigType_strip_single_qualifier is used to provide some sort of consistency + * with the default (SWIGTYPE) typemap matching rules for the first qualifier to be stripped. */ + { + SwigType *oldctype = ctype; + ctype = SwigType_strip_single_qualifier(oldctype); + if (!Equal(ctype, oldctype)) { + Delete(oldctype); + continue; } + Delete(oldctype); } - if (ctype != type) { - Delete(ctype); - ctype = 0; + + /* Once all qualifiers are stripped try resolve a typedef */ + { + SwigType *oldctype = ctype; + ctype = SwigType_typedef_resolve(ctype_unstripped); + Delete(oldctype); + ctype_unstripped = Copy(ctype); } - ts--; /* Hmmm. Nothing found in this scope. Guess we'll go try another scope */ + } + + /* Hmmm. Well, no match seems to be found at all. See if there is some kind of default (SWIGTYPE) mapping */ + + primitive = SwigType_default_create(type); + while (primitive) { + tm = get_typemap(primitive); + result = typemap_search_helper(debug_display, tm, tm_method, primitive, cqualifiedname, cname, &backup); + if (result && Getattr(result, "code")) + goto ret_result; + + { + SwigType *nprim = SwigType_default_deduce(primitive); + Delete(primitive); + primitive = nprim; + } + } + if (ctype != type) { + Delete(ctype); + ctype = 0; } result = backup; @@ -1318,6 +1267,7 @@ static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, No char *cmethod = Char(tmap_method); int optimal_attribute = 0; int optimal_substitution = 0; + int delete_optimal_attribute = 0; int num_substitutions = 0; SwigType *matchtype = 0; @@ -1372,7 +1322,6 @@ static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, No Delete(typestr); } - Delete(qpname); qpname = 0; Delete(noscope_pname); @@ -1391,23 +1340,16 @@ static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, No s = Copy(s); /* Make a local copy of the typemap code */ - /* Attach kwargs - ie the typemap attributes */ - kw = Getattr(tm, "kwargs"); - while (kw) { - String *value = Copy(Getattr(kw, "value")); - String *kwtype = Getattr(kw, "type"); - char *ckwname = Char(Getattr(kw, "name")); - if (kwtype) { - String *mangle = Swig_string_mangle(kwtype); - Append(value, mangle); - Delete(mangle); + /* Look in the "out" typemap for the "optimal" attribute */ + if (Cmp(cmethod, "out") == 0) { + kw = Getattr(tm, "kwargs"); + while (kw) { + if (Cmp(Getattr(kw, "name"), "optimal") == 0) { + optimal_attribute = GetFlag(kw, "value"); + break; + } + kw = nextSibling(kw); } - sprintf(temp, "%s:%s", cmethod, ckwname); - Setattr(node, typemap_method_name(temp), value); - if (Cmp(temp, "out:optimal") == 0) - optimal_attribute = (Cmp(value, "0") != 0) ? 1 : 0; - Delete(value); - kw = nextSibling(kw); } if (optimal_attribute) { @@ -1438,14 +1380,15 @@ static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, No } } if (!optimal_substitution) { - Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(node), Getline(node), "Method %s usage of the optimal attribute ignored\n", Swig_name_decl(node)); - Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(s), Getline(s), "in the out typemap as the following cannot be used to generate optimal code: %s\n", clname); - Delattr(node, "tmap:out:optimal"); + Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(node), Getline(node), "Method %s usage of the optimal attribute ignored\n", Swig_name_decl(node)); + Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(s), Getline(s), "in the out typemap as the following cannot be used to generate optimal code: %s\n", clname); + delete_optimal_attribute = 1; } } else { assert(!f); } } + if (actioncode) { assert(f); Append(f->code, actioncode); @@ -1486,6 +1429,41 @@ static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, No Delete(parm_sublist); } + /* Attach kwargs - ie the typemap attributes */ + kw = Getattr(tm, "kwargs"); + while (kw) { + String *value = Copy(Getattr(kw, "value")); + String *kwtype = Getattr(kw, "type"); + char *ckwname = Char(Getattr(kw, "name")); + { + /* Expand special variables in typemap attributes. */ + SwigType *ptype = Getattr(node, "type"); + String *pname = Getattr(node, "name"); + SwigType *mtype = Getattr(node, "tmap:match"); + SwigType *matchtype = mtype ? mtype : ptype; + ParmList *parm_sublist; + typemap_replace_vars(value, NULL, matchtype, ptype, pname, (char *)lname, 1); + + /* Expand special variable macros (embedded typemaps) in typemap attributes. */ + parm_sublist = NewParmWithoutFileLineInfo(ptype, pname); + Setattr(parm_sublist, "lname", lname); + replace_embedded_typemap(value, parm_sublist, NULL, tm); + Delete(parm_sublist); + } + if (kwtype) { + String *mangle = Swig_string_mangle(kwtype); + Append(value, mangle); + Delete(mangle); + } + sprintf(temp, "%s:%s", cmethod, ckwname); + Setattr(node, typemap_method_name(temp), value); + Delete(value); + kw = nextSibling(kw); + } + + if (delete_optimal_attribute) + Delattr(node, "tmap:out:optimal"); + Replace(s, "$name", pname, DOH_REPLACE_ANY); symname = Getattr(node, "sym:name"); @@ -1558,17 +1536,44 @@ String *Swig_typemap_lookup(const_String_or_char_ptr tmap_method, Node *node, co * If this hash (tm) contains a linked list of parameters under its "kwargs" * attribute, add keys for each of those named keyword arguments to this * parameter for later use. - * For example, attach the typemap attributes to p: + * For example, attach the typemap attributes to firstp (first parameter in parameter list): * %typemap(in, foo="xyz") ... - * A new attribute called "tmap:in:foo" with value "xyz" is attached to p. + * A new attribute called "tmap:in:foo" with value "xyz" is attached to firstp. + * Also expands special variables and special variable macros in the typemap attributes. * ----------------------------------------------------------------------------- */ -static void typemap_attach_kwargs(Hash *tm, const_String_or_char_ptr tmap_method, Parm *p) { +static void typemap_attach_kwargs(Hash *tm, const_String_or_char_ptr tmap_method, Parm *firstp, int nmatch) { String *temp = NewStringEmpty(); Parm *kw = Getattr(tm, "kwargs"); while (kw) { String *value = Copy(Getattr(kw, "value")); String *type = Getattr(kw, "type"); + int i; + Parm *p = firstp; + /* Expand special variables */ + for (i = 0; i < nmatch; i++) { + SwigType *type = Getattr(p, "type"); + String *pname = Getattr(p, "name"); + String *lname = Getattr(p, "lname"); + SwigType *mtype = Getattr(p, "tmap:match"); + SwigType *matchtype = mtype ? mtype : type; + typemap_replace_vars(value, NULL, matchtype, type, pname, lname, i + 1); + p = nextSibling(p); + } + + /* Expand special variable macros (embedded typemaps). + * Special variable are expanded first above as they might be used in the special variable macros. + * For example: $typemap(imtype, $2_type). */ + p = firstp; + for (i = 0; i < nmatch; i++) { + SwigType *type = Getattr(p, "type"); + String *pname = Getattr(p, "name"); + String *lname = Getattr(p, "lname"); + ParmList *parm_sublist = NewParmWithoutFileLineInfo(type, pname); + Setattr(parm_sublist, "lname", lname); + replace_embedded_typemap(value, parm_sublist, NULL, tm); + p = nextSibling(p); + } if (type) { Hash *v = NewHash(); Setattr(v, "type", type); @@ -1578,13 +1583,13 @@ static void typemap_attach_kwargs(Hash *tm, const_String_or_char_ptr tmap_method } Clear(temp); Printf(temp, "%s:%s", tmap_method, Getattr(kw, "name")); - Setattr(p, typemap_method_name(temp), value); + Setattr(firstp, typemap_method_name(temp), value); Delete(value); kw = nextSibling(kw); } Clear(temp); Printf(temp, "%s:match_type", tmap_method); - Setattr(p, typemap_method_name(temp), Getattr(tm, "type")); + Setattr(firstp, typemap_method_name(temp), Getattr(tm, "type")); Delete(temp); } @@ -1779,7 +1784,7 @@ void Swig_typemap_attach_parms(const_String_or_char_ptr tmap_method, ParmList *p Setattr(firstp, typemap_method_name(temp), p); /* Attach kwargs */ - typemap_attach_kwargs(tm, tmap_method, firstp); + typemap_attach_kwargs(tm, tmap_method, firstp, nmatch); /* Replace the argument number */ sprintf(temp, "%d", argnum); @@ -2054,16 +2059,9 @@ static void replace_embedded_typemap(String *s, ParmList *parm_sublist, Wrapper * ----------------------------------------------------------------------------- */ void Swig_typemap_debug() { - int ts; int nesting_level = 2; Printf(stdout, "---[ typemaps ]--------------------------------------------------------------\n"); - - ts = tm_scope; - while (ts >= 0) { - Printf(stdout, "::: scope %d\n\n", ts); - Swig_print(typemaps[ts], nesting_level); - ts--; - } + Swig_print(typemaps, nesting_level); Printf(stdout, "-----------------------------------------------------------------------------\n"); } diff --git a/Tools/convertpath b/Tools/convertpath index fce5ac24b..0cc8b74bb 100755 --- a/Tools/convertpath +++ b/Tools/convertpath @@ -1,25 +1,32 @@ #!/bin/sh -# Unix to Windows relative path conversion in a script. +# Unix to Windows path conversion in a script. # Useful for avoiding backslash quoting difficulties in Makefiles. -# Acts as a much dumbed down 'cygpath -w' tool. +# Acts as a much dumbed down cygpath tool mainly for use on MinGW. usage() { cat <&2; exit 1 ;; + esac ;; -u) shift; echo $@ | sed -e 's,\\,/,g' ;; + -w) shift; echo $@ | sed -e 's,/,\\,g' ;; -h) shift; usage; ;; *) usage; exit 1 ;; esac diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 1eec5bc1e..5eeec0785 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -14,7 +14,7 @@ all: javascript CC = @CC@ -# HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries +# HACK: under Mac OS X a g++ compiled interpreter is seg-faulting when loading module libraries # with 'c++' it works... probably some missing flags? JSCXX = @JSINTERPRETERCXX@ CPPFLAGS = @BOOST_CPPFLAGS@ diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 7016e9c31..5001bc25a 100644 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -13,7 +13,7 @@ typedef int (*V8ExtensionInitializer) (v8::Handle module); // Note: these typedefs and defines are used to deal with v8 API changes since version 3.19.00 -#if (SWIG_V8_VERSION < 0x031903) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) typedef v8::Handle SwigV8ReturnValue; typedef v8::Arguments SwigV8Arguments; typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; @@ -28,11 +28,11 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #endif -#if (SWIG_V8_VERSION < 0x032117) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032117) #define SWIGV8_HANDLESCOPE() v8::HandleScope scope #define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope #define SWIGV8_ESCAPE(val) return scope.Close(val) -#elif (SWIG_V8_VERSION < 0x032318) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) #define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope(v8::Isolate::GetCurrent()); #define SWIGV8_ESCAPE(val) return scope.Close(val) @@ -42,7 +42,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIGV8_ESCAPE(val) return scope.Escape(val) #endif -#if (SWIG_V8_VERSION < 0x032318) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) #define SWIGV8_CURRENT_CONTEXT() v8::Context::GetCurrent() #define SWIGV8_STRING_NEW(str) v8::String::New(str) #define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(func) @@ -59,7 +59,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #endif -#if (SWIG_V8_VERSION < 0x031900) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) typedef v8::Persistent SwigV8Context; #else typedef v8::Local SwigV8Context; @@ -149,9 +149,9 @@ bool V8Shell::RunScript(const std::string &scriptPath) { context->Exit(); -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) context.Dispose(); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) context.Dispose(v8::Isolate::GetCurrent()); #else // context.Dispose(); @@ -193,9 +193,9 @@ bool V8Shell::RunShell() { context->Exit(); -#if (SWIG_V8_VERSION < 0x031710) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) context.Dispose(); -#elif (SWIG_V8_VERSION < 0x031900) +#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) context.Dispose(v8::Isolate::GetCurrent()); #else // context.Dispose(); @@ -249,7 +249,7 @@ SwigV8Context V8Shell::CreateShellContext() { global->Set(SWIGV8_STRING_NEW("require"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Require)); global->Set(SWIGV8_STRING_NEW("version"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Version)); -#if (SWIG_V8_VERSION < 0x031900) +#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) SwigV8Context context = v8::Context::New(NULL, global); return context; #else diff --git a/Tools/mkdist.py b/Tools/mkdist.py index 2e69dbece..11a0dd6cd 100755 --- a/Tools/mkdist.py +++ b/Tools/mkdist.py @@ -78,10 +78,6 @@ outdir = os.path.basename(os.getcwd()) + "/" + dirname + "/" print "Grabbing tagged release git repository using 'git archive' into " + outdir os.system("(cd .. && git archive --prefix=" + outdir + " " + tag + " . | tar -xf -)") == 0 or failed() -# Remove the debian directory -- it's not official - -os.system("rm -Rf "+dirname+"/debian") == 0 or failed() - # Go build the system print "Building system" @@ -95,8 +91,6 @@ os.system("find "+dirname+" -name autom4te.cache -exec rm -rf {} \\;") # Build documentation print "Building html documentation" os.system("cd "+dirname+"/Doc/Manual && make all clean-baks") == 0 or failed() -print "Building man pages" -os.system("cd "+dirname+"/CCache && yodl2man -o ccache-swig.1 ccache.yo") == 0 or failed() # Build the tar-ball os.system("tar -cf "+dirname+".tar "+dirname) == 0 or failed() diff --git a/Tools/mkwindows.sh b/Tools/mkwindows.sh index 6042361b3..0651bbd60 100755 --- a/Tools/mkwindows.sh +++ b/Tools/mkwindows.sh @@ -11,8 +11,7 @@ zip= # options for configure extraconfigureoptions= -compileflags="-O2" -extracompileflags= +compileflags="-O2 -Wall -Wextra" if test x$1 != x; then version=$1 @@ -43,14 +42,28 @@ else if test x$zip = x; then zip=zip fi - extraconfigureoptions="--host=i586-mingw32msvc --build=i686-linux" + echo "Checking that mingw 32-bit gcc is installed/available" + if test -n "`which i686-w64-mingw32-gcc`" ; then + i686-w64-mingw32-gcc --version || exit 1 + i686-w64-mingw32-g++ --version || exit 1 + extraconfigureoptions="--host=i686-w64-mingw32 --build=i686-linux" + # Statically link so that libstdc++-6.dll and libgcc_s_sjlj-1.dll don't have to be shipped + compileflags="$compileflags -static-libgcc -static-libstdc++" + elif test -n "`which i586-mingw32msvc-gcc`" ; then + i586-mingw32msvc-gcc --version || exit 1 + i586-mingw32msvc-g++ --version || exit 1 + extraconfigureoptions="--host=i586-mingw32msvc --build=i686-linux" + else + echo "Could not detect mingw gcc - please install mingw-w64 package." + exit 1; + fi else if test "$cygwin"; then echo "Building native Windows executable on Cygwin" if test x$zip = x; then zip=zip fi - compileflags="-O2 -mno-cygwin" + compileflags="$compileflags -mno-cygwin" else echo "Unknown platform. Requires either Linux or MinGW." exit 1; @@ -58,6 +71,9 @@ else fi fi +export CFLAGS="$compileflags" +export CXXFLAGS="$compileflags" + swigbasename=swig-$version swigwinbasename=swigwin-$version tarball=$swigbasename.tar.gz @@ -86,10 +102,10 @@ if test -f "$tarball"; then tar -zxf ../$tarball cd $swigbasename (cd ../.. && cp $pcre_tarball $builddir/$swigbasename) - echo Running: Tools/pcre-build.sh $extraconfigureoptions CFLAGS="$compileflags" CXXFLAGS="$compileflags" - ./Tools/pcre-build.sh $extraconfigureoptions CFLAGS="$compileflags" CXXFLAGS="$compileflags" || exit 1 - echo Running: ./configure $extraconfigureoptions CFLAGS="$compileflags" CXXFLAGS="$compileflags" - ./configure $extraconfigureoptions CFLAGS="$compileflags" CXXFLAGS="$compileflags" || exit 1 + echo Running: Tools/pcre-build.sh $extraconfigureoptions + ./Tools/pcre-build.sh $extraconfigureoptions + echo Running: ./configure $extraconfigureoptions --without-alllang + ./configure $extraconfigureoptions --without-alllang echo "Compiling (quietly)..." make > build.log echo "Simple check to see if swig.exe runs..." diff --git a/Tools/nuget-install.cmd b/Tools/nuget-install.cmd new file mode 100644 index 000000000..08caea7e0 --- /dev/null +++ b/Tools/nuget-install.cmd @@ -0,0 +1,28 @@ +rem Workaround 'nuget install' not being reliable by retrying a few times + +@echo off +rem initiate the retry number +set errorCode=1 +set retryNumber=0 +set maxRetries=5 + +:RESTORE +nuget install %* + +rem problem? +IF ERRORLEVEL %errorCode% GOTO :RETRY + +rem everything is fine! +GOTO :EXIT + +:RETRY +@echo Oops, nuget restore exited with code %errorCode% - let us try again! +set /a retryNumber=%retryNumber%+1 +IF %reTryNumber% LSS %maxRetries% (GOTO :RESTORE) +IF %retryNumber% EQU %maxRetries% (GOTO :ERR) + +:ERR +@echo Sorry, we tried restoring nuget packages for %maxRetries% times and all attempts were unsuccessful! +EXIT /B 1 + +:EXIT diff --git a/Tools/testflags.py b/Tools/testflags.py index 04bbc1c67..564bc91e6 100755 --- a/Tools/testflags.py +++ b/Tools/testflags.py @@ -1,13 +1,13 @@ #!/usr/bin/env python -def get_cflags(language, std): +def get_cflags(language, std, compiler): if std == None or len(std) == 0: std = "gnu89" - c_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wdeclaration-after-statement" + c_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wdeclaration-after-statement -Wmissing-field-initializers" cflags = { "csharp":"-Werror " + c_common, "d":"-Werror " + c_common, - "go":"-Werror " + c_common, + "go":"-Werror " + c_common + " -Wno-declaration-after-statement", "guile":"-Werror " + c_common, "java":"-Werror " + c_common, "javascript":"-Werror " + c_common, @@ -15,21 +15,25 @@ def get_cflags(language, std): "octave":"-Werror " + c_common, "perl5":"-Werror " + c_common, "php":"-Werror " + c_common, + "php5":"-Werror " + c_common, "python":"-Werror " + c_common, + "r":"-Werror " + c_common, "ruby":"-Werror " + c_common, "scilab":"-Werror " + c_common, "tcl":"-Werror " + c_common, } + if compiler == 'clang': + cflags["guile"] += " -Wno-attributes" # -Wno-attributes is for clang LLVM 3.5 and bdw-gc < 7.5 used by guile if language not in cflags: raise RuntimeError("{} is not a supported language".format(language)) return cflags[language] -def get_cxxflags(language, std): +def get_cxxflags(language, std, compiler): if std == None or len(std) == 0: std = "c++98" - cxx_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type" + cxx_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wmissing-field-initializers" cxxflags = { "csharp":"-Werror " + cxx_common, "d":"-Werror " + cxx_common, @@ -41,11 +45,15 @@ def get_cxxflags(language, std): "octave":"-Werror " + cxx_common, "perl5":"-Werror " + cxx_common, "php":"-Werror " + cxx_common, + "php5":"-Werror " + cxx_common, "python":"-Werror " + cxx_common, + "r":"-Werror " + cxx_common, "ruby":"-Werror " + cxx_common, - "scilab": cxx_common, + "scilab":"-Werror " + cxx_common, "tcl":"-Werror " + cxx_common, } + if compiler == 'clang': + cxxflags["guile"] += " -Wno-attributes" # -Wno-attributes is for clang LLVM 3.5 and bdw-gc < 7.5 used by guile if language not in cxxflags: raise RuntimeError("{} is not a supported language".format(language)) @@ -59,12 +67,15 @@ flags = parser.add_mutually_exclusive_group(required=True) flags.add_argument('-c', '--cflags', action='store_true', default=False, help='show CFLAGS') flags.add_argument('-x', '--cxxflags', action='store_true', default=False, help='show CXXFLAGS') parser.add_argument('-s', '--std', required=False, help='language standard flags for the -std= option') +parser.add_argument('-C', '--compiler', required=False, help='compiler used (clang or gcc)') args = parser.parse_args() if args.cflags: - print("{}".format(get_cflags(args.language, args.std))) + get_flags = get_cflags elif args.cxxflags: - print("{}".format(get_cxxflags(args.language, args.std))) + get_flags = get_cxxflags else: parser.print_help() exit(1) + +print(get_flags(args.language, args.std, args.compiler)) diff --git a/Tools/travis-linux-install.sh b/Tools/travis-linux-install.sh new file mode 100755 index 000000000..87801d398 --- /dev/null +++ b/Tools/travis-linux-install.sh @@ -0,0 +1,111 @@ +#!/bin/bash + +set -e # exit on failure (same as -o errexit) + +lsb_release -a +sudo apt-get -qq update + +if [[ "$CC" == gcc-5 ]]; then + sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test + sudo apt-get -qq update + sudo apt-get install -qq g++-5 +elif [[ "$CC" == gcc-6 ]]; then + sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test + sudo apt-get -qq update + sudo apt-get install -qq g++-6 +fi + +sudo apt-get -qq install libboost-dev + +WITHLANG=$SWIGLANG + +case "$SWIGLANG" in + "") ;; + "csharp") + sudo apt-get -qq install mono-devel + ;; + "d") + wget http://downloads.dlang.org/releases/2014/dmd_2.066.0-0_amd64.deb + sudo dpkg -i dmd_2.066.0-0_amd64.deb + ;; + "go") + ;; + "javascript") + case "$ENGINE" in + "node") + sudo add-apt-repository -y ppa:chris-lea/node.js + sudo apt-get -qq update + sudo apt-get install -qq nodejs rlwrap + sudo npm install -g node-gyp + ;; + "jsc") + sudo apt-get install -qq libwebkitgtk-dev + ;; + "v8") + sudo apt-get install -qq libv8-dev + ;; + esac + ;; + "guile") + sudo apt-get -qq install guile-2.0-dev + ;; + "lua") + if [[ -z "$VER" ]]; then + sudo apt-get -qq install lua5.2 liblua5.2-dev + else + sudo add-apt-repository -y ppa:ubuntu-cloud-archive/mitaka-staging + sudo apt-get -qq update + sudo apt-get -qq install lua${VER} liblua${VER}-dev + fi + ;; + "ocaml") + # configure also looks for ocamldlgen, but this isn't packaged. But it isn't used by default so this doesn't matter. + sudo apt-get -qq install ocaml ocaml-findlib + ;; + "octave") + if [[ -z "$VER" ]]; then + sudo apt-get -qq install octave3.2 octave3.2-headers + else + sudo add-apt-repository -y ppa:kwwette/octaves + sudo apt-get -qq update + sudo apt-get -qq install liboctave${VER}-dev + fi + ;; + "php5") + sudo apt-get -qq install php5-cli php5-dev + ;; + "php") + sudo add-apt-repository -y ppa:ondrej/php + sudo apt-get -qq update + sudo apt-get -qq install php$VER-cli php$VER-dev + ;; + "python") + sudo apt-get -qq install pep8 + if [[ "$PY3" ]]; then + sudo apt-get install -qq python3-dev + fi + WITHLANG=$SWIGLANG$PY3 + if [[ "$VER" ]]; then + sudo add-apt-repository -y ppa:fkrull/deadsnakes + sudo apt-get -qq update + sudo apt-get -qq install python${VER}-dev + WITHLANG=$SWIGLANG$PY3=$SWIGLANG$VER + fi + ;; + "r") + sudo apt-get -qq install r-base + ;; + "ruby") + if [[ "$VER" ]]; then + rvm install $VER + fi + ;; + "scilab") + sudo apt-get -qq install scilab + ;; + "tcl") + sudo apt-get -qq install tcl-dev + ;; +esac + +set +e # turn off exit on failure (same as +o errexit) diff --git a/Tools/travis-osx-install.sh b/Tools/travis-osx-install.sh new file mode 100755 index 000000000..85183722b --- /dev/null +++ b/Tools/travis-osx-install.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +set -e # exit on failure (same as -o errexit) + +sw_vers +brew update +brew list +# brew install pcre # Travis Xcode-7.3 has pcre +# brew install boost + +WITHLANG=$SWIGLANG + +case "$SWIGLANG" in + "csharp") + brew install mono + ;; + "guile") + Tools/brew-install guile + ;; + "lua") + brew install lua + ;; + "python") + WITHLANG=$SWIGLANG$PY3 + if [[ "$PY3" ]]; then + brew install python3 + brew list -v python3 + fi + ;; +esac + +# Workaround for https://github.com/travis-ci/travis-ci/issues/6522 +set +e # turn off exit on failure (same as +o errexit) diff --git a/appveyor.yml b/appveyor.yml index dc96d0bca..d7be4a3d5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -5,26 +5,19 @@ platform: environment: matrix: - SWIGLANG: csharp - VSVER: 14 + VSVER: 12 - SWIGLANG: csharp - VSVER: 12 + VSVER: 14 - SWIGLANG: java - VSVER: 12 + VSVER: 14 - SWIGLANG: python - VSVER: 12 + VSVER: 14 VER: 27 - SWIGLANG: python - VSVER: 12 - VER: 34 + VSVER: 14 + VER: 35 PY3: 1 -matrix: - allow_failures: - - platform: x64 - SWIGLANG: python - VSVER: 12 - VER: 27 - install: - date /T & time /T - set PATH=C:\cygwin\bin;%PATH% @@ -46,7 +39,7 @@ install: - ps: $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS")) - echo "Using Visual Studio %VSVER%.0 at %VSCOMNTOOLS%" - call "%VSCOMNTOOLS%\..\..\VC\vcvarsall.bat" %VCVARS_PLATFORM% -- nuget install pcre -Verbosity detailed -Version 8.33.0.1 -OutputDirectory C:\pcre +- Tools\nuget-install.cmd pcre -Verbosity detailed -Version 8.33.0.1 -OutputDirectory C:\pcre - set PCRE_ROOT=C:/pcre/pcre.8.33.0.1/build/native - set PATH=C:\Python%VER%%LANG_PLATFORM%;%PATH% - python -V diff --git a/configure.ac b/configure.ac index 3c4d192dd..7313dbd3f 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl Process this file with autoconf to produce a configure script. dnl The macros which aren't shipped with the autotools are stored in the dnl Tools/config directory in .m4 files. -AC_INIT([swig],[3.0.7],[http://www.swig.org]) +AC_INIT([swig],[3.0.11],[http://www.swig.org]) dnl NB: When this requirement is increased to 2.60 or later, AC_PROG_SED dnl definition below can be removed @@ -40,11 +40,6 @@ AC_DEFINE_UNQUOTED(SWIG_PLATFORM, ["$host"], [Platform that SWIG is built for]) dnl Checks for header files. AC_HEADER_STDC -dnl Checks for types. -AC_LANG_PUSH([C++]) -AC_CHECK_TYPES([bool]) -AC_LANG_POP([C++]) - dnl Look for popen AC_ARG_WITH(popen, AS_HELP_STRING([--without-popen], [Disable popen]), with_popen="$withval") if test x"${with_popen}" = xno ; then @@ -122,23 +117,6 @@ echo "Note : None of the following packages are required for users to compile an echo "" AC_PROG_YACC -AC_PROG_RANLIB -AC_CHECK_PROGS(AR, ar aal, ar) -AC_SUBST(AR) -AC_CHECK_PROGS(YODL2MAN, yodl2man) -AC_CHECK_PROGS(YODL2HTML, yodl2html) - -if test -n "$YODL2MAN"; then - AC_MSG_CHECKING([yodl2man version >= 2.02]) - [yodl_version=`$YODL2MAN --version 2>&1 | grep 'yodl version' | sed 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.*[0-9]*\).*/\1/g'`] - AX_COMPARE_VERSION([$yodl_version],[ge],[2.02], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no - $yodl_version found])]) -fi - -if test -n "$YODL2HTML"; then - AC_MSG_CHECKING([yodl2html version >= 2.02]) - [yodl_version=`$YODL2HTML --version 2>&1 | grep 'yodl version' | sed 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/g'`] - AX_COMPARE_VERSION([$yodl_version],[ge],[2.02], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no - $yodl_version found])]) -fi echo "" echo "Checking for installed target languages and other information in order to compile and run" @@ -357,7 +335,7 @@ fi # On darwin 10.7,10.8,10.9 using clang++, need to ensure using # libc++ for tests and examples to run under mono. May affect -# other language targets as well - problem is an OSX incompatibility +# other language targets as well - problem is a Mac OS X incompatibility # between libraries depending on libstdc++ and libc++. CLANGXX= $CXX -v 2>&1 | grep -i clang >/dev/null && CLANGXX=yes @@ -408,6 +386,9 @@ case $host in *) PHP_SO=$SO;; esac +AC_SUBST(PHP5_SO) +PHP5_SO=$PHP_SO + AC_SUBST(MZSCHEME_SO) case $host in *) MZSCHEME_SO=.so;; @@ -464,6 +445,12 @@ fi]) AC_ARG_WITH(alllang, AS_HELP_STRING([--without-alllang], [Disable all languages]), with_alllang="$withval") +if test "$with_alllang" = "no"; then + alllang_default=no +else + alllang_default=yes +fi + AC_CHECK_PROGS(PKGCONFIG, [pkg-config]) #-------------------------------------------------------------------- @@ -478,14 +465,14 @@ AC_ARG_WITH(tclconfig, AS_HELP_STRING([--without-tcl], [Disable Tcl]) AS_HELP_STRING([--with-tclconfig=path], [Set location of tclConfig.sh]), [with_tclconfig="$withval"], [with_tclconfig=]) AC_ARG_WITH(tcl, [ --with-tcl=path Set location of Tcl package],[ - TCLPACKAGE="$withval"], [TCLPACKAGE=yes]) + TCLPACKAGE="$withval"], [TCLPACKAGE="$alllang_default"]) AC_ARG_WITH(tclincl,[ --with-tclincl=path Set location of Tcl include directory],[ TCLINCLUDE="$ISYSTEM$withval"], [TCLINCLUDE=]) AC_ARG_WITH(tcllib,[ --with-tcllib=path Set location of Tcl library directory],[ TCLLIB="-L$withval"], [TCLLIB=]) # First, check for "--without-tcl" or "--with-tcl=no". -if test x"${TCLPACKAGE}" = xno -o x"${with_alllang}" = xno; then +if test x"${TCLPACKAGE}" = xno; then AC_MSG_NOTICE([Disabling Tcl]) else AC_MSG_CHECKING([for Tcl configuration]) @@ -606,15 +593,15 @@ PYLINK= PYPACKAGE= AC_ARG_WITH(python, AS_HELP_STRING([--without-python], [Disable Python]) -AS_HELP_STRING([--with-python=path], [Set location of Python executable]),[ PYBIN="$withval"], [PYBIN=yes]) +AS_HELP_STRING([--with-python=path], [Set location of Python executable]),[ PYBIN="$withval"], [PYBIN="$alllang_default"]) # First, check for "--without-python" or "--with-python=no". -if test x"${PYBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${PYBIN}" = xno; then AC_MSG_NOTICE([Disabling Python]) else # First figure out the name of the Python executable if test "x$PYBIN" = xyes; then - AC_CHECK_PROGS(PYTHON, [python python2.8 python2.7 python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0 python1.6 python1.5 python1.4]) + AC_CHECK_PROGS(PYTHON, [python python2.8 python2.7 python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0]) else PYTHON="$PYBIN" fi @@ -626,19 +613,20 @@ else AC_MSG_RESULT($PYVER) if test -z "$PYVER"; then PYVER=0 + else + AC_MSG_CHECKING(for Python os.name) + PYOSNAME=`($PYTHON -c "import sys, os; sys.stdout.write(os.name)")` + AC_MSG_RESULT($PYOSNAME) fi fi - if test $PYVER -le 2; then + if test $PYVER -eq 1 -o $PYVER -eq 2; then AC_MSG_CHECKING(for Python prefix) PYPREFIX=`($PYTHON -c "import sys; sys.stdout.write(sys.prefix)") 2>/dev/null` AC_MSG_RESULT($PYPREFIX) AC_MSG_CHECKING(for Python exec-prefix) PYEPREFIX=`($PYTHON -c "import sys; sys.stdout.write(sys.exec_prefix)") 2>/dev/null` AC_MSG_RESULT($PYEPREFIX) - AC_MSG_CHECKING(for Python os.name) - PYOSNAME=`($PYTHON -c "import sys, os; sys.stdout.write(os.name)")` - AC_MSG_RESULT($PYOSNAME) if test x"$PYOSNAME" = x"nt"; then # Windows installations are quite different to posix installations @@ -747,28 +735,34 @@ PY3LINK= PY3PACKAGE= AC_ARG_WITH(python3, AS_HELP_STRING([--without-python3], [Disable Python 3.x support]) -AS_HELP_STRING([--with-python3=path], [Set location of Python 3.x executable]),[ PY3BIN="$withval"], [PY3BIN=yes]) +AS_HELP_STRING([--with-python3=path], [Set location of Python 3.x executable]),[ PY3BIN="$withval"], [PY3BIN="$alllang_default"]) # First, check for "--without-python3" or "--with-python3=no". -if test x"${PY3BIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${PY3BIN}" = xno; then AC_MSG_NOTICE([Disabling Python 3.x support]) else + if test -z "$PYVER"; then + PYVER=0 + fi if test "x$PY3BIN" = xyes; then - for py_ver in 3 3.9 3.8 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0 ""; do - AC_CHECK_PROGS(PYTHON3, [python$py_ver]) - if test -n "$PYTHON3"; then - AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) - if test -n "$PY3CONFIG"; then - break + if test x"$PYOSNAME" = x"nt" -a $PYVER -ge 3; then + PYTHON3="$PYTHON" + else + for py_ver in 3 3.9 3.8 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0 ""; do + AC_CHECK_PROGS(PYTHON3, [python$py_ver]) + if test -n "$PYTHON3"; then + AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) + if test -n "$PY3CONFIG"; then + break + fi fi - fi - done + done + fi else PYTHON3="$PY3BIN" AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) fi - PYVER=0 if test -n "$PYTHON3"; then AC_MSG_CHECKING([for $PYTHON3 major version number]) PYVER=`($PYTHON3 -c "import sys; sys.stdout.write(sys.version[[0]])") 2>/dev/null` @@ -887,13 +881,13 @@ else ;; *)PYTHON3DYNAMICLINKING="";; esac -fi -AC_SUBST(PY3INCLUDE) -AC_SUBST(PY3LIB) -AC_SUBST(PY3LINK) -AC_SUBST(PYTHON3DYNAMICLINKING) -AC_CHECK_PROGS(PEP8, pep8) + AC_SUBST(PY3INCLUDE) + AC_SUBST(PY3LIB) + AC_SUBST(PY3LINK) + AC_SUBST(PYTHON3DYNAMICLINKING) + AC_CHECK_PROGS(PEP8, pep8) +fi #---------------------------------------------------------------- # Look for Perl5 @@ -902,10 +896,10 @@ AC_CHECK_PROGS(PEP8, pep8) PERLBIN= AC_ARG_WITH(perl5, AS_HELP_STRING([--without-perl5], [Disable Perl5]) -AS_HELP_STRING([--with-perl5=path], [Set location of Perl5 executable]),[ PERLBIN="$withval"], [PERLBIN=yes]) +AS_HELP_STRING([--with-perl5=path], [Set location of Perl5 executable]),[ PERLBIN="$withval"], [PERLBIN="$alllang_default"]) # First, check for "--without-perl5" or "--with-perl5=no". -if test x"${PERLBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${PERLBIN}" = xno; then AC_MSG_NOTICE([Disabling Perl5]) PERL= else @@ -1013,10 +1007,10 @@ OCTAVEBIN= OCTAVE_SO=.oct AC_ARG_WITH(octave, AS_HELP_STRING([--without-octave], [Disable Octave]) -AS_HELP_STRING([--with-octave=path], [Set location of Octave executable]),[OCTAVEBIN="$withval"], [OCTAVEBIN=yes]) +AS_HELP_STRING([--with-octave=path], [Set location of Octave executable]),[OCTAVEBIN="$withval"], [OCTAVEBIN="$alllang_default"]) # First, check for "--without-octave" or "--with-octave=no". -if test x"${OCTAVEBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${OCTAVEBIN}" = xno; then AC_MSG_NOTICE([Disabling Octave]) OCTAVE= @@ -1098,11 +1092,11 @@ AC_SUBST(OCTAVE_LDFLAGS) #---------------------------------------------------------------- AC_ARG_WITH(scilab, AS_HELP_STRING([--without-scilab], [Disable Scilab]) -AS_HELP_STRING([--with-scilab=path], [Set location of Scilab executable]),[SCILABBIN="$withval"], [SCILABBIN=yes]) +AS_HELP_STRING([--with-scilab=path], [Set location of Scilab executable]),[SCILABBIN="$withval"], [SCILABBIN="$alllang_default"]) AC_ARG_WITH(scilab-inc, [ --with-scilab-inc=path Set location of Scilab include directory], [SCILABINCDIR="$withval"], [SCILABINCDIR=""]) # First, check for "--without-scilab" or "--with-scilab=no". -if test x"${SCILABBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${SCILABBIN}" = xno; then AC_MSG_NOTICE([Disabling Scilab]) SCILAB= else @@ -1158,12 +1152,12 @@ else if test -r $i/api_scilab.h; then AC_MSG_RESULT($i) SCILABINCLUDE="-I$i" - break; + break fi if test -r $i/scilab/api_scilab.h; then AC_MSG_RESULT($i/scilab) SCILABINCLUDE="-I$i/scilab" - break; + break fi done if test "$SCILABINCLUDE" = "" ; then @@ -1184,16 +1178,20 @@ AC_SUBST(SCILABOPT) #---------------------------------------------------------------- AC_ARG_WITH(java, AS_HELP_STRING([--without-java], [Disable Java]) -AS_HELP_STRING([--with-java=path], [Set location of java executable]),[JAVABIN="$withval"], [JAVABIN=yes]) +AS_HELP_STRING([--with-java=path], [Set location of java executable]),[JAVABIN="$withval"], [JAVABIN="$alllang_default"]) AC_ARG_WITH(javac, [ --with-javac=path Set location of javac executable],[JAVACBIN="$withval"], [JAVACBIN=]) # First, check for "--without-java" or "--with-java=no". -if test x"${JAVABIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${JAVABIN}" = xno; then AC_MSG_NOTICE([Disabling Java]) JAVA= else -dnl Platform-specific Java detection logic. +dnl Detect everything we need for Java: java for running Java tests, javac for +dnl compiling them and C headers for compiling C code. +dnl +dnl If JAVA_HOME is defined and contains everything needed, as it's supposed to, +dnl just use it. Otherwise try to locate the necessary files in the path. case $host in *-*-cygwin*) dnl Ensure that JAVA_HOME is in the form we can use, it's typically set to Windows path by the installer. @@ -1204,13 +1202,22 @@ case $host in JAVA_CLASSPATH_SEP=";" ;; *-*-mingw*) + if test -n "$JAVA_HOME"; then + JAVA_HOME=`${srcdir}/Tools/convertpath -u "$JAVA_HOME"` + fi JAVA_CLASSPATH_SEP=";" ;; *-*-darwin*) - dnl Under OS X JAVA_HOME is not set by default, try to set it to the default value. - if test -z "$JAVA_HOME"; then + dnl Under OS X JAVA_HOME is not set by default, try to use the system default JRE. + if test -z "$JAVA_HOME" -a -x /usr/libexec/java_home; then JAVA_HOME=`/usr/libexec/java_home` fi + dnl The JAVA_HOME doesn't contain the JDK headers though, but they seem to + dnl always be in the same location, according to Apple JNI documentation. + JAVA_OSX_STD_INCDIR="/System/Library/Frameworks/JavaVM.framework/Headers" + if test -r "$JAVA_OSX_STD_INCDIR/jni.h"; then + JAVA_HOME_INCDIR=$JAVA_OSX_STD_INCDIR + fi JAVA_CLASSPATH_SEP=":" ;; *) @@ -1219,11 +1226,44 @@ case $host in ;; esac +AC_MSG_CHECKING(for java JDK) +if test -n "$JAVA_HOME"; then + dnl Don't complain about missing executables/headers if they had been + dnl explicitly overridden from the command line, but otherwise verify that we + dnl have everything we need. + java_home_ok=1 + if test -z "$JAVABIN" -a ! -x "$JAVA_HOME/bin/java"; then + AC_MSG_WARN([No java executable under JAVA_HOME.]) + java_home_ok=0 + fi + if test -z "$JAVACBIN" -a ! -x "$JAVA_HOME/bin/javac"; then + AC_MSG_WARN([No javac executable under JAVA_HOME.]) + java_home_ok=0 + fi + + dnl By default the headers are under JAVA_HOME/include, but OS X is special + dnl and defines JAVA_HOME_INCDIR differently above. + if test -z "$JAVA_HOME_INCDIR"; then + JAVA_HOME_INCDIR="$JAVA_HOME/include" + fi + if test -z "$JAVAINCDIR" -a ! -r "$JAVA_HOME_INCDIR/jni.h"; then + AC_MSG_WARN([No java headers under JAVA_HOME (does it point to a JDK and not just JRE?).]) + java_home_ok=0 + fi + if test "$java_home_ok" = 1; then + AC_MSG_RESULT([found (in $JAVA_HOME)]) + else + AC_MSG_RESULT(no) + AC_MSG_WARN([JAVA_HOME ($JAVA_HOME) is defined but does not point to a complete JDK installation, ignoring it.]) + JAVA_HOME= + fi +else + AC_MSG_RESULT([no (JAVA_HOME is not defined)]) +fi + if test "x$JAVABIN" = xyes; then - if test -x "$JAVA_HOME/bin/java"; then - AC_MSG_CHECKING(for java) + if test -n "$JAVA_HOME"; then JAVA="$JAVA_HOME/bin/java" - AC_MSG_RESULT($JAVA) else AC_CHECK_PROGS(JAVA, java kaffe guavac) fi @@ -1232,10 +1272,8 @@ else fi if test -z "$JAVACBIN"; then - if test -x "$JAVA_HOME/bin/javac"; then - AC_MSG_CHECKING(for javac) + if test -n "$JAVA_HOME"; then JAVAC="$JAVA_HOME/bin/javac" - AC_MSG_RESULT($JAVAC) else AC_CHECK_PROGS(JAVAC, javac) fi @@ -1248,8 +1286,8 @@ AC_ARG_WITH(javaincl, [ --with-javaincl=path Set location of Java include di JAVAINC="" if test -z "$JAVAINCDIR" ; then - if test -r "$JAVA_HOME/include/jni.h"; then - JAVAINCDIR="$JAVA_HOME/include" + if test -n "$JAVA_HOME"; then + JAVAINCDIR="$JAVA_HOME_INCDIR" JAVAINC=-I\"$JAVAINCDIR\" else JAVAINCDIR="/usr/j2sdk*/include /usr/local/j2sdk*/include /usr/jdk*/include /usr/local/jdk*/include /opt/j2sdk*/include /opt/jdk*/include /usr/java/include /usr/java/j2sdk*/include /usr/java/jdk*/include /usr/local/java/include /opt/java/include /usr/include/java /usr/local/include/java /usr/lib/java/include /usr/lib/jvm/java*/include /usr/lib64/jvm/java*/include /usr/include/kaffe /usr/local/include/kaffe /usr/include" @@ -1257,7 +1295,7 @@ if test -z "$JAVAINCDIR" ; then # Add in default installation directory on Windows for Cygwin case $host in *-*-cygwin* | *-*-mingw*) JAVAINCDIR="c:/Program*Files*/Java/jdk*/include d:/Program*Files*/Java/jdk*/include c:/j2sdk*/include d:/j2sdk*/include c:/jdk*/include d:/jdk*/include $JAVAINCDIR";; - *-*-darwin*) JAVAINCDIR="/System/Library/Frameworks/JavaVM.framework/Headers $JAVAINCDIR";; + *-*-darwin*) JAVAINCDIR="$JAVA_OSX_STD_INCDIR $JAVAINCDIR";; *);; esac @@ -1350,6 +1388,8 @@ if test -n "$JAVAC"; then JAVAC=\"$JAVAC\" fi +# Turned off due to spurious warnings in later versions of openjdk-1.8 +# JAVAFLAGS=-Xcheck:jni AC_SUBST(JAVA) AC_SUBST(JAVAC) @@ -1360,15 +1400,16 @@ AC_SUBST(JAVALIBRARYPREFIX) AC_SUBST(JAVASO) AC_SUBST(JAVALDSHARED) AC_SUBST(JAVACXXSHARED) +AC_SUBST(JAVAFLAGS) AC_SUBST(JAVACFLAGS) #---------------------------------------------------------------- # Look for Javascript #---------------------------------------------------------------- -AC_ARG_WITH(javascript, AS_HELP_STRING([--without-javascript], [Disable Javascript]), [with_javascript="$withval"], [with_javascript=yes]) +AC_ARG_WITH(javascript, AS_HELP_STRING([--without-javascript], [Disable Javascript]), [with_javascript="$withval"], [with_javascript="$alllang_default"]) # First, check for "--without-javascript" or "--with-javascript=no". -if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then +if test x"${with_javascript}" = xno; then AC_MSG_NOTICE([Disabling Javascript]) JAVASCRIPT= else @@ -1396,7 +1437,7 @@ else # Look for Node.js which is the default Javascript engine #---------------------------------------------------------------- - AC_CHECK_PROGS(NODEJS, node) + AC_CHECK_PROGS(NODEJS, [nodejs node]) if test -n "$NODEJS"; then # node-gyp is needed to run the test-suite/examples @@ -1412,14 +1453,14 @@ else # check for include files AC_MSG_CHECKING(for JavaScriptCore/JavaScript.h) - AC_ARG_WITH(jscoreinc, [ --with-jscinc=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) + AC_ARG_WITH(jscoreinc, [ --with-jscinc=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) JSCOREVERSION= if test -z "$JSCOREINCDIR"; then JSCOREINCDIR="/usr/include/ /usr/local/include/" - # Add in default directory for JavaScriptCore headers for Linux and MacOSX + # Add in default directory for JavaScriptCore headers for Linux and Mac OS X case $host in *-*-linux*) JSCOREINCDIR="/usr/include/webkit-1.0/ /usr/include/webkitgtk-1.0/ /usr/local/include/webkit-1.0/JavaScriptCore/ $JSCOREINCDIR" @@ -1446,7 +1487,7 @@ else fi # check for JavaScriptCore/Webkit libraries - AC_ARG_WITH(jscorelib,[ --with-jsclib =path Set location of the JavaScriptCore/Webkit library directory],[JSCORELIB="-L$withval"], [JSCORELIB=]) + AC_ARG_WITH(jscorelib,[ --with-jsclib=path Set location of the JavaScriptCore/Webkit library directory],[JSCORELIB="-L$withval"], [JSCORELIB=]) if test -z "$JSCORELIB" -a -n "$PKGCONFIG"; then AC_MSG_CHECKING(for JavaScriptCore/Webkit library) @@ -1470,11 +1511,11 @@ else # check for include files AC_MSG_CHECKING(for V8 Javascript v8.h) - AC_ARG_WITH(jsv8inc, [ --with-jsv8inc=path Set location of Javascript v8 include directory], [JSV8INCDIR="$withval"]) + AC_ARG_WITH(jsv8inc, [ --with-jsv8inc=path Set location of Javascript v8 include directory], [JSV8INCDIR="$withval"]) # if not include dir is specified we try to find if test -z "$JSV8INCDIR"; then - # Add in default directory for JavaScriptCore headers for Linux and MacOSX + # Add in default directory for JavaScriptCore headers for Linux and Mac OS X case $host in *-*-linux*) JSV8INCDIR="/usr/include /usr/local/include/ $JSV8INCDIR" @@ -1503,7 +1544,7 @@ else # check for V8 library AC_MSG_CHECKING(for V8 Javascript library) - AC_ARG_WITH(jsv8lib,[ --with-jsv8lib=path Set location of V8 Javascript library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) + AC_ARG_WITH(jsv8lib,[ --with-jsv8lib=path Set location of V8 Javascript library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) v8libdirs="$JSV8LIBDIR /usr/lib64/ /usr/local/lib64/ /usr/lib/ /usr/local/lib/" for d in $v8libdirs ; do @@ -1558,11 +1599,11 @@ AC_SUBST(NODEGYP) #---------------------------------------------------------------- AC_ARG_WITH(gcj, AS_HELP_STRING([--without-gcj], [Disable GCJ]) -AS_HELP_STRING([--with-gcj=path], [Set location of gcj executable]),[GCJBIN="$withval"], [GCJBIN=yes]) +AS_HELP_STRING([--with-gcj=path], [Set location of gcj executable]),[GCJBIN="$withval"], [GCJBIN="$alllang_default"]) AC_ARG_WITH(gcjh, [ --with-gcjh=path Set location of gcjh executable],[GCJHBIN="$withval"], [GCJHBIN=]) # First, check for "--without-gcj" or "--with-gcj=no". -if test x"${GCJBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${GCJBIN}" = xno; then AC_MSG_NOTICE([Disabling GCJ]) else if test "x$GCJBIN" = xyes; then @@ -1586,13 +1627,13 @@ AC_SUBST(GCJH) #---------------------------------------------------------------- AC_ARG_WITH(android, AS_HELP_STRING([--without-android], [Disable Android]) -AS_HELP_STRING([--with-android=path], [Set location of android executable]),[ANDROIDBIN="$withval"], [ANDROIDBIN=yes]) -AC_ARG_WITH(adb, [ --with-adb=path Set location of adb executable - Android Debug Bridge],[ADBBIN="$withval"], [ADBBIN=]) -AC_ARG_WITH(ant, [ --with-ant=path Set location of ant executable for Android],[ANTBIN="$withval"], [ANTBIN=]) -AC_ARG_WITH(ndk-build, [ --with-ndk-build=path Set location of Android ndk-build executable],[NDKBUILDBIN="$withval"], [NDKBUILDBIN=]) +AS_HELP_STRING([--with-android=path], [Set location of android executable]),[ANDROIDBIN="$withval"], [ANDROIDBIN="$alllang_default"]) +AC_ARG_WITH(adb, [ --with-adb=path Set location of adb executable - Android Debug Bridge],[ADBBIN="$withval"], [ADBBIN=]) +AC_ARG_WITH(ant, [ --with-ant=path Set location of ant executable for Android],[ANTBIN="$withval"], [ANTBIN=]) +AC_ARG_WITH(ndk-build, [ --with-ndk-build=path Set location of Android ndk-build executable],[NDKBUILDBIN="$withval"], [NDKBUILDBIN=]) # First, check for "--without-android" or "--with-android=no". -if test x"${ANDROIDBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${ANDROIDBIN}" = xno; then AC_MSG_NOTICE([Disabling Android]) ANDROID= else @@ -1635,16 +1676,16 @@ GUILE_CFLAGS= GUILE_LIBS= AC_ARG_WITH(guile-config, AS_HELP_STRING([--without-guile], [Disable Guile]) - AS_HELP_STRING([--with-guile-config=path], [Set location of guile-config]),[ GUILE_CONFIG="$withval"], [GUILE_CONFIG=]) +AS_HELP_STRING([--with-guile-config=path], [Set location of guile-config]),[ GUILE_CONFIG="$withval"], [GUILE_CONFIG=]) AC_ARG_WITH(guile,[ --with-guile=path Set location of Guile executable],[ - GUILE="$withval"], [GUILE=yes]) + GUILE="$withval"], [GUILE="$alllang_default"]) AC_ARG_WITH(guile-cflags,[ --with-guile-cflags=cflags Set cflags required to compile against Guile],[ GUILE_CFLAGS="$withval"]) AC_ARG_WITH(guile-libs,[ --with-guile-libs=ldflags Set ldflags needed to link with Guile],[ GUILE_LIBS="$withval"]) # First, check for "--without-guile" or "--with-guile=no". -if test x"${GUILE}" = xno -o x"${with_alllang}" = xno ; then +if test x"${GUILE}" = xno; then AC_MSG_NOTICE([Disabling Guile]) else if test -z "$GUILE_CONFIG" ; then @@ -1697,11 +1738,11 @@ AC_SUBST(GUILE_LIBS) #---------------------------------------------------------------- AC_ARG_WITH(mzscheme, AS_HELP_STRING([--without-mzscheme], [Disable MzScheme]) -AS_HELP_STRING([--with-mzscheme=path], [Set location of MzScheme executable]),[ MZSCHEMEBIN="$withval"], [MZSCHEMEBIN=yes]) +AS_HELP_STRING([--with-mzscheme=path], [Set location of MzScheme executable]),[ MZSCHEMEBIN="$withval"], [MZSCHEMEBIN="$alllang_default"]) AC_ARG_WITH(mzc, AS_HELP_STRING([--with-mzc=path], [Set location of MzScheme's mzc]), [ MZCBIN="$withval"], [MZCBIN=]) # First, check for "--without-mzscheme" or "--with-mzscheme=no". -if test x"${MZSCHEMEBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${MZSCHEMEBIN}" = xno; then AC_MSG_NOTICE([Disabling MzScheme]) MZC= else @@ -1741,11 +1782,11 @@ AC_SUBST(MZDYNOBJ) RUBYBIN= AC_ARG_WITH(ruby, AS_HELP_STRING([--without-ruby], [Disable Ruby]) -AS_HELP_STRING([--with-ruby=path], [Set location of Ruby executable]),[ RUBYBIN="$withval"], [RUBYBIN=yes]) +AS_HELP_STRING([--with-ruby=path], [Set location of Ruby executable]),[ RUBYBIN="$withval"], [RUBYBIN="$alllang_default"]) # First, check for "--without-ruby" or "--with-ruby=no". RUBYSO=$SO -if test x"${RUBYBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${RUBYBIN}" = xno; then AC_MSG_NOTICE([Disabling Ruby]) RUBY= else @@ -1762,6 +1803,7 @@ AC_MSG_CHECKING(for Ruby header files) if test -n "$RUBY"; then # Try Ruby1.9+ first RUBYDIR=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["rubyhdrdir"]] || $rubyhdrdir') 2>/dev/null` + RUBYARCHHDRDIR=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["rubyarchhdrdir"]] || $rubyarchhdrdir') 2>/dev/null` if test x"$RUBYDIR" = x"" || test x"$RUBYDIR" = x"nil"; then RUBYDIR=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["archdir"]] || $archdir') 2>/dev/null` else @@ -1774,6 +1816,8 @@ if test -n "$RUBY"; then if test -r $i/ruby.h; then if test x"$RUBYARCH" = x""; then RUBYINCLUDE="-I$i" + elif test -n "$RUBYARCHHDRDIR"; then + RUBYINCLUDE="-I$i -I$RUBYARCHHDRDIR" else RUBYINCLUDE="-I$i -I$i/$RUBYARCH" fi @@ -1788,9 +1832,10 @@ if test -n "$RUBY"; then # Find library and path for linking. AC_MSG_CHECKING(for Ruby library) RUBYLIB="" + rb_archlibdir=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["archlibdir"]]') 2>/dev/null` rb_libdir=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["libdir"]]') 2>/dev/null` rb_bindir=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["bindir"]]') 2>/dev/null` - dirs="$dirs $rb_libdir $rb_bindir" + dirs="$dirs $rb_archlibdir $rb_libdir $rb_bindir" rb_libruby=`($RUBY -rrbconfig -e 'print RbConfig::CONFIG[["LIBRUBY_A"]]') 2>/dev/null` RUBYLINK=`($RUBY -rrbconfig -e ' @@ -1863,37 +1908,83 @@ AC_SUBST(RUBYSO) AC_SUBST(RUBYDYNAMICLINKING) #------------------------------------------------------------------------- -# Look for PHP +# Look for PHP5 +#------------------------------------------------------------------------- + +PHP5BIN= + +AC_ARG_WITH(php5, AS_HELP_STRING([--without-php5], [Disable PHP5]) +AS_HELP_STRING([--with-php5=path], [Set location of PHP5 executable]),[ PHP5BIN="$withval"], [PHP5BIN="$alllang_default"]) + +# First, check for "--without-php5" or "--with-php5=no". +if test x"${PHP5BIN}" = xno; then + AC_MSG_NOTICE([Disabling PHP5]) + PHP5= +else + if test "x$PHP5BIN" = xyes; then + AC_CHECK_PROGS(PHP5, [php5 php]) + else + PHP5=$PHP5BIN + fi + + AC_MSG_CHECKING(for PHP5 header files) + dnl /usr/bin/php5 -> /usr/bin/php-config5 + case $PHP5 in + *5) + PHP5CONFIG=`echo "$PHP5"|sed 's/5$/-config5/'` ;; + *) + PHP5CONFIG=$PHP5-config ;; + esac + php5_version=`$PHP5CONFIG --version 2>/dev/null` + case $php5_version in + 5*) + PHP5INC=`$PHP5CONFIG --includes 2>/dev/null` + if test -n "$PHP5INC"; then + AC_MSG_RESULT($PHP5INC) + else + AC_MSG_RESULT(not found) + fi + ;; + "") + AC_MSG_RESULT([could not find $PHP5CONFIG or obtain PHP5 version from it]) ;; + *) + AC_MSG_RESULT([found PHP $php_version - not PHP 5]) ;; + esac +fi +AC_SUBST(PHP5) +AC_SUBST(PHP5INC) + +#------------------------------------------------------------------------- +# Look for PHP7 #------------------------------------------------------------------------- PHPBIN= AC_ARG_WITH(php, AS_HELP_STRING([--without-php], [Disable PHP]) -AS_HELP_STRING([--with-php=path], [Set location of PHP executable]),[ PHPBIN="$withval"], [PHPBIN=yes]) +AS_HELP_STRING([--with-php=path], [Set location of PHP executable]),[ PHPBIN="$withval"], [PHPBIN="$alllang_default"]) # First, check for "--without-php" or "--with-php=no". -if test x"${PHPBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${PHPBIN}" = xno; then AC_MSG_NOTICE([Disabling PHP]) PHP= else - if test "x$PHPBIN" = xyes; then - AC_CHECK_PROGS(PHP, [php5 php]) + AC_CHECK_PROGS(PHP, [php7.1 php7.0 php]) else PHP=$PHPBIN fi AC_MSG_CHECKING(for PHP header files) - dnl /usr/bin/php5 -> /usr/bin/php-config5 + dnl /usr/bin/php7.0 -> /usr/bin/php-config7.0 case $PHP in - *5) - PHPCONFIG=`echo "$PHP"|sed 's/5$/-config5/'` ;; + *7.*) + PHPCONFIG=`echo "$PHP"|sed 's/7\...*$/-config&/'` ;; *) PHPCONFIG=$PHP-config ;; esac php_version=`$PHPCONFIG --version 2>/dev/null` case $php_version in - 5*) + 7.*) PHPINC=`$PHPCONFIG --includes 2>/dev/null` if test -n "$PHPINC"; then AC_MSG_RESULT($PHPINC) @@ -1901,8 +1992,10 @@ else AC_MSG_RESULT(not found) fi ;; + "") + AC_MSG_RESULT([could not find $PHPCONFIG or obtain PHP version from it]) ;; *) - AC_MSG_RESULT([found PHP $version, but only PHP 5 is supported]) ;; + AC_MSG_RESULT([found PHP $php_version - not PHP 7]) ;; esac fi AC_SUBST(PHP) @@ -1912,7 +2005,7 @@ AC_SUBST(PHPINC) # Look for ocaml #---------------------------------------------------------------- -AC_ARG_WITH(ocaml, AS_HELP_STRING([--without-ocaml], [Disable OCaml]), [with_ocaml="$withval"], [with_ocaml=yes]) +AC_ARG_WITH(ocaml, AS_HELP_STRING([--without-ocaml], [Disable OCaml]), [with_ocaml="$withval"], [with_ocaml="$alllang_default"]) AC_ARG_WITH(ocamlc,[ --with-ocamlc=path Set location of ocamlc executable],[ OCAMLC="$withval"], [OCAMLC=]) AC_ARG_WITH(ocamldlgen,[ --with-ocamldlgen=path Set location of ocamldlgen],[ OCAMLDLGEN="$withval" ], [OCAMLDLGEN=]) AC_ARG_WITH(ocamlfind,[ --with-ocamlfind=path Set location of ocamlfind],[OCAMLFIND="$withval"],[OCAMLFIND=]) @@ -1920,33 +2013,33 @@ AC_ARG_WITH(ocamlmktop,[ --with-ocamlmktop=path Set location of ocamlmktop exe AC_ARG_WITH(camlp4,[ --with-camlp4=path Set location of camlp4 executable],[ CAMLP4="$withval"], [CAMLP4=]) # First, check for "--without-ocaml" or "--with-ocaml=no". -if test x"${with_ocaml}" = xno -o x"${with_alllang}" = xno ; then +if test x"${with_ocaml}" = xno; then AC_MSG_NOTICE([Disabling OCaml]) OCAMLC= else AC_MSG_CHECKING(for Ocaml DL load generator) if test -z "$OCAMLDLGEN"; then - AC_CHECK_PROGS(OCAMLDLGEN, ocamldlgen, :) + AC_CHECK_PROGS(OCAMLDLGEN, ocamldlgen) fi AC_MSG_CHECKING(for Ocaml package tool) if test -z "$OCAMLFIND"; then - AC_CHECK_PROGS(OCAMLFIND, ocamlfind, :) + AC_CHECK_PROGS(OCAMLFIND, ocamlfind) fi AC_MSG_CHECKING(for Ocaml compiler) if test -z "$OCAMLC"; then - AC_CHECK_PROGS(OCAMLC, ocamlc, :) + AC_CHECK_PROGS(OCAMLC, ocamlc) fi AC_MSG_CHECKING(for Ocaml toplevel creator) if test -z "$OCAMLMKTOP"; then - AC_CHECK_PROGS(OCAMLMKTOP, ocamlmktop, :) + AC_CHECK_PROGS(OCAMLMKTOP, ocamlmktop) fi AC_MSG_CHECKING(for Ocaml Pre-Processor-Pretty-Printer) if test -z "$CAMLP4"; then - AC_CHECK_PROGS(CAMLP4, camlp4, :) + AC_CHECK_PROGS(CAMLP4, camlp4) fi fi # Disabling ocaml @@ -1964,10 +2057,10 @@ AC_SUBST(CAMLP4) # Priority: configure option, automatic search PIKEBIN= AC_ARG_WITH(pike, AS_HELP_STRING([--without-pike], [Disable Pike]) -AS_HELP_STRING([--with-pike=path], [Set location of Pike executable]),[PIKEBIN="$withval"], [PIKEBIN=yes]) +AS_HELP_STRING([--with-pike=path], [Set location of Pike executable]),[PIKEBIN="$withval"], [PIKEBIN="$alllang_default"]) # First, check for "--without-pike" or "--with-pike=no". -if test x"${PIKEBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${PIKEBIN}" = xno; then AC_MSG_NOTICE([Disabling Pike]) PIKEBIN= else @@ -2034,10 +2127,10 @@ CHICKENLIB= AC_ARG_WITH(chicken, AS_HELP_STRING([--without-chicken], [Disable CHICKEN]) -AS_HELP_STRING([--with-chicken=path], [Set location of CHICKEN executable]),[ CHICKENBIN="$withval"], [CHICKENBIN=yes]) +AS_HELP_STRING([--with-chicken=path], [Set location of CHICKEN executable]),[ CHICKENBIN="$withval"], [CHICKENBIN="$alllang_default"]) # First, check for "--without-chicken" or "--with-chicken=no". -if test x"${CHICKENBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${CHICKENBIN}" = xno; then AC_MSG_NOTICE([Disabling CHICKEN]) else @@ -2128,12 +2221,12 @@ AC_SUBST(CHICKENSHAREDLIB) # Look for C# #---------------------------------------------------------------- -AC_ARG_WITH(csharp, AS_HELP_STRING([--without-csharp], [Disable CSharp]), [with_csharp="$withval"], [with_csharp=yes]) +AC_ARG_WITH(csharp, AS_HELP_STRING([--without-csharp], [Disable CSharp]), [with_csharp="$withval"], [with_csharp="$alllang_default"]) AC_ARG_WITH(cil-interpreter, [ --with-cil-interpreter=path Set location of CIL interpreter for CSharp],[CSHARPBIN="$withval"], [CSHARPBIN=]) AC_ARG_WITH(csharp-compiler, [ --with-csharp-compiler=path Set location of CSharp compiler],[CSHARPCOMPILERBIN="$withval"], [CSHARPCOMPILERBIN=]) # First, check for "--without-csharp" or "--with-csharp=no". -if test x"${with_csharp}" = xno -o x"${with_alllang}" = xno ; then +if test x"${with_csharp}" = xno; then AC_MSG_NOTICE([Disabling CSharp]) CSHARPCOMPILER= else @@ -2251,14 +2344,14 @@ LUALINK= # LUABIN will be cleared if certain dependencies cannot be found AC_ARG_WITH(lua, AS_HELP_STRING([--without-lua], [Disable Lua]) -AS_HELP_STRING([--with-lua=path], [Set location of Lua executable]),[ LUABIN="$withval"], [LUABIN=yes]) +AS_HELP_STRING([--with-lua=path], [Set location of Lua executable]),[ LUABIN="$withval"], [LUABIN="$alllang_default"]) AC_ARG_WITH(luaincl,[ --with-luaincl=path Set location of Lua include directory],[ LUAINCLUDE="$withval"], [LUAINCLUDE=]) AC_ARG_WITH(lualib,[ --with-lualib=path Set location of Lua library directory],[ LUALIB="$withval"], [LUALIB=]) # First, check for "--without-lua" or "--with-lua=no". -if test x"${LUABIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${LUABIN}" = xno; then AC_MSG_NOTICE([Disabling Lua]) else @@ -2269,7 +2362,7 @@ if test "x$LUABIN" = xyes; then # The search order should match the include-file and library search # orders below (a Lua shared library built for one version may not # work with a Lua binary of a different version). - AC_PATH_PROGS(LUABIN, [lua5.2 lua5.1 lua]) + AC_PATH_PROGS(LUABIN, [lua5.4 lua5.3 lua5.2 lua5.1 lua]) fi # check version: we need Lua 5.x @@ -2312,7 +2405,10 @@ if test "$LUABIN"; then AC_CHECK_FILE($LUAINCLUDE/lua.h,[LUAFLAGS="$ISYSTEM$LUAINCLUDE"],[LUABIN=]) else LUA_OK="1" - AC_CHECK_HEADER(lua.h,[LUAFLAGS=""],[LUA_OK=""]) + CFLAGS_SAVED=$CFLAGS + CFLAGS= # Use empty CFLAGS to avoid failure: "present but cannot be compiled" + AC_CHECK_HEADER([lua.h],[LUAFLAGS=""],[LUA_OK=""]) + CFLAGS=$CFLAGS_SAVED # if we didn't get it, going to have to look elsewhere (the hard way) if test -z "$LUA_OK"; then AC_MSG_CHECKING(for lua.h in other locations) @@ -2320,7 +2416,7 @@ if test "$LUABIN"; then # The ordering of the include directories to search should match # the ordering of libraries to search in the library test below. inc=/usr/include - dirs="$inc/lua5.2 $inc/lua5.1 $inc/lua51 $inc/lua5.0 $inc/lua50 /usr/local/include" + dirs="$inc/lua5.4 $inc/lua5.3 $inc/lua5.2 $inc/lua5.1 $inc/lua51 $inc/lua5.0 $inc/lua50 /usr/local/include" for i in $dirs; do #echo "$i" if test -r $i/lua.h; then @@ -2343,7 +2439,7 @@ if test "$LUABIN"; then if test -n "$LUALIB"; then AC_CHECK_FILE($LUALIB/liblua.a,[LUALINK="-L$LUALIB -llua"],[LUABIN=]) else - AC_SEARCH_LIBS(lua_close, [lua lua5.2 lua5.1 lua51 lua5.0 lua50], [LUALINK="-l$ac_lib"],[LUABIN=]) + AC_SEARCH_LIBS(lua_close, [lua lua5.4 lua5.3 lua5.2 lua5.1 lua51 lua5.0 lua50], [LUALINK="-l$ac_lib"],[LUABIN=]) fi # adding lualib for lua 5.0 @@ -2368,10 +2464,10 @@ AC_SUBST(LUABIN) ALLEGROCLBIN= AC_ARG_WITH(allegrocl, AS_HELP_STRING([--without-allegrocl], [Disable Allegro CL]) -AS_HELP_STRING([--with-allegrocl=path], [Set location of Allegro CL executable (alisp)]),[ ALLEGROCLBIN="$withval"], [ALLEGROCLBIN=yes]) +AS_HELP_STRING([--with-allegrocl=path], [Set location of Allegro CL executable (alisp)]),[ ALLEGROCLBIN="$withval"], [ALLEGROCLBIN="$alllang_default"]) # First, check for "--without-allegrocl" or "--with-allegrocl=no". -if test x"${ALLEGROCLBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${ALLEGROCLBIN}" = xno; then AC_MSG_NOTICE([Disabling Allegro CL]) ALLEGROCLBIN= else @@ -2391,10 +2487,10 @@ AC_SUBST(ALLEGROCLBIN) CLISPBIN= AC_ARG_WITH(clisp, AS_HELP_STRING([--without-clisp], [Disable CLISP]) -AS_HELP_STRING([--with-clisp=path], [Set location of CLISP executable (clisp)]),[ CLISPBIN="$withval"], [CLISPBIN=yes]) +AS_HELP_STRING([--with-clisp=path], [Set location of CLISP executable (clisp)]),[ CLISPBIN="$withval"], [CLISPBIN="$alllang_default"]) # First, check for "--without-clisp" or "--with-clisp=no". -if test x"${CLISPBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${CLISPBIN}" = xno; then AC_MSG_NOTICE([Disabling CLISP]) CLISPBIN= else @@ -2414,10 +2510,10 @@ AC_SUBST(CLISPBIN) RBIN= AC_ARG_WITH(r, AS_HELP_STRING([--without-r], [Disable R]) -AS_HELP_STRING([--with-r=path], [Set location of R executable (r)]),[ RBIN="$withval"], [RBIN=yes]) +AS_HELP_STRING([--with-r=path], [Set location of R executable (r)]),[ RBIN="$withval"], [RBIN="$alllang_default"]) # First, check for "--without-r" or "--with-r=no". -if test x"${RBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${RBIN}" = xno; then AC_MSG_NOTICE([Disabling R]) RBIN= else @@ -2435,9 +2531,9 @@ AC_SUBST(RBIN) #---------------------------------------------------------------- AC_ARG_WITH(go, AS_HELP_STRING([--without-go], [Disable Go]) -AS_HELP_STRING([--with-go=path], [Set location of Go compiler]),[GOBIN="$withval"], [GOBIN=yes]) +AS_HELP_STRING([--with-go=path], [Set location of Go compiler]),[GOBIN="$withval"], [GOBIN="$alllang_default"]) -if test x"${GOBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${GOBIN}" = xno; then AC_MSG_NOTICE([Disabling Go]) GO= GOC= @@ -2482,8 +2578,8 @@ else esac AC_MSG_CHECKING([whether go version is too old]) case $go_version in - go1.0* | go1 ) - AC_MSG_RESULT([yes - minimum version is 1.1]) + go1.1* | go1.0* | go1 ) + AC_MSG_RESULT([yes - minimum version is 1.2]) GO= GOOPT="-intgosize 32" ;; @@ -2560,13 +2656,13 @@ AC_SUBST(GOVERSIONOPTION) # Look for D #---------------------------------------------------------------- -AC_ARG_WITH(d, AS_HELP_STRING([--without-d], [Disable D]), [with_d="$withval"], [with_d=yes]) +AC_ARG_WITH(d, AS_HELP_STRING([--without-d], [Disable D]), [with_d="$withval"], [with_d="$alllang_default"]) AC_ARG_WITH(d1-compiler, [ --with-d1-compiler=path Set location of D1/Tango compiler (DMD compatible)],[D1COMPILERBIN="$withval"], [D1COMPILERBIN=]) AC_ARG_WITH(d2-compiler, [ --with-d2-compiler=path Set location of D2 compiler (DMD compatible)],[D2COMPILERBIN="$withval"], [D2COMPILERBIN=]) # First, check for "--without-d" or "--with-d=no". -if test x"${with_d}" = xno -o x"${with_alllang}" = xno ; then +if test x"${with_d}" = xno; then AC_MSG_NOTICE([Disabling D]) D1COMPILER= D2COMPILER= @@ -2718,6 +2814,13 @@ fi AC_SUBST(SKIP_PHP) +SKIP_PHP5= +if test -z "$PHP5" || test -z "$PHP5INC" ; then + SKIP_PHP5="1" +fi +AC_SUBST(SKIP_PHP5) + + SKIP_OCAML= if test -z "$OCAMLC" ; then SKIP_OCAML="1" @@ -2835,6 +2938,16 @@ AC_SUBST(SKIP_ANDROID) ABS_SRCDIR=`(cd ${srcdir} && pwd)` +dnl Under Cygwin, we may need native absolute path as it is used by SWIG, which +dnl may be a native, and not a Cygwin, program (this is the case when it's +dnl built using MinGW or cccl compiler in Cygwin environment). However it may, +dnl although this is probably more rare, also be built as a Cygwin program. +dnl Using "mixed" path like we do here allows the path to work in both cases. +case $host in + *-*-mingw* ) ABS_SRCDIR=`${srcdir}/Tools/convertpath -m $ABS_SRCDIR` ;; + *-*-cygwin* ) ABS_SRCDIR=`cygpath --mixed $ABS_SRCDIR` ;; +esac + # Root directory ROOT_DIR=`pwd` case $host in @@ -2861,25 +2974,34 @@ AC_SUBST(ac_aux_dir) AC_ARG_WITH(swiglibdir,[ --with-swiglibdir=DIR Put SWIG system-independent libraries into DIR.], [swig_lib="$withval"], [swig_lib="${datadir}/swig/${PACKAGE_VERSION}"]) -AC_SUBST(swig_lib) +SWIG_LIB_INSTALL=${swig_lib} +AC_SUBST(SWIG_LIB_INSTALL) AC_DEFINE_DIR(SWIG_LIB, swig_lib, [Directory for SWIG system-independent libraries]) case $build in - # Windows does not understand unix directories. Convert into a windows directory with drive letter. - *-*-mingw*) SWIG_LIB_WIN_UNIX=`cmd //c echo $SWIG_LIB | sed -e "s/[ ]*$//"`;; # This echo converts unix to mixed paths. Then zap unexpected trailing space. - *-*-cygwin*) SWIG_LIB_WIN_UNIX=`cygpath --mixed "$SWIG_LIB"`;; - *) SWIG_LIB_WIN_UNIX="";; + # Windows does not understand unix directories. Convert into a windows directory with drive letter. + *-*-mingw*) SWIG_LIB_WIN_UNIX=`${srcdir}/Tools/convertpath -m $SWIG_LIB`;; + *-*-cygwin*) SWIG_LIB_WIN_UNIX=`cygpath --mixed "$SWIG_LIB"`;; + *) SWIG_LIB_WIN_UNIX="";; esac AC_DEFINE_UNQUOTED(SWIG_LIB_WIN_UNIX, ["$SWIG_LIB_WIN_UNIX"], [Directory for SWIG system-independent libraries (Unix install on native Windows)]) -# For testing - Windows builds of SWIG do not need SWIG_LIB set -AC_EGREP_CPP([yes], -[#ifdef _WIN32 - yes -#endif -], [SWIG_LIB_PREINST=], [SWIG_LIB_PREINST=$ABS_SRCDIR/Lib]) +SWIG_LIB_PREINST=$ABS_SRCDIR/Lib AC_SUBST(SWIG_LIB_PREINST) +dnl For testing purposes, clear SWIG_LIB when building SWIG in the source +dnl directory under Windows because it is supposed to work without SWIG_LIB +dnl being set. Otherwise it always needs to be set. +SWIG_LIB_SET="env SWIG_LIB=\$(SWIG_LIB_DIR)" +if test "${srcdir}" = "."; then + AC_EGREP_CPP([yes], + [#ifdef _WIN32 + yes + #endif + ], [SWIG_LIB_SET="env SWIG_LIB="], []) +fi +AC_SUBST(SWIG_LIB_SET) + AC_CONFIG_FILES([ Makefile swig.spec @@ -2898,6 +3020,7 @@ AC_CONFIG_FILES([ Examples/test-suite/octave/Makefile Examples/test-suite/perl5/Makefile Examples/test-suite/php/Makefile + Examples/test-suite/php5/Makefile Examples/test-suite/pike/Makefile Examples/test-suite/python/Makefile Examples/test-suite/ruby/Makefile @@ -2931,7 +3054,7 @@ AC_CONFIG_COMMANDS([Examples],[ for mkfile in `cd ${srcdir} && find Examples/ -type f -name Makefile`; do dir=`dirname ${mkfile}` d=${dir} - reldir=""; + reldir="" while test "x$d" != "x." ; do d=`dirname $d` reldir="${reldir}../" @@ -2941,6 +3064,7 @@ AC_CONFIG_COMMANDS([Examples],[ cat <${mkfile} # DO NOT EDIT: instead edit ${relsrcdir}${mkfile} # and run (cd ${reldir} && ./config.status) to regenerate +TOP_BUILDDIR_TO_TOP_SRCDIR = ${srcdir}/ SRCDIR = ${relsrcdir}${dir}/ EOF @@ -2971,6 +3095,7 @@ test -n "$SKIP_OCAML" || langs="${langs}ocaml " test -n "$SKIP_OCTAVE" || langs="${langs}octave " test -n "$SKIP_PERL5" || langs="${langs}perl5 " test -n "$SKIP_PHP" || langs="${langs}php " +test -n "$SKIP_PHP5" || langs="${langs}php5 " test -n "$SKIP_PIKE" || langs="${langs}pike " test -n "$SKIP_PYTHON" || langs="${langs}python " test -n "$SKIP_R" || langs="${langs}r " diff --git a/debian/README b/debian/README deleted file mode 100644 index 9cbe96a3c..000000000 --- a/debian/README +++ /dev/null @@ -1,20 +0,0 @@ -The Debian Package swig1.3 --------------------------- - -This is SWIG 1.3 (Simplified Wrapper and Interface Generator) -packaged for Debian GNU/Linux. - -SWIG 1.3 is not fully compatible with SWIG 1.1. It is a re-development -effort of SWIG 1.1 (which was written in C++) in ANSI C. The 1.3 -series is in "alpha" state. Release 1.3a5 was rather stable, and it -should be used for new projects rather than the ancient release -1.1p5. See the file `NEW' for information on the new features of the -1.3 series. - -This Debian package derives from the release 1.3a5 and corresponds to -the "mkoeppe-1-3-a5-patches" branch of the SWIG CVS repository. It -fixes several bugs and enhances several language backends. See the -top of the file `CHANGES' for details. - - -Matthias Koeppe , Mon, 28 May 2001 15:08:55 +0200 diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index da43b40e9..000000000 --- a/debian/changelog +++ /dev/null @@ -1,66 +0,0 @@ -swig1.3 (1.3.pnet) unstable; urgency=low - - * Support for dotgnu pnet under debian - - -- James Michael DuPont Wed, 12 Mar 2003 20:55:53 +0200 - -swig1.3 (1.3.a5+patches-9) unstable; urgency=low - - * New upstream version - - -- Matthias Koeppe Wed, 6 Jun 2001 16:11:41 +0200 - -swig1.3 (1.3.a5+patches-8) unstable; urgency=low - - * New upstream version - - -- Matthias Koeppe Wed, 6 Jun 2001 14:06:51 +0200 - -swig1.3 (1.3.a5+patches-7) unstable; urgency=low - - * New upstream version - - -- Matthias Koeppe Wed, 6 Jun 2001 13:34:44 +0200 - -swig1.3 (1.3.a5+patches-6) unstable; urgency=low - - * New upstream version - - -- Matthias Koeppe Tue, 5 Jun 2001 14:11:52 +0200 - -swig1.3 (1.3.a5+patches-5) unstable; urgency=low - - * New upstream version. - - -- Matthias Koeppe Fri, 1 Jun 2001 18:48:59 +0200 - -swig1.3 (1.3.a5+patches-4) unstable; urgency=low - - * Fix hard-coded location of swig library. Added build-dependency on - tcl-dev. - - -- Matthias Koeppe Fri, 1 Jun 2001 13:32:34 +0200 - -swig1.3 (1.3.a5+patches-3) unstable; urgency=low - - * New upstream version - - -- Matthias Koeppe Thu, 31 May 2001 13:15:20 +0200 - -swig1.3 (1.3.a5+patches-2) unstable; urgency=low - - * Binary and manpage now include version number, to improve - cooperation with the "swig" package. - - -- Matthias Koeppe Tue, 29 May 2001 15:15:07 +0200 - -swig1.3 (1.3.a5+patches-1) unstable; urgency=low - - * First release. - - -- Matthias Koeppe Sat, 20 Nov 1999 01:09:11 +0100 - -Local variables: -mode: debian-changelog -add-log-mailing-address: "mkoeppe@mail.math.uni-magdeburg.de" -End: \ No newline at end of file diff --git a/debian/control b/debian/control deleted file mode 100644 index 80e0a7017..000000000 --- a/debian/control +++ /dev/null @@ -1,18 +0,0 @@ -Source: swig1.3 -Section: interpreters -Priority: optional -Maintainer: Matthias Koeppe -Build-Depends: debhelper (>> 3.0.0), libguile-dev, python-dev, perl, - ruby-dev, ruby, tcl8.0-dev -Standards-Version: 3.5.2 - -Package: swig1.3 -Architecture: any -Depends: ${shlibs:Depends} -Description: Generate scripting interfaces to C/C++ code - SWIG (Simplified Wrapper and Interface Generator) is a system for - automatically generating wrapper/glue code for several languages - (Tcl, Python, Perl, Ruby, MzScheme, Guile, Java) from annotated C or - C++ header files. - This package represents some point in the SWIG 1.3 development - series. It is not fully compatible with the SWIG 1.1 release. diff --git a/debian/copyright b/debian/copyright deleted file mode 100644 index 8cb86922e..000000000 --- a/debian/copyright +++ /dev/null @@ -1,83 +0,0 @@ -This is SWIG, written and maintained by: - - Dave Beazley (beazley@cs.uchicago.edu) (SWIG core) - Loic Dachary (loic@ceic.com) (Perl5) - Harco de Hilster (Harco.de.Hilster@ATComputing.nl) (Java) - Thien-Thi Nguyen (ttn@glug.org) (Testing/Misc) - Masaki Fukushima (fukusima@goto.info.waseda.ac.jp) (Ruby) - Matthias Koeppe (mkoeppe@mail.math.uni-magdeburg.de) (Guile/MzScheme) - -Past contributors: - - Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran Kovuk, Gary Holt, - David Fletcher, Oleg Tolmatcev. - -SWIG can be obtained by anonymous CVS: - - cvs -d :pserver:cvs@swig.cs.uchicago.edu:/cvsroot co SWIG - -SWIG is distributed under the following terms: - -I. - -Copyright (C) 1998-2000 -The University of Chicago - -Permission is hereby granted, without written agreement and without -license or royalty fees, to use, copy, modify, and distribute this -software and its documentation for any purpose, provided that -(1) The above copyright notice and the following two paragraphs -appear in all copies of the source code and (2) redistributions -including binaries reproduces these notices in the supporting -documentation. Substantial modifications to this software may be -copyrighted by their authors and need not follow the licensing terms -described here, provided that the new terms are clearly indicated in -all files where they apply. - -IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CHICAGO, OR -DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT, -INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF -THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE AUTHORS OR -ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. - -THE AUTHOR AND THE UNIVERSITY OF CHICAGO SPECIFICALLY DISCLAIM ANY -WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE -PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE AUTHORS AND -DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, -UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - - -II. - -Copyright (c) 1995-1998 -The University of Utah and the Regents of the University of California -All Rights Reserved - -Permission is hereby granted, without written agreement and without -license or royalty fees, to use, copy, modify, and distribute this -software and its documentation for any purpose, provided that -(1) The above copyright notice and the following two paragraphs -appear in all copies of the source code and (2) redistributions -including binaries reproduces these notices in the supporting -documentation. Substantial modifications to this software may be -copyrighted by their authors and need not follow the licensing terms -described here, provided that the new terms are clearly indicated in -all files where they apply. - -IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE -UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY -PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, -EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH -SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND -THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, -SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - - diff --git a/debian/dirs b/debian/dirs deleted file mode 100644 index 587d58405..000000000 --- a/debian/dirs +++ /dev/null @@ -1,4 +0,0 @@ -usr/bin -usr/lib -#usr/share/swig1.3-pnet -#usr/share/doc/swig1.3-pnet diff --git a/debian/docs b/debian/docs deleted file mode 100644 index 9e310ea30..000000000 --- a/debian/docs +++ /dev/null @@ -1,47 +0,0 @@ -README -TODO -ANNOUNCE -CHANGES -NEW -Doc/Devel/engineering.html -Doc/Devel/index.html -Doc/Devel/internals.html -Doc/Devel/migrate.txt -Doc/README -Doc/Manual/About.html -Doc/Manual/Advanced.html -Doc/Manual/Arguments.html -Doc/Manual/Chicken.html -Doc/Manual/Contents.html -Doc/Manual/Copyright.html -Doc/Manual/Customization.html -Doc/Manual/Documentation.html -Doc/Manual/Extending.html -Doc/Manual/Guile.html -Doc/Manual/Introduction.html -Doc/Manual/Java.html -Doc/Manual/Library.html -Doc/Manual/Ocaml.html -Doc/Manual/Perl5.html -Doc/Manual/Php.html -Doc/Manual/Preface.html -Doc/Manual/Preprocessor.html -Doc/Manual/Python.html -Doc/Manual/README -Doc/Manual/Ruby.html -Doc/Manual/SWIG.html -Doc/Manual/SWIGPlus.html -Doc/Manual/Scripting.html -Doc/Manual/Tcl.html -Doc/Manual/Typemaps.html -Doc/Manual/Varargs.html -Doc/Manual/Warnings.html -Doc/Manual/Windows.html -Doc/Manual/ch11.1.png -Doc/Manual/ch11.2.png -Doc/Manual/ch11.3.png -Doc/Manual/ch12.1.png -Doc/Manual/ch2.1.png -Doc/Manual/ch9.table.2.png -Doc/Manual/chapters -Doc/Manual/index.html diff --git a/debian/postinst b/debian/postinst deleted file mode 100644 index 164b5ff1a..000000000 --- a/debian/postinst +++ /dev/null @@ -1,45 +0,0 @@ -#! /bin/sh -# postinst script for swig1.3 -# -# see: dh_installdeb(1) - -set -e - -# summary of how this script can be called: -# * `configure' -# * `abort-upgrade' -# * `abort-remove' `in-favour' -# -# * `abort-deconfigure' `in-favour' -# `removing' -# -# for details, see /usr/share/doc/packaging-manual/ -# -# quoting from the policy: -# Any necessary prompting should almost always be confined to the -# post-installation script, and should be protected with a conditional -# so that unnecessary prompting doesn't happen if a package's -# installation fails and the `postinst' is called with `abort-upgrade', -# `abort-remove' or `abort-deconfigure'. - -case "$1" in - configure) - - ;; - - abort-upgrade|abort-remove|abort-deconfigure) - - ;; - - *) - echo "postinst called with unknown argument \`$1'" >&2 - exit 0 - ;; -esac - -# dh_installdeb will replace this with shell code automatically -# generated by other debhelper scripts. - -#DEBHELPER# - -exit 0 diff --git a/debian/rules b/debian/rules deleted file mode 100755 index 1fafed902..000000000 --- a/debian/rules +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/make -f -# Sample debian/rules that uses debhelper. -# GNU copyright 1997 to 1999 by Joey Hess. - -# Uncomment this to turn on verbose mode. -export DH_VERBOSE=1 - -# This is the debhelper compatability version to use. -export DH_COMPAT=3 - -configure: configure-stamp -configure-stamp: - dh_testdir - ./autogen-debian.sh - ./configure --prefix=/usr --mandir=/usr/share/man --with-swiglibdir=/usr/share/swig1.3 --program-suffix=-1.3 - touch configure-stamp - -build: configure-stamp build-stamp -build-stamp: - dh_testdir - $(MAKE) - $(MAKE) runtime - touch build-stamp - -clean: - dh_testdir - dh_testroot - rm -f build-stamp configure-stamp - - -$(MAKE) clean - - dh_clean - -install: build - dh_testdir - dh_testroot - dh_clean -k - dh_installdirs - $(MAKE) install DESTDIR=$(CURDIR)/debian/swig1.3 - -# Build architecture-independent files here. -binary-indep: build install -# We have nothing to do by default. - -# Build architecture-dependent files here. -binary-arch: build install - dh_testdir - dh_testroot -# dh_installdebconf - dh_installdocs - dh_installexamples - dh_installmenu -# dh_installlogrotate -# dh_installemacsen -# dh_installpam -# dh_installmime -# dh_installinit -# dh_installcron - dh_installman - dh_installinfo - dh_undocumented swig-1.3.1 -# dh_installchangelogs CHANGES - dh_link - dh_strip - dh_compress - dh_fixperms - dh_makeshlibs - dh_installdeb -# dh_perl - dh_shlibdeps - dh_gencontrol - dh_md5sums - dh_builddeb - -binary: binary-indep binary-arch -.PHONY: build clean binary-indep binary-arch binary install configure diff --git a/debian/substvars b/debian/substvars deleted file mode 100644 index c9df68ba1..000000000 --- a/debian/substvars +++ /dev/null @@ -1 +0,0 @@ -shlibs:Depends=libc6 (>= 2.2.3-1), libstdc++2.10-glibc2.2 diff --git a/preinst-swig.in b/preinst-swig.in old mode 100755 new mode 100644 index e77db7858..ac00602bb --- a/preinst-swig.in +++ b/preinst-swig.in @@ -1,5 +1,9 @@ #!/bin/sh -builddir=`dirname $0` -SWIG_LIB=@SWIG_LIB_PREINST@ + +# Convenience script for running SWIG before it is installed. +# Intended for ad-hoc usage and not by the test-suite or examples. + +builddir=`dirname "$0"` +SWIG_LIB='@SWIG_LIB_PREINST@' export SWIG_LIB exec "$builddir/swig" "$@"