diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..596615322 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +.gitattributes export-ignore +.gitignore export-ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..e94087e29 --- /dev/null +++ b/.gitignore @@ -0,0 +1,197 @@ +# Compiled Source +*.o +*.class + +# Editor files and various other junk +.*.sw? +*.bak +*.log +.DS_Store + +# Local PCRE +pcre +*.gz + +# C/C++ object files, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.slo +*.lo + +# C/C++ dynamic libraries, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.dll +*.so +*.so.* +*.dylib +*.bundle + +# C/C++ static libraries, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.lib +*.lai +*.la +*.a + +# C/C++ executables, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.exe +*.out +*.app + +# Generated by autogen.sh +CCache/autom4te.cache/ +CCache/config.h.in +CCache/configure +Source/Include/swigconfig.h.in +Source/Include/swigconfig.h.in~ +Source/Makefile.in +Tools/config/compile +Tools/config/config.guess +Tools/config/config.sub +Tools/config/depcomp +Tools/config/install-sh +Tools/config/missing +Tools/config/ylwrap +aclocal.m4 +autom4te.cache/ +configure + +# Generated by ./configure +CCache/Makefile +CCache/ccache_swig_config.h +CCache/config.h +CCache/config.log +CCache/config.status +Examples/Makefile +Examples/d/example.mk +Examples/guile/Makefile +Examples/test-suite/*/Makefile +Examples/xml/Makefile +/Makefile +Source/Include/stamp-h1 +Source/Include/swigconfig.h +Source/Makefile +Tools/javascript/Makefile +.deps +config.log +config.status +preinst-swig +swig.spec + +# Build Artifacts +.dirstamp +CCache/ccache-swig +Lib/swigwarn.swg +Source/CParse/parser.c +Source/CParse/parser.h +Source/eswig +Source/TAGS +swig +Tools/javascript/javascript + +# Generated documentation +Doc/Manual/SWIGDocumentation.html +Doc/Manual/SWIGDocumentation.pdf +Doc/Manual/*.book + +# SWIG common generated files +*_wrap.c +*_wrap.cpp +*_wrap.cxx +*_wrap.h +*-gypcopy.cxx + +# Scratch directories +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# +Examples/test-suite/csharp/*/ +*runme.exe.mdb +*runme.exe +Examples/csharp/*/*.cs +!Examples/csharp/*/runme.cs + +# D +Examples/test-suite/d/*/ +Examples/d/**/example.d +Examples/d/**/example_im.d +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 + +# Java +Examples/test-suite/java/*/ +Examples/java/*/*.java +!Examples/java/*/runme.java + +# Javascript +Examples/test-suite/javascript/*/ +*.gyp + +# Octave +swigexample*.oct +Examples/test-suite/octave/*.oct + +# Perl5 +Examples/test-suite/perl5/*.pm +Examples/perl5/*/*.pm + +# PHP +Examples/test-suite/php/php_*.h +Examples/test-suite/php/*.php +!Examples/test-suite/php/*runme.php +!Examples/test-suite/php/skel.php +Examples/php/*/php_*.h +Examples/php/*/example.php + +# Python +# Based on https://github.com/github/gitignore/blob/master/Python.gitignore +*.py[cod] +*/__pycache__/ +/__pycache__/ +Examples/test-suite/python/*.py +!Examples/test-suite/python/*runme.py +Examples/python/*/example.py +Examples/python/**/bar.py +Examples/python/**/base.py +Examples/python/**/foo.py +Examples/python/**/spam.py + +# R +Examples/test-suite/r/*.R +Examples/test-suite/r/*.Rout +!Examples/test-suite/r/*runme.R +Examples/r/*/example.R +Examples/r/*/*.Rout +Examples/r/*/.RData + +# Scilab +Examples/test-suite/scilab/*/ +loader.sce + diff --git a/.project b/.project deleted file mode 100644 index 86af75213..000000000 --- a/.project +++ /dev/null @@ -1,11 +0,0 @@ - - - SWIG - - - - - - - - diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..6bf3e3c37 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,206 @@ +language: cpp +matrix: + include: + - compiler: clang + os: linux + env: SWIGLANG= + - compiler: gcc + os: linux + env: SWIGLANG= + - os: linux + env: SWIGLANG= SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 + - os: linux + env: SWIGLANG= SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP14=1 + - compiler: gcc + os: linux + env: SWIGLANG=csharp + - compiler: gcc + os: linux + env: SWIGLANG=d + - compiler: gcc + os: linux + env: SWIGLANG=go + - compiler: gcc + os: linux + env: SWIGLANG=guile + - compiler: gcc + os: linux + env: SWIGLANG=java + - compiler: gcc + os: linux + env: SWIGLANG=javascript ENGINE=node + - compiler: gcc + os: linux + env: SWIGLANG=javascript ENGINE=jsc + - compiler: gcc + os: linux + env: SWIGLANG=javascript ENGINE=v8 + - compiler: gcc + os: linux + env: SWIGLANG=lua + - compiler: gcc + os: linux + env: SWIGLANG=octave SWIGJOBS=-j2 # 3.2 + - compiler: gcc + os: linux + env: SWIGLANG=octave SWIGJOBS=-j2 VER=3.8 + - compiler: gcc + os: linux + env: SWIGLANG=octave SWIGJOBS=-j2 VER=4.0 + - compiler: gcc + os: linux + env: SWIGLANG=perl5 + - compiler: gcc + os: linux + env: SWIGLANG=php + - compiler: gcc + os: linux + env: SWIGLANG=python VER=2.4 + - compiler: gcc + os: linux + env: SWIGLANG=python VER=2.5 + - compiler: gcc + os: linux + env: SWIGLANG=python VER=2.6 + - compiler: gcc + os: linux + env: SWIGLANG=python # 2.7 + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 # 3.2 + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.3 + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.4 + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.5 + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.5 + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-O + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-classic + - compiler: gcc + os: linux + env: SWIGLANG=r + - compiler: gcc + os: linux + env: SWIGLANG=ruby + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.3.0 + - compiler: gcc + os: linux + env: SWIGLANG=scilab + - compiler: gcc + os: linux + env: SWIGLANG=tcl + - os: linux + env: SWIGLANG=csharp SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 + - os: linux + env: SWIGLANG=java SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 + - os: linux + env: SWIGLANG=python SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 + - os: osx + env: SWIGLANG= SWIG_CC=gcc-4.2 SWIG_CXX=g++-4.2 + - 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=php + - 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 + # Not quite working yet + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-O +before_install: + - date -u + - uname -a + - if test "$TRAVIS_OS_NAME" = "linux"; then lscpu && cat /proc/cpuinfo | grep "model name" && cat /proc/meminfo | grep MemTotal; fi + - if test "$TRAVIS_OS_NAME" = "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 +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' + - make -s $SWIGJOBS + - ./swig -version && ./swig -pcreversion + - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi + - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi + - 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 825837614..b06aa53d2 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,31 +1,37 @@ -*** ANNOUNCE: SWIG 2.0.6 (30 April 2012) *** +*** ANNOUNCE: SWIG 3.0.9 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-2.0.6, the latest SWIG release. +We're pleased to announce SWIG-3.0.9, the latest SWIG release. What is SWIG? ============= SWIG is a software development tool that reads C/C++ header files and generates the wrapper code needed to make C and C++ code accessible -from other languages including Perl, Python, Tcl, Ruby, PHP, Java, -Scheme (Guile, MzScheme, CHICKEN), D, Ocaml, Lua, Pike, C#, Modula-3, -Octave, R, Common Lisp (CLISP, Allegro CL, CFFI, UFFI). SWIG can also -export its parse tree in the form of XML and Lisp s-expressions. Major -applications of SWIG include generation of scripting language extension -modules, rapid prototyping, testing, and user interface development for -large C/C++ systems. +from other programming languages including Perl, Python, Tcl, Ruby, +PHP, C#, Go, Java, Javascript, Lua, Scheme (Guile, MzScheme, CHICKEN), +D, Ocaml, Pike, Modula-3, Octave, R, Scilab, Common Lisp (CLISP, +Allegro CL, CFFI, UFFI). SWIG can also export its parse tree in +the form of XML and Lisp s-expressions. Major applications of SWIG +include generation of scripting language extension modules, rapid +prototyping, testing, and user interface development for large +C/C++ systems. + +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-2.0.6.tar.gz + http://prdownloads.sourceforge.net/swig/swig-3.0.9.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-2.0.6.zip + http://prdownloads.sourceforge.net/swig/swigwin-3.0.9.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 d8f9042fe..67fd3f363 100644 --- a/CCache/Makefile.in +++ b/CCache/Makefile.in @@ -14,7 +14,7 @@ NOSOFTLINKSTEST= CC=@CC@ CFLAGS=@CFLAGS@ -I. SWIG=swig -SWIG_LIB=../../Lib +SWIG_LIB=../$(srcdir)/../Lib EXEEXT=@EXEEXT@ # Use standard autoconf approach to transform executable name using --program-prefix and --program-suffix @@ -27,38 +27,44 @@ HEADERS = ccache.h mdfour.h all: $(PACKAGE_NAME)$(EXEEXT) +# Regenerate Makefile if Makefile.in or config.status have changed. +Makefile: $(srcdir)/Makefile.in ./config.status + $(SHELL) ./config.status + # Note that HTML documentation is actually generated and used from the main SWIG documentation Makefile -docs: $(PACKAGE_NAME).1 web/ccache-man.html +docs: $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/ccache-man.html $(PACKAGE_NAME)$(EXEEXT): $(OBJS) $(HEADERS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) -$(PACKAGE_NAME).1: ccache.yo - -yodl2man -o $(PACKAGE_NAME).1 ccache.yo +$(srcdir)/$(PACKAGE_NAME).1: $(srcdir)/ccache.yo + -yodl2man -o $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/ccache.yo -web/ccache-man.html: ccache.yo - yodl2html -o web/ccache-man.html ccache.yo +$(srcdir)/web/ccache-man.html: $(srcdir)/ccache.yo + yodl2html -o $(srcdir)/web/ccache-man.html $(srcdir)/ccache.yo -install: $(PACKAGE_NAME)$(EXEEXT) $(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 + ${INSTALLCMD} -m 644 $(srcdir)/$(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 -uninstall: $(PACKAGE_NAME)$(EXEEXT) $(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: /bin/rm -f $(OBJS) *~ $(PACKAGE_NAME)$(EXEEXT) -check : test - test: test.sh - SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' ./test.sh + SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' $(srcdir)/test.sh check: test @@ -67,11 +73,11 @@ distclean: clean /bin/rm -rf autom4te.cache maintainer-clean: distclean - /bin/rm -f $(PACKAGE_NAME).1 web/ccache-man.html + /bin/rm -f $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/ccache-man.html + - # FIXME: To fix this, test.sh needs to be able to take ccache from the # installed prefix, not from the source dir. -installcheck: +installcheck: @echo "WARNING! This is not really \"installcheck\" yet." $(MAKE) check diff --git a/CCache/ccache.c b/CCache/ccache.c index d1696da88..e7dd1d30a 100644 --- a/CCache/ccache.c +++ b/CCache/ccache.c @@ -712,12 +712,13 @@ static void from_cache(int first) passfail = retrieve_from_cache(hashname, output_file, hardlink); } - free(stderr_file); if (passfail == -1) { close(fd_stderr); unlink(stderr_file); + free(stderr_file); return; } + free(stderr_file); } /* get rid of the intermediate preprocessor file */ diff --git a/CCache/ccache.h b/CCache/ccache.h index 668ce8288..dcbb03f0c 100644 --- a/CCache/ccache.h +++ b/CCache/ccache.h @@ -159,7 +159,7 @@ int asprintf(char **ptr, const char *format, ...); int snprintf(char *,size_t ,const char *, ...); #endif -void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize); +void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize, size_t minfiles); void cleanup_all(const char *dir); void wipe_all(const char *dir); @@ -200,6 +200,8 @@ typedef int (*COMPAR_FN_T)(const void *, const void *); /* mkstemp() on some versions of cygwin don't handle binary files, so override */ +/* Seems okay in Cygwin 1.7.0 #ifdef __CYGWIN__ #undef HAVE_MKSTEMP #endif +*/ diff --git a/CCache/cleanup.c b/CCache/cleanup.c index 99312283e..f54ee54d9 100644 --- a/CCache/cleanup.c +++ b/CCache/cleanup.c @@ -75,21 +75,40 @@ static void traverse_fn(const char *fname, struct stat *st) /* sort the files we've found and delete the oldest ones until we are below the thresholds */ -static void sort_and_clean(void) +static void sort_and_clean(size_t minfiles) { unsigned i; + size_t adjusted_minfiles = minfiles; if (num_files > 1) { /* sort in ascending data order */ qsort(files, num_files, sizeof(struct files *), (COMPAR_FN_T)files_compare); } + /* ensure newly cached files (minfiles) are kept - instead of matching + the filenames of those newly cached, a faster and simpler approach + assumes these are the most recent in the cache and if any other + cached files have an identical time stamp, they will also be kept - + this approach would not be needed if the cleanup was done at exit. */ + if (minfiles != 0 && minfiles < num_files) { + unsigned minfiles_index = num_files - minfiles; + time_t minfiles_time = files[minfiles_index]->mtime; + for (i=1; i<=minfiles_index; i++) { + if (files[minfiles_index-i]->mtime == minfiles_time) + adjusted_minfiles++; + else + break; + } + } /* delete enough files to bring us below the threshold */ for (i=0;ifname) != 0 && errno != ENOENT) { fprintf(stderr, "unlink %s - %s\n", files[i]->fname, strerror(errno)); @@ -103,7 +122,7 @@ static void sort_and_clean(void) } /* cleanup in one cache subdir */ -void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize) +void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize, size_t minfiles) { unsigned i; @@ -117,7 +136,7 @@ void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize) traverse(dir, traverse_fn); /* clean the cache */ - sort_and_clean(); + sort_and_clean(minfiles); stats_set_sizes(dir, total_files, total_size); @@ -151,7 +170,8 @@ void cleanup_all(const char *dir) cleanup_dir(dname, counters[STATS_MAXFILES], - counters[STATS_MAXSIZE]); + counters[STATS_MAXSIZE], + 0); free(dname); free(sfile); } diff --git a/CCache/configure.in b/CCache/configure.ac similarity index 100% rename from CCache/configure.in rename to CCache/configure.ac diff --git a/CCache/stats.c b/CCache/stats.c index 92bc4a835..d2122bcd3 100644 --- a/CCache/stats.c +++ b/CCache/stats.c @@ -168,7 +168,8 @@ static void stats_update_size(enum stats stat, size_t size, size_t numfiles) if (need_cleanup) { char *p = dirname(stats_file); - cleanup_dir(p, counters[STATS_MAXFILES], counters[STATS_MAXSIZE]); + cleanup_dir(p, counters[STATS_MAXFILES], counters[STATS_MAXSIZE], + numfiles); free(p); } } diff --git a/CCache/test.sh b/CCache/test.sh index 9581c85e3..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.$$ @@ -142,7 +147,7 @@ basetests() { testname="non-regular" mkdir testd $CCACHE_COMPILE -o testd -c test1.c > /dev/null 2>&1 - rmdir testd + rm -rf testd checkstat 'output to a non-regular file' 1 testname="no-input" @@ -315,7 +320,7 @@ swigtests() { testname="non-regular" mkdir testd $CCACHE_COMPILE -o testd -java testswig1.i > /dev/null 2>&1 - rmdir testd + rm -rf testd checkstat 'output to a non-regular file' 1 testname="no-input" @@ -402,6 +407,29 @@ swigtests() { rm -rf $TESTDIR mkdir $TESTDIR cd $TESTDIR || exit 1 + +unset CCACHE_DIR +unset CCACHE_TEMPDIR +unset CCACHE_LOGFILE +unset CCACHE_VERBOSE +unset CCACHE_PATH +unset CCACHE_CC +unset CCACHE_PREFIX +unset CCACHE_DISABLE +unset CCACHE_READONLY +unset CCACHE_CPP2 +unset CCACHE_NOCOMPRESS +unset CCACHE_NOSTATS +unset CCACHE_NLEVELS +unset CCACHE_HARDLINK +unset CCACHE_RECACHE +unset CCACHE_UMASK +unset CCACHE_HASHDIR +unset CCACHE_UNIFY +unset CCACHE_EXTENSION +unset CCACHE_STRIPC +unset CCACHE_SWIG + CCACHE_DIR="ccache dir" # with space in directory name (like Windows default) mkdir "$CCACHE_DIR" export CCACHE_DIR diff --git a/CCache/util.c b/CCache/util.c index bba232492..66f9823b9 100644 --- a/CCache/util.c +++ b/CCache/util.c @@ -82,7 +82,7 @@ void copy_fd(int fd_in, int fd_out) #ifndef HAVE_MKSTEMP /* cheap and nasty mkstemp replacement */ -static int mkstemp(char *template) +int mkstemp(char *template) { mktemp(template); return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600); diff --git a/CHANGES b/CHANGES index 70af78333..198230775 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,2010 @@ 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.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) +========================== + +2015-07-02: wsfulton + Fix syntax error when the template keyword is used in types, eg: + + std::template vector v; + +2015-07-02: ngladitz + [Lua] Push characters as unformatted 1-character strings to avoid + unprintable characters such as (char)127 being converted to + "<\127>" with Lua 5.3 and later. (github PR #452) + +2015-06-29: olly + [Python] Improve handling of whitespace in %pythoncode. + + Previously SWIG looked at the indentation of the first line and + removed that many characters from each subsequent line, regardless + of what those characters were. This was made worse because SWIG's + preprocessor removes any whitespace before a '#'. Fixes github + issue #379, reported by Joe Orton. + +2015-06-12: wsfulton + [R] Fix #430 - call to SWIG_createNewRef in copyToC was incorrectly named. + +2015-06-11: sghirate + [C#] Patch #427 adds in new command line option -outfile to combine all the + generated C# code into a single file. + +2015-06-09: wsfulton + Fix seg fault processing C++11 type aliasing. Issue #424. + +2015-05-28: wsfulton + [Python] Add new feature "python:cdefaultargs" to control default argument + code generation. By default, SWIG attempts to convert C/C++ default argument values + into Python values and generates code into the Python layer with these values. + Recent versions of SWIG are able to convert more of these values, however, the + new behaviour can be circumvented if desired via this new feature, such that + the default argument values are obtained from the C layer and not the Python layer. + For example: + + struct CDA { + int fff(int a = 1, bool b = false); + }; + + The default code generation in the Python layer is: + + class CDA(_object): + ... + def fff(self, a=1, b=False): + return _default_args.CDA_fff(self, a, b) + + Adding the feature: + + %feature("python:cdefaultargs") CDA::fff; + + Results in: + + class CDA(_object): + ... + def fff(self, *args): + return _default_args.CDA_fff(self, *args) + + Some code generation modes, eg -builtin and -fastproxy, are unaffected by this as + the default values are always obtained from the C layer. + +2015-05-27: wsfulton + [Python] Deal with an integer as the default value of a typedef to bool + parameter in the C++ prototype. See #327. Regression from 3.0.0 onwards. + +2015-05-19: olly + [Python] Fix warning when compiling generated code with MSVC. + (Fixes https://sourceforge.net/p/swig/patches/351/ reported by + Mateusz Szymaski). + +2015-05-14: wsfulton + Fix seg fault wrapping shared_ptr of classes with private constructors and destructors. + This also fixes the "unref" feature when used on classes with private destructors. + +2015-05-10: wsfulton + [Java] Fix multi-argument typemaps (char *STRING, size_t LENGTH) + so that they can be applied to a wider range of types. Fixes #385. + +2015-05-07: olly + [Python] Deal with an integer as the default value of a bool + parameter in the C++ prototype. Fixes github #327, reported by + Greg Allen. + +2015-05-07: LindleyF + [Java] Allow feature("director") and feature("ref") to be used + together. Github PR#403. + +2015-05-05: olly + Suppress warning 325 "Nested class not currently supported (Foo + ignored)" when Foo has already been explicitly ignored with "%ignore". + +2015-05-04: wsfulton + Add support for friend templates, including operator overloading - fixes #196. Considering + the example below, previously the operator gave a syntax error and friendfunc incorrectly + warned with: + + "Warning 503: Can't wrap 'friendfunc<(Type)>' unless renamed to a valid identifier." + + template class MyClass { + friend int friendfunc (double is, MyClass & x); + friend int operator<< (double un, const MyClass &x); + }; + + The following also previously incorrectly warned with: + + "Warning 302: Identifier 'template_friend' redefined (ignored)," + + template T template_friend(T); + struct MyTemplate { + template friend T template_friend(T); + }; + +2015-05-01: wsfulton + Fix handling of conversion operators where the operator is split over multiple + lines or has comments within the operator type. Fixes #401. + + Also fix similar problem with normal operators which gave a syntax error if split over + multiple lines or had a comment within the operator declaration. + +2015-04-30: olly + Ignore unknown preprocessor directives which are inside an inactive + conditional (github issue #394, reported by Dan Wilcox). + Regression introduced in 3.0.3. + +2015-04-27: vadz + [Python] Fix "default" typemap used after an argument with "numinputs=0" (#377). + +2015-04-24: wsfulton + [Python] Fix #256. Code generated with '-builtin -modernargs' segfaults for any + method taking zero arguments. + + Also fixes: "SystemError: error return without exception set" during error checking + when using just -builtin and the incorrect number of arguments is passed to a class + method expecting zero arguments. + +2015-04-23: wsfulton + [Java] Bug #386 - Memory leak fix in (char *STRING, size_t LENGTH) typemaps. + +2015-04-23: vadz + [Python] Make "default" typemap work again (#330, #377). + +2015-04-23: vadz + [Python] Fix the use of default values for the pointer types (#365, #376). + +2015-04-23: wsfulton + Fix 'make check-ccache' which is part of 'make check' when one of the CCACHE_ + environment variables, for example CCACHE_DISABLE, is set. + +2015-04-14: wsfulton + Clearer warning message for badly constructed typecheck typemaps. For example, was: + + example.i:3: Warning 467: Overloaded foo(int) not supported (no type checking + rule for 'int'). + + Now: + + example.i:3: Warning 467: Overloaded foo(int) not supported (incomplete type checking + rule - no precedence level in typecheck typemap for 'int'). + +2015-04-11: wsfulton + [Java] Fix #353 - Linker multiple definition of 'ExceptionMatches' when + using directors and multiple modules. + +2015-04-11: wsfulton + Merge #320 - Make __dict__ accessible for Python builtin classes. + +2015-04-07: wsfulton + Fix #375 - parsing of extern "C" and typedef for example: + extern "C" typedef void (*Hook2_t)(int, const char *); + extern "C" typedef int Integer; + +2015-03-12: olly + -DSWIG_DIRECTOR_STATIC is now supported for all languages with + director support, not only Python and PHP. + +2015-03-02: ianlancetaylor + [Go] Add -cgo option, required for Go versions 1.5 and + later. + +2015-02-26: olly + Fix segmentation fault when top==NULL, introduced by nested class + handling (reported in issue#346 by Pawe Tomulik). + +2015-02-09: wsfulton + [Guile] Fix generated code for static const char member variables when + defined and declared inline. + +2015-02-09: mishas + [Go] Fix %import of files in sub directories. + +2015-02-05: ianlancetaylor + [Go] Ignore Go specific type maps (goin, goout, etc.) if they are empty. + +2015-02-05: ianlancetaylor + [Go] Generated Go code no longer calls _swig_goallocate or + _swig_makegostring, as they will no longer work as of Go 1.5. + +Version 3.0.5 (31 Jan 2015) +=========================== + +2015-01-30: wsfulton + [Python] Fix Python -classic and property setting. Setting properties on classic classes + was broken in swig-3.0.3 by attempting to use __setattr__. This regression is fixed now + by using __dict__ again when using -classic. + Fixes patch #232. + +2015-01-27: smarchetto + [Scilab] Support for the Scilab language has been added + +2015-01-23: olly + [PHP] When wrapping a returned resource as an object, check if all + cases wrap it in the same class, and if so eliminate the pointless + switch statement wrapper we previously generated. + +2015-01-22: wsfulton + [Octave] Merge patch #297 for SF bug #1277 - Octave shared_ptr support + +2015-01-15: wsfulton + [Python] Merge patch #250 - Fixes for using %constant and objects (non-primitive types) + +2015-01-15: wsfulton + [C# Go] Merge patch #308 and fix #307 - C++11 strongly typed enum support + in directors + +2015-01-15: wsfulton + [Python] Second fix for #294 #296 - Regression introduced in SWIG-3.0.3 when + wrapping functions with default arguments, this time when using kwargs. + +Version 3.0.4 (14 Jan 2015) +=========================== + +2015-01-12: olly + [PHP] Fix segfault in director upcall check when using PHP built with + ZTS enabled. Fixes #155, reported by Pierre Labastie. + +2015-01-12: vadz + [Python] Fix #294 #296 - Regression introduced in SWIG-3.0.3 when + wrapping functions with default arguments. Invalid or missing default + arguments were sometimes being generated into the python layer. + +2015-01-08: olly + Allow C++11 "explicit constexpr". Fixes github issue #284 reported + by Pawel Tomulik. Also handle "constexpr explicit" and "constexpr + static". + +2015-01-08: olly + When reporting an error for a construct which hasn't been + terminated when the end of the file is reached, report it at the + start line rather than "EOF" as then tools like editors and IDEs + will take you to a generally more useful place for fixing the + problem. + +2015-01-08: olly + Improve error messages for a few cases which previously gave the + one of the cryptic catch-all errors "Syntax error in input". + +2015-01-08: olly + Provide -cppext as a general command line option for setting the + extension used for generated C++ files (previously it was specific + to the PHP backend). Deprecate the equivalent -suffix option + provided by the Ocaml backend, but continue to support that for + now. + +Version 3.0.3 (30 Dec 2014) +=========================== + +2014-12-27: wsfulton + Fix #280 - abort using all default template parameters within other template + parameters. + +2014-12-27: talby + [Perl] Issue #282 perl5 archlib vs archlibexp + [Perl] tidy "warning: duplicate 'extern' declaration specifier" when building generated code + under clang + +2014-12-18: wsfulton + Add support for %constant and structs/classes - issue #272 + +2014-12-09: wsfulton + Fix #245 - regression (since swig-3.0.0) in templated constructors. + Templated constructors could not be instantiated - they were incorrectly ignored with a warning 504: + "Function: xyz must have a return type. Ignored." + +2014-12-07: wsfulton + Add support for C++11 strongly typed enumerations. + +2014-11-21: wsfulton + [Java C#] Fix multiply defined error when using %rename of enum items when using the "simple enum" + wrappers. + +2014-10-28: vadz + [Python] Patch #201 The generated .py file no longer uses *args for all Python parameters. + Instead, the parameters are named using the C++ parameter names. + + "compactdefaultargs" feature can be enabled to restore the old behaviour. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-10-24: timotheecour + [D] Patch #204 Use core.atomic.atomicOp to mutate shared variables + +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. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-10-10: diorcety + [Python] Patch #232 Fix property access using directors + +2014-10-06: wsfulton + [Python] Fixes when using -builtin and std::vector/std::list wrappers to allow deletion + of single elements, such as 'del vec[0]'. + +2014-09-30: oliverb + [Javascript] Merge patch #216 by Richie765 - Added support for many versions of v8 javascript. + +2014-09-30: oliverb + [Javascript] Merge patch #195 by zittix - Fixed JSClassRef declaration not using the static one. + +2014-09-30: ianlancetaylor + [Go] In configure script, require Go 1.1 or later. + +2014-09-30: wsfulton + [Python] Patch #207 - Fix No module error with -relativeimport when using single + header file import. + +2014-09-27: wsfulton + Patch #208 - Initialise newly created array when using array_functions in the + carrays.i library (C++ usage). + +2014-09-27: wsfulton + [Ruby] Patch #187 - Fix crash on shutdown of the Ruby interpreter if more than one + module was loaded at a time when data is being shared between modules. + +2014-09-27: wsfulton + [Java] Patch #168 - Fix leak in Java director string handling after the Java + upcall when called from a native thread. + +2014-09-25: ianlancetaylor + [Go] Adjust generated code to work with upcoming Go 1.4 + release. + +2014-09-23: wsfulton + [Python] Add patch from Thomas Maslach to fix crash in wrappers when using -threads in + the STL iterators (SwigPyIterator destructor). + +2014-09-17: wsfulton + [C#] Merge patch #229 from contre - Add bool array types to arrays_csharp.i + +2014-09-12: olly + [PHP] Add support for specifying any PHP interfaces a wrapped class + implements, e.g.: %typemap("phpinterfaces") MyIterator "Iterator"; + +2014-09-11: olly + [PHP] Fix throwing a PHP exception through C++ from a subclassed + director method - PHP NULL gets returned by the subclassed method + in this case, so the directorout typemap needs to allow that (at + least if an exception is active). + +2014-09-09: ianlancetaylor + [Go] Add goargout typemap. + +2014-09-09: olly + [PHP] Fix segmentation faults with directors in PHP >= 5.4, and + reenable runme tests for director_basic testcase. Fix from + pavel-charvat in issue#164. + +2014-09-05: ianlancetaylor + [Go] Add imtype, goin, goout, godirectorin, and + godirectorout typemaps, to support writing Go code to + convert between types. + +2014-09-02: olly + [Python] Fix regression in indentation of python code produced with + -modern, introduced by changes in #188. Reported by fabiencastan + in #218. + +2014-09-01: olly + Issue an error for unknown SWIG preprocessor directives, rather + than quietly ignoring them. Reported by jrhelsey in issue#217. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-08-15: talby + [Perl] Include guard fix for nested modules from Anthony Heading (SF Patch #350). + +2014-08-04: wsfulton + [C#] Merge patch #200 from gpetrou - Changed CSharp license header to include auto-generated + tag so that StyleCop ignores the files. + +2014-08-04: wsfulton + [Java] Merge patch #198 from Yuval Kashtan - Support for java.nio.ByteBuffer mapping to + unsigned char * in various.i in NIOBUFFER typemaps. + +2014-07-14: ianlancetaylor + [Go] Change struct definition to use void *, not uint8, so + that the type is recorded as possibly containing + pointers. This ensures that the 1.3 garbage collector + does not collect pointers passed to C++ code. + +2014-07-01: wsfulton + Fix SF Bug #1375 - Expansion of the $parentclassname special variable incorrectly contains + brackets in the expanded name. + +Version 3.0.2 (4 Jun 2014) +========================== + +2014-06-02: v-for-vandal + [Lua] Pull request #176: + If class has no __eq implemented, then default __eq is generated. + Default __eq compares actual pointers stored inside Lua userdata. + +2014-06-02: vkalinin + Fix #183 - %extend and unnamed nested structs + +2014-05-28: kwwette + Fix install failure when using an 'out of source' build using the shipped + tarball - regression introduced in swig-3.0.1. + +2014-05-24: kwwette + [Octave] Remove deprecated -global/-noglobal command-line arguments + + *** POTENTIAL INCOMPATIBILITY *** + +Version 3.0.1 (27 May 2014) +=========================== + +2014-05-25: hfalcic + [Python] Python 3 byte string output: use errors="surrogateescape" + if available on the version of Python that's in use. This allows + obtaining the original byte string (and potentially trying a fallback + encoding) if the bytes can't be decoded as UTF-8. + + Previously, a UnicodeDecodeError would be raised with no way to treat + the data as bytes or try another codec. + +2014-05-18: vkalinin + Bug #175 - Restore %extend to work for unnamed nested structures by using a C + symbol comprising the outer structure name and unnamed variable instance name. + +2014-05-15: kwwette + Add #166 - 'make check' now works out of source. This required the examples to build + out of source. The main languages have been tested - C#, Go, Guile, Java, Javascript, + Lua, Octave, Perl, PHP, Python, Ruby and Tcl. + +2014-05-01: Oliver Buchtala + Javascript support added, see Javascript chapter in the documentation. + +2014-05-01: olly + [PHP] The generated __isset() method now returns true for read-only properties. + +2014-04-24: kwwette + [Go] Fix go ./configure parsing of gccgo --version, and + goruntime.swg typo in __GNUC_PATCHLEVEL__ (SF Bug #1298) + +2014-04-24: kwwette + Fix {python|perl5|ruby|tcl}/java examples + + In Lib/gcj/cni.i, for compatibility with newer gcj versions: + + - remove JvAllocObject() which gcj no longer defines, from gcj Changelog: + 2004-04-16 Bryce McKinlay + * gcj/cni.h (JvAllocObject): Remove these obsolete, + undocumented CNI calls. + + - change JvCreateJavaVM() argument from void* to JvVMInitArgs*, from gcj Changelog: + 2005-02-23 Thomas Fitzsimmons + PR libgcj/16923 + ... + (JvCreateJavaVM): Declare vm_args as JvVMInitArgs* rather than void*. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-04-08: wsfulton + SF Bug #1366 - Remove duplicate declarations of strtoimax and strtoumax in inttypes.i + +2014-04-08: wsfulton + [Java C#] Enums which have been ignored via %ignore and are subsequently + used are handled slightly differently. Type wrapper classes are now generated + which are effectively a wrapper of an empty enum. Previously in Java uncompilable + code was generated and in C# an int was used. + +2014-04-04: wsfulton + Fix regression in 3.0.0 where legal code following an operator<< definition might + give a syntax error. SF Bug #1365. + +2014-04-03: olly + [PHP] Fix wrapping director constructors with default parameters + with a ZTS-enabled build of PHP. + +2014-04-02: olly + [PHP] Pass the ZTS context we already have to avoid needing to + call TSRMLS_FETCH, which is relatively expensive. + +2014-04-02: olly + [PHP] Pass ZTS context through to t_output_helper() so it works + with a ZTS-enabled build of PHP. Reported by Pierre Labastie in + github PR#155. + +2014-03-28: wsfulton + [Java C# D Go] Fixes for C enums used in an API and the definition of the enum + has not been parsed. For D, this fixes a segfault in SWIG. The other languages + now produce code that compiles, although the definition of the enum is needed + in order to use the enum properly from the target language. + +2014-03-23: v-for-vandal + [Lua] Fix for usage of snprintf in Lua runtime which Visual Studio does not have. + +Version 3.0.0 (16 Mar 2014) +=========================== + +2014-03-16: wsfulton + C++11 support initially developed as C++0x support by Matevz Jekovec as a Google Summer of Code + project has been further extended. The C++11 support is comprehensive, but by no means complete + or without limitations. Full details for each new feature in C++11 is covered in the + CPlusPlus11.html chapter in the documentation which is included in SWIG and also available + online at http://www.swig.org/Doc3.0/CPlusPlus11.html. + +2014-03-14: v-for-vandal + [Lua] Numerous Lua improvements: + 1. %nspace support has been added. Namespaces are mapped to tables in the module, with the same + name as the C++ namespace. + 2. Inheritance is now handled differently. Each class metatable keeps a list of class bases instead + of merging all members of all bases into the derived class. + 3. The new metatables result in differences in accessing class members. For example: + + %module example + struct Test { + enum { TEST1 = 10, TEST2 = 20 }; + static const int ICONST = 12; + }; + + Now this can be used as follows: + print(example.Test.TEST1) + print(example.Test.ICONST) + The old way was: + print(example.Test_TEST1) + print(example.Test_ICONST) + + 4. The special class metatable member ".constructor" was removed. Now SWIG generates the proxy + function by itself and assigns it directly to the class table "__call" method. + 5. eLua should also now support inheritance. + 6. 'const' subtable in eLua is considered deprecated. + + Changes in behaviour: + a. You can no longer assign to non-existing class members in classes without a __setitem__ method. + It will cause a Lua error. + b. You can no longer iterate over a module table and copy everything into the global namespace. + Actually, this was never the case, but it is now explicitly prohibited. + c. Now changing a base class will immediately affect all derived classes. + d. There might be some issues with inheritance. Although the bases iteration scheme is the same + as was used for merging base classes into derived one, some unknown issues may arise. + + The old metatable behaviour can be restored by using the -no-old-metatable-bindings option. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-03-06: wsfulton + [Python] Change in default behaviour wrapping C++ bool. Only a Python True or False + will now work for C++ bool parameters. This fixes overloading bool with other types. + Python 2.3 minimum is now required for wrapping bool. + + When wrapping: + + const char* overloaded(bool value) { return "bool"; } + const char* overloaded(int value) { return "int"; } + + Previous behaviour: + >>> overloaded(False) + 'int' + >>> overloaded(True) + 'int' + >>> overloaded(0) + 'int' + + Now we get the expected behaviour: + >>> overloaded(False) + 'bool' + >>> overloaded(0) + 'int' + + The consequence is when wrapping bool in non-overloaded functions: + + const char* boolfunction(bool value) { return value ? "true" : "false"; } + + The previous behaviour was very Pythonic: + >>> boolfunction("") + 'false' + >>> boolfunction("hi") + 'true' + >>> boolfunction(12.34) + 'true' + >>> boolfunction(0) + 'false' + >>> boolfunction(1) + 'true' + + Now the new behaviour more along the lines of C++ due to stricter type checking. The + above calls result in an exception and need to be explicitly converted into a bool as + follows: + >>> boolfunction(0) + Traceback (most recent call last): + File "", line 1, in + TypeError: in method 'boolfunction', argument 1 of type 'bool' + >>> boolfunction(bool(0)) + 'false' + + The old behaviour can be resurrected by passing the -DSWIG_PYTHON_LEGACY_BOOL command line + parameter when executing SWIG. Typemaps can of course be written to customise the behaviour + for specific parameters. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-03-06: wsfulton + Fix SF Bug #1363 - Problem with method overloading when some methods are added by %extend + and others are real methods and using template default parameters with smart pointers. + This is noticeable as a regression since 2.0.12 when using the default smart pointer + handling for some languages when the smart pointer wraps std::map and other STL containers. + +2014-03-02: wsfulton + [Python] SF Patch #346 from Jens Krueger. Correct exception thrown attempting to + access a non-existent C/C++ global variable on the 'cvar' object. The exception thrown + used to be a NameError. However, as this access is via a primary, an AttributeError + is more correct and so the exception thrown now is an AttributeError. Reference: + http://docs.python.org/2/reference/expressions.html#attribute-references + + *** POTENTIAL INCOMPATIBILITY *** + +2014-03-01: wsfulton + [Python] Patch #143 Fix type shown when using type() to include the module and package + name when using -builtin. + +2014-03-01: wsfulton + [Python] SF patch #347 Fix missing argument count checking with -modern. + Fixes regression introduced when builtin changes were introduced in SWIG-2.0.3. + +2014-02-21: wsfulton + [PHP] Fix warning suppression using %warnfilter for PHP reserved class names. + +2014-02-19: olly + [Lua] Add keyword warnings for Lua keywords and Basic Functions. + +2014-02-19: olly + -Wallkw now includes keywords for all languages with keyword + warnings (previously Go and R were missing). + +2014-02-19: olly + [PHP] Update the lists of PHP keywords with new ones from PHP 5.4 + and newer (and some missing ones from 5.3). Reserved PHP constants + names are now checked against enum values and constants, instead + of against function and method names. Built-in PHP function names + no longer match methods added by %extend. Functions and methods + named '__sleep', '__wakeup', 'not', 'parent', or 'virtual' are no + longer needlessly renamed. + +2014-02-15: wsfulton + Fix the %$ismember %rename predicates to also apply to members added via %extend. + + Add %$isextendmember for %rename of members added via %extend. This can be used to + distinguish between normal class/struct members and %extend members. For example + '%$ismember, %$not %$isextendmember' will now identify just class/struct members. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-02-16: hfalcic + [Python] Patch #137 - fix crashes/exceptions in exception handling in Python 3.3 + +2014-02-15: wsfulton + [Java] Add support for the cdata library. + +2014-02-08: vkalinin + Nested class support added. This primarily allows SWIG to properly parse nested + classes and keep the nested class information in the parse tree. Java and C# + have utilised this information wrapping the C++ nested classes as Java/C# + nested classes. The remaining target languages ignore nested classes as in + previous versions. Help is needed by users of these remaining languages to + design how C++ nested classes can be best wrapped. Please talk to us on the + swig-devel mailing list if you think you can help. + + Previously, there was limited nested class support. Nested classes were treated + as opaque pointers. However, the "nestedworkaround" feature provided a way to + wrap a nested class as if it was a global class. This feature no longer exists + and is replaced by the new "flatnested" feature. This effectively does the same + thing with less manual code to be written. Please see the 'Nested classes' + section in the documentation in SWIGPlus.html if you were previously using this + feature. + + SWIG now parses the contents of nested classes where previously it did not. You + may find that you will need to make adjustments to your interface file as + effectively extra code is being wrapped. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-02-06: gjanssens + [Guile] Patch #133. Make scm to string conversion work with non-ascii strings. + Guile 2 has a completely rewritten string implementation. SWIG made some assumptions + that are no longer valid as to the internals of guile's string representation. + +2014-01-30: wsfulton + [C#] Add new swigtype_inout.i library containing SWIGTYPE *& OUTPUT typemaps. + + Example usage wrapping: + + void f(XXX *& x) { x = new XXX(111); } + + would be: + + XXX x = null; + f(out x); + // use x + x.Dispose(); // manually clear memory or otherwise leave out and leave it to the garbage collector + +2014-01-21: ianlancetaylor + [Go] Add %go_import directive. + +2014-01-21: ianlancetaylor + [Go] Add support for Go 1.3, not yet released. + +2014-01-20: wsfulton + Director exceptions (Swig::DirectorException) now derive from std::exception + and hence provide the what() method. In Python and Ruby, this replaces the now + deprecated DirectorException::getMessage() method. + +2014-01-14: diorcety + Patch #112 - Fix symbol resolution involving scopes that have multiple levels + of typedefs - fixes some template resolutions as well as some typemap searches. + +2014-01-11: wsfulton + Fix and document the naturalvar feature override behaviour - the naturalvar + feature attached to a variable name has precedence over the naturalvar + feature attached to the variable's type. The overriding was not working + when turning the feature off on the variable's name. + + Fix so that any use of the naturalvar feature will override the global + setting. Previously when set globally by -naturalvar or %module(naturalvar=1), + use of the naturalvar feature was not always honoured. + +2014-01-06: ianlancetaylor + [Go] Fix bug that broke using directors from a thread not + created by Go. + +2013-12-24: ptomulik + [Python] SF Bug #1297 + + Resolve several issues related to python imports. + For example, it's now possible to import modules having the same module + names, but belonging in different packages. + + From the user's viewpoint, this patch gives a little bit more control on + import statements generated by SWIG. The user may choose to use relative + or absolute imports. + + Some details: + - we (still) generate import statements in the form 'import a.b.c' which + corresponds to absolute imports in python3 and (the only available) + ambiguous one in python2. + - added -relativeimport option to use explicit relative import syntax + (python3), + + The "Python Packages" section in the documentation discusses how to work + with importing packages including the new -relativeimport command line option. + +2013-12-23: vadz + [Octave, Perl, Python, R, Ruby, Tcl] Change the length of strings created from fixed-size char + buffers in C code. + + This is a potential backwards compatibility break: a "char buf[5]" containing "ho\0la" was + returned as a string of length 5 before, but is returned as a string of length 2 now. Also, + it was possible to assign a (non-NUL-terminated) string "hello" to such a buffer before but + now this fails and only "helo" can fit. + + Apply "char FIXSIZE[ANY]" typemaps to explicitly choose the old behaviour. + + *** POTENTIAL INCOMPATIBILITY *** + +2013-12-23: talby + [Perl] Add support for directors. + +2013-12-18: ianlancetaylor + [Go] Don't require that Go environment variables be set + when running examples or testsuite when using Go 1 or + later. + +2013-12-17: ianlancetaylor + [Go] Remove -longsize option (for backward compatibility, + ignore it if seen). + +2013-12-17: ianlancetaylor + [Go] Add -go-pkgpath option. + +2013-12-16: ianlancetaylor + [Go] Update for Go 1.2 release. Add support for linking + SWIG code directly into executable, rather than using a + shared library. + +2013-12-13: ianlancetaylor + [Go] Add SWIG source file name as comments in generated + files. This can be used by Go documentation tools. + +2013-12-12: jleveque + [Lua] Fix typo (wchar instead of wchar_t) which made wchar.i + for Lua useless. + +2013-12-12: vmiklos + [PHP] PHP's peculiar call-time pass-by-reference feature was + deprecated in PHP 5.3 and removed in PHP 5.4, so update the REF + typemaps in phppointers.i to specify pass-by-reference in the + function definition. Examples/php/pointer has been updated + accordingly. + +2013-12-12: olly + [PHP] The usage of $input in PHP directorout typemaps has been + changed to be consistent with other languages. The typemaps + provided by SWIG have been updated accordingly, but if you + have written your own directorout typemaps, you'll need to + update $input to &$input (or make equivalent changes). + + *** POTENTIAL INCOMPATIBILITY *** + +2013-11-27: vadz + [C#, Java, Python] Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. + +2013-11-09: wsfulton + [C#] Apply patch #79 from Brant Kyser + - Remove using directives from the generated C# code and fully qualify the use of all .NET + framework types in order to minimize potential name collisions from input files defining + types, namespace, etc with the same name as .NET framework members. + - Globally qualify the use of .NET framework types in the System namespace + - Remove .NET 1.1 support, .NET 2 is the minimum for the C# module + + This is a potential backwards compatibility break if code has been added relying on these using + statements that used to be generated: + + using System; + using System.Runtime.InteropServices; + + The quick fix to add these back in is to add the -DSWIG2_CSHARP command line option when + executing SWIG. See CSharp.html documentation for more info. + + *** POTENTIAL INCOMPATIBILITY *** + +2013-11-05: wsfulton + [Java] Fix some corner cases for the $packagepath/$javaclassname special variable substitution. + +2013-11-05: wsfulton + [Java] Apply patch #91 from Marvin Greenberg - Add director:except feature for improved + exception handling in director methods for Java. + +2013-10-15: vadz + Allow using \l, \L, \u, \U and \E in the substitution part of %(regex:/pattern/subst/) + inside %rename to change the case of the text being replaced. + +2013-10-12: wsfulton + [CFFI] Apply #96 - superclass not lispify + +2013-10-12: wsfulton + Merge in C++11 support from the gsoc2009-matevz branch where Matevz Jekovec first + started the C++0x additions. Documentation of the C++11 features supported is in a + new Chapter of the documentation, "SWIG and C++11" in Doc/Manual/CPlusPlus11.html. + +2013-10-04: wsfulton + Fix %naturalvar not having any affect on templated classes instantiated with an + enum as the template parameter type. Problem reported by Vadim Zeitlin. + +2013-09-20: wsfulton + [Java] Fix a memory leak for the java char **STRING_ARRAY typemaps. + +Version 2.0.12 (9 Feb 2014) +=========================== + +2014-01-16: wsfulton + [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement + of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. + +2014-01-13: kwwette + [Octave] update support to Octave version 3.8.0 + + - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1 + will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see + http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e + So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to + enable features requiring Octave version major.minor.patch or later. + + For Octave versions prior to 3.8.1, we reconstruct values for + OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER, + extracted from Octave's ChangeLogs. An additional hack is needed to + distinguish between Octave <= 3.2.x and 3.8.0, neither of which define + OCTAVE_API_VERSION_NUMBER. + + - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use + for this and future versions of Octave. + + - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in + octave_swig_type::dims(). Its use is not required here, so remove it. + + - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. + + - Updated Octave documentation with tested Octave versions, and added a + warning against using versions <= 3.x.x, which are no longer tested. + +2013-12-22: wsfulton + C++11 support for new versions of erase and insert in the STL containers. + + The erase and insert methods in the containers use const_iterator instead + of iterator in C++11. There are times when the methods wrapped must match + the parameters exactly. Specifically when full type information for + template types is missing or SWIG fails to look up the type correctly, + for example: + + %include + typedef float Real; + %template(RealVector) std::vector; + + SWIG does not find std::vector::iterator because %template using + typedefs does not always work and so SWIG doesn't know if the type is + copyable and so uses SwigValueWrapper which does + not support conversion to another type (const_iterator). This resulted + in compilation errors when using the C++11 version of the containers. + + Closes #73 + +2013-10-17: wsfulton + [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include + within extern "C" block. + +2013-10-17: wsfulton + [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. + +2013-10-12: wsfulton + [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() + and SWIG_Lua_namespace_register(). + +Version 2.0.11 (15 Sep 2013) +============================ + +2013-09-15: wsfulton + [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: + unsigned short *OUTPUT + unsigned long *OUTPUT + signed long long *OUTPUT + char *OUTPUT + signed char*OUTPUT + unsigned char*OUTPUT + +2013-09-12: wsfulton + [Lua] Pull Git patch #62. + 1) Static members and static functions inside class can be accessed as + ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as + ModuleName.ClassName_FunctionName still works. + 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. + +2013-09-12: wsfulton + [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes + the handling of type 'float' and 'double' the same. The implementation requires the + C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. + + Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap + wherever a float is used, such as: + + %typemap(check,fragment="") float, const float & %{ + if ($1 < -FLT_MAX || $1 > FLT_MAX) { + SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); + } + %} + + *** POTENTIAL INCOMPATIBILITY *** + +2013-08-30: wsfulton + [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. + This is standard information in Lua error messages, and makes it much + easier to find bugs. + +2013-08-29: wsfulton + Pull Git patch #75: Handle UTF-8 files with BOM at beginning of file. Was giving an + 'Illegal token' syntax error. + +2013-08-29: wsfulton + [C#] Pull Git patch #77: Allow exporting std::map using non-default comparison function. + +2013-08-28: wsfulton + [Python] %implicitconv is improved for overloaded functions. Like in C++, the methods + with the actual types are considered before trying implicit conversions. Example: + + %implicitconv A; + struct A { + A(int i); + }; + class CCC { + public: + int xx(int i) { return 11; } + int xx(const A& i) { return 22; } + }; + + The following python code: + + CCC().xx(-1) + + will now return 11 instead of 22 - the implicit conversion is not done. + +2013-08-23: olly + [Python] Fix clang++ warning in generated wrapper code. + +2013-08-16: wsfulton + [Python] %implicitconv will now accept None where the implicit conversion takes a C/C++ pointer. + Problem highlighted by Bo Peng. Closes SF patch #230. + +2013-08-07: wsfulton + [Python] SF Patch #326 from Kris Thielemans - Remove SwigPyObject_print and SwigPyObject_str and + make the generated wrapper use the default python implementations, which will fall back to repr + (for -builtin option). + + Advantages: + - it avoids the swig user having to jump through hoops to get print to work as expected when + redefining repr/str slots. + - typing the name of a variable on the python prompt now prints the result of a (possibly redefined) + repr, without the swig user having to do any extra work. + - when redefining repr, the swig user doesn't necessarily have to redefine str as it will call the + redefined repr + - the behaviour is exactly the same as without the -builtin option while requiring no extra work + by the user (aside from adding the %feature("python:slot...) statements of course) + + Disadvantage: + - default str() will give different (but clearer?) output on swigged classes + +2013-07-30: wsfulton + [Python, Ruby] Fix #64 #65: Missing code in std::multimap wrappers. Previously an instantiation + of a std::map was erroneously required in addition to an instantiation of std::multimap with the + same template parameters to prevent compilation errors for the wrappers of a std::multimap. + +2013-07-14: joequant + [R] Change types file to allow for SEXP return values + +2013-07-05: wsfulton + [Python] Add %pythonbegin directive which works like %pythoncode, except the specified code is + added at the beginning of the generated .py file. This is primarily needed for importing from + __future__ statements required to be at the very beginning of the file. Example: + + %pythonbegin %{ + from __future__ import print_function + print("Loading", "Whizz", "Bang", sep=' ... ') + %} + +2013-07-01: wsfulton + [Python] Apply SF patch #340 - Uninitialized variable fix in SWIG_Python_NonDynamicSetAttr + when using -builtin. + +2013-07-01: wsfulton + [Python, Ruby, Ocaml] Apply SF patch #341 - fix a const_cast in generated code that was generating + a <:: digraph when using the unary scope operator (::) (global scope) in a template type. + +2013-07-01: wsfulton + [Python] Add SF patch #342 from Christian Delbaere to fix some director classes crashing on + object deletion when using -builtin. Fixes SF bug #1301. + +2013-06-11: wsfulton + [Python] Add SWIG_PYTHON_INTERPRETER_NO_DEBUG macro which can be defined to use the Release version + of the Python interpreter in Debug builds of the wrappers. The Visual Studio .dsp example + files have been modified to use this so that Debug builds will now work without having + to install or build a Debug build of the interpreter. + +2013-06-07: wsfulton + [Ruby] Git issue #52. Fix regression with missing rb_complex_new function for Ruby + versions prior to 1.9 using std::complex wrappers if just using std::complex as an output type. + Also fix the Complex helper functions external visibility (to static by default). + +2013-06-04: olly + [PHP] Fix SWIG_ZTS_ConvertResourcePtr() not to dereference NULL + if the type lookup fails. + +Version 2.0.10 (27 May 2013) +============================ + +2013-05-25: wsfulton + [Python] Fix Python 3 inconsistency when negative numbers are passed + where a parameter expects an unsigned C type. An OverFlow error is + now consistently thrown instead of a TypeError. + +2013-05-25: Artem Serebriyskiy + SVN Patch ticket #338 - fixes to %attribute macros for template usage + with %arg. + +2013-05-19: wsfulton + Fix ccache-swig internal error bug due to premature file cleanup. + + Fixes SF bug 1319 which shows up as a failure in the ccache tests on + Debian 64 bit Wheezy, possibly because ENABLE_ZLIB is defined. + + This is a corner case which will be hit when the maximum number of files + in the cache is set to be quite low (-F option), resulting in a cache miss. + +2013-05-09: kwwette + [Octave] Fix bugs in Octave module loading: + - fix a memory leak in setting of global variables + - install functions only once, to speed up module loads + +2013-04-28: gjanssens + [Guile] Updates in guile module: + - Add support for guile 2.0 + - Drop support for guile 1.6 + - Drop support for generating wrappers using guile's gh interface. + All generated wrappers will use the scm interface from now on. + - Deprecate -gh and -scm options. They are no longer needed. + A warning will be issued when these options are still used. + - Fix all tests and examples to have a successful travis test + +2013-04-18: wsfulton + Apply Patch #36 from Jesus Lopez to add support for $descriptor() special variable macro expansion + in fragments. For example: + + %fragment("nameDescriptor", "header") + %{ + static const char *nameDescriptor = "$descriptor(Name)"; + %} + + which will generate into the wrapper if the fragment is used: + + static const char *nameDescriptor = "SWIGTYPE_Name"; + +2013-04-18: wsfulton + Fix SF Bug #428 - Syntax error when preprocessor macros are defined inside of enum lists, such as: + + typedef enum { + eZero = 0 + #define ONE 1 + } EFoo; + + The macros are silently ignored. + +2013-04-17: wsfulton + [C#] Pull patch #34 from BrantKyser to fix smart pointers in conjunction with directors. + +2013-04-15: kwwette + [Octave] Fix bugs in output of cleanup code. + - Cleanup code is now written also after the "fail:" label, so it will be called if + a SWIG_exception is raised by the wrapping function, consistent with other modules. + - Octave module now also recognises the "$cleanup" special variable, if needed. + +2013-04-08: kwwette + Add -MP option to SWIG for generating phony targets for all dependencies. + - Prevents make from complaining if header files have been deleted before + the dependency file has been updated. + - Modelled on similar option in GCC. + +2013-04-09: olly + [PHP] Add missing directorin typemap for char* and char[] which + fixes director_string testcase failure. + +2013-04-05: wsfulton + [Ruby] SF Bug #1292 - Runtime fixes for Proc changes in ruby-1.9 when using STL + wrappers that override the default predicate, such as: + + %template(Map) std::map >; + +2013-04-05: wsfulton + [Ruby] SF Bug #1159 - Correctly check rb_respond_to call return values to fix some + further 1.9 problems with functors and use of Complex wrappers. + +2013-04-02: wsfulton + [Ruby] Runtime fixes for std::complex wrappers for ruby-1.9 - new native Ruby complex numbers are used. + +2013-03-30: wsfulton + [Ruby] Fix seg fault when using STL containers of generic Ruby types, GC_VALUE or LANGUAGE_OBJECT, + on exit of the Ruby interpreter. More frequently observed in ruby-1.9. + +2013-03-29: wsfulton + [Ruby] Fix delete_if (reject!) for the STL container wrappers which previously would + sometimes seg fault or not work. + +2013-03-25: wsfulton + [Python] Fix some undefined behaviour deleting slices in the STL containers. + +2013-03-19: wsfulton + [C#, Java, D] Fix seg fault in SWIG using directors when class and virtual method names are + the same except being in different namespaces when the %nspace feature is not being used. + +2013-02-19: kwwette + Fix bug in SWIG's handling of qualified (e.g. const) variables of array type. Given the typedef + a(7).q(volatile).double myarray // typedef volatile double[7] myarray; + the type + q(const).myarray // const myarray + becomes + a(7).q(const volatile).double // const volatile double[7] + Previously, SwigType_typedef_resolve() produces the type + q(const).a(7).q(volatile).double // non-sensical type + which would never match %typemap declarations, whose types were parsed correctly. + Add typemap_array_qualifiers.i to the test suite which checks for the correct behaviour. + +2013-02-18: wsfulton + Deprecate typedef names used as constructor and destructor names in %extend. The real + class/struct name should be used. + + typedef struct tagEStruct { + int ivar; + } EStruct; + + %extend tagEStruct { + EStruct() // illegal name, should be tagEStruct() + { + EStruct *s = new EStruct(); + s->ivar = ivar0; + return s; + } + ~EStruct() // illegal name, should be ~tagEStruct() + { + delete $self; + } + } + + For now these trigger a warning: + + extend_constructor_destructor.i:107: Warning 522: Use of an illegal constructor name 'EStruct' in + %extend is deprecated, the constructor name should be 'tagEStruct'. + extend_constructor_destructor.i:111: Warning 523: Use of an illegal destructor name 'EStruct' in + %extend is deprecated, the destructor name should be 'tagEStruct'. + + These %extend destructor and constructor names were valid up to swig-2.0.4, however swig-2.0.5 ignored + them altogether for C code as reported in SF bug #1306. The old behaviour of using them has been + restored for now, but is officially deprecated. This does not apply to anonymously defined typedef + classes/structs such as: + + typedef struct {...} X; + +2013-02-17: kwwette + When generating functions provided by %extend, use "(void)" for no-argument functions + instead of "()". This prevents warnings when compiling with "gcc -Wstrict-prototypes". + +2013-02-17: kwwette + [Octave] Minor fix to autodoc generation: get the right type for functions returning structs. + +2013-02-15: wsfulton + Deprecate typedef names used in %extend that are not the real class/struct name. For example: + + typedef struct StructBName { + int myint; + } StructB; + + %extend StructB { + void method() {} + } + + will now trigger a warning: + + swig_extend.i:19: Warning 326: Deprecated %extend name used - the struct name StructBName + should be used instead of the typedef name StructB. + + This is only partially working anyway (the %extend only worked if placed after the class + definition). + +2013-02-09: wsfulton + [CFFI] Apply patch #22 - Fix missing package before &body + +2013-01-29: wsfulton + [Java] Ensure 'javapackage' typemap is used as it stopped working from version 2.0.5. + +2013-01-28: wsfulton + [Python] Apply patch SF #334 - Fix default value conversions "TRUE"->True, "FALSE"->False. + +2013-01-28: wsfulton + [Java] Apply patch SF #335 - Truly ignore constructors in directors with %ignore. + +2013-01-18: Brant Kyser + [Java] Patch #15 - Allow the use of the nspace feature without the -package commandline option. + This works as long and the new jniclasspackage pragma is used to place the JNI intermediate class + into a package and the nspace feature is used to place all exposed types into a package. + +2013-01-15: wsfulton + Fix Visual Studio examples to work when SWIG is unzipped into a directory containing spaces. + +2013-01-15: wsfulton + [C#] Fix cstype typemap lookup for member variables so that a fully qualified variable name + matches. For example: + %typemap(cstype) bool MVar::mvar "MyBool" + struct MVar { + bool mvar; + }; + +2013-01-11: Brant Kyser + [Java, C#, D] SF Bug #1299 - Fix generated names for when %nspace is used on + classes with the same name in two different namespaces. + +2013-01-11: Vladimir Kalinin + [C#] Add support for csdirectorin 'pre', 'post' and 'terminator' attributes. + +2013-01-08: olly + [PHP] Fix to work with a ZTS build of PHP (broken in 2.0.7). + +2013-01-07: olly + Fix bashism in configure, introduced in 2.0.9. + +2013-01-06: wsfulton + Pull patch #4 from ptomulik to fix SF Bug #1296 - Fix incorrect warning for virtual destructors + in templates, such as: + Warning 521: Illegal destructor name B< A >::~B(). Ignored. + +2013-01-05: wsfulton + [Python] Pull patch #3 from ptomulik to fix SF Bug #1295 - standard exceptions as + classes using the SWIG_STD_EXCEPTIONS_AS_CLASSES macro. + +2013-01-04: wsfulton + [Java] Pull patch #2 from BrantKyser to fix SF Bug #1283 - fix smart pointers in conjuction + with directors. + +2013-01-03: wsfulton + [Java] Pull patch #1 from BrantKyser to fix SF Bug #1278 - fix directors and nspace feature when + multilevel namespaces are used. + +Version 2.0.9 (16 December 2012) +================================ + +2012-12-16: wsfulton + Fix garbage line number / empty file name reporting for some missing + '}' or ')' error messages. + +2012-12-15: kkaempf + [Ruby] Apply patch 3530444, Class#methods and Class#constants returns array of + symbols in Ruby 1.9+ + +2012-12-14: kkaempf + [Ruby] Apply patch 3530439 and finally replace all occurrences of the STR2CSTR() macro + with StringValuePtr(). STR2CSTR was deprecated since years and got removed in Ruby 1.9 + +2012-12-14: kkaempf + [Ruby] Applied patches #3530442 and 3530443 to adapt compile and runtime include + paths to match Ruby 1.9+ + +2012-12-14: wsfulton + [CFFI] Fix #3161614 - Some string constants are incorrect + +2012-12-13: wsfulton + [CFFI] Fix #3529690 - Fix incorrect constant names. + +2012-12-12: drjoe + [R] add fix to finalizer that was missed earlier + +2012-12-11: wsfulton + [Python] Apply patch #3590522 - fully qualified package paths for Python 3 even if a module is in the + same package. + +2012-12-08: wsfulton + [Python] Bug #3563647 - PyInt_FromSize_t unavailable prior to Python 2.5 for unsigned int types. + +2012-12-08: wsfulton + [Perl] Fix bug #3571361 - C++ comment in C wrappers. + +2012-12-07: wsfulton + [C#] Apply patch #3571029 which adds missing director support for const unsigned long long &. + +2012-11-28: kwwette + [Octave] Simplified module loading: now just the syntax + $ example; + is accepted, which loads functions globally but constants and variables relative to the current scope. + This make module loading behaviour reliably consistent, and reduces problems when loading modules which + depend on other modules which may not have been previously loaded. + +2012-11-27: wsfulton + [cffi] Fix junk output when wrapping single character literal constants. + +2012-11-17: wsfulton + [Tcl, Modula3] Add missing support for -outdir. + +2012-11-17: wsfulton + Fix segfaults when using filename paths greater than 1024 characters in length. + +2012-11-14: wsfulton + [ccache-swig] Apply patch #3586392 from Frederik Deweerdt to fix some error cases - incorrectly using + memory after it has been deleted. + +2012-11-09: vzeitlin + [Python] Fix overflow when passing values greater than LONG_MAX from Python 3 for parameters with unsigned long C type. + +2012-11-09: wsfulton + Fix some feature matching issues for implicit destructors and implicit constructors and implicit + copy constructors added with %copyctor. Previously a feature for these had to be fully qualified + in order to match. Now the following will also match: + + %feature("xyz") ~XXX(); + struct XXX {}; + +2012-11-09: wsfulton + Further consistency in named output typemap lookups for implicit constructors and destructors and + implicit copy constructors added with %copyctor. Previously only the fully qualified name was being + used, now the unqualified name will also be used. For example, previously: + + example.i:38: Searching for a suitable 'out' typemap for: void Space::More::~More + Looking for: void Space::More::~More + Looking for: void + + Now the unqualified name is also used: + + example.i:38: Searching for a suitable 'out' typemap for: void Space::More::~More + Looking for: void Space::More::~More + Looking for: void ~More + Looking for: void + +2012-11-02: wsfulton + Fix some subtle named output typemap lookup misses, the fully qualified name was not always being + used for variables, for example: + + struct Glob { + int MyVar; + }; + + Previously the search rules (as shown by -debug-tmsearch) for the getter wrapper were: + + example.i:44: Searching for a suitable 'out' typemap for: int MyVar + Looking for: int MyVar + Looking for: int + + Now the scope is named correctly: + + example.i:44: Searching for a suitable 'out' typemap for: int Glob::MyVar + Looking for: int Glob::MyVar + Looking for: int MyVar + Looking for: int + +2012-10-26: wsfulton + Fix director typemap searching so that a typemap specified with a name will be correctly matched. Previously + the name was ignored during the typemap search. Applies to the following list of typemaps: + directorout, csdirectorout, cstype, imtype, ctype, ddirectorout, dtype, gotype, jtype, jni, javadirectorout. + +2012-10-11: wsfulton + Most of the special variables available for use in %exception are now also available for expansion in + %extend blocks. These are: $name $symname $overname $decl $fulldecl $parentclassname $parentclasssymname, see docs + on "Class extension" in SWIGPlus.html. Patch based on submission from Kris Thielemans. + +2012-10-10: wsfulton + Additional new special variables in %exception are expanded as follows: + $parentclassname - The parent class name (if any) for a method. + $parentclasssymname - The target language parent class name (if any) for a method. + +2012-10-08: iant + [Go] Generating Go code now requires using the -intgosize option to + indicate the size of the 'int' type in Go. This is because the + size of the type is changing from Go 1.0 to Go 1.1 for x86_64. + +2012-09-14: wsfulton + Add new warning if the empty template instantiation is used as a base class, for example: + + template class Base {}; + %template() Base; + class Derived : public Base {}; + + gives the following warning instead of silently ignoring the base: + + cpp_inherit.i:52: Warning 401: Base class 'Base< int >' has no name as it is an empty template instantiated with '%template()'. Ignored. + cpp_inherit.i:51: Warning 401: The %template directive must be written before 'Base< int >' is used as a base class and be declared with a name. + + +2012-09-11: wsfulton + [Java] Fix #3535304 - Direct use of a weak global reference in directors + sometimes causing seg faults especially on Android. + +2012-09-06: wsfulton + [Java] Fix (char *STRING, size_t LENGTH) typemaps to accept NULL string. + +2012-08-26: drjoe + [R] make ExternalReference slot ref to contain reference + +2012-08-26: drjoe + [R] fix Examples/Makefile to use C in $(CC) rather than $(CXX) + +Version 2.0.8 (20 August 2012) +============================== + +2012-08-15: wsfulton + [Perl] Add size_type, value_type, const_reference to the STL containers. + +2012-08-15: wsfulton + [Python] Add discard and add methods to std::set wrappers so that pyabc.i can be used ensuring + MutableSet is a valid abstract base class for std::set. As reported by Alexey Sokolov. + Similarly for std::multiset. + +2012-08-15: wsfulton + [Python] Fix #3541744 - Missing PyInt_FromSize_t calls for Python 3. + +2012-08-13: wsfulton + [Java] Patch from David Baum to add the assumeoverride feature for Java directors to + improve performance when all overridden methods can be assumed to be overridden. + +2012-08-05: wsfulton + [Python] #3530021 Fix unused variable warning. + +2012-08-05: wsfulton + [C#] Fix #3536360 - Invalid code sometimes being generated for director methods + with many arguments. + +2012-08-05: wsfulton + [Perl] #3545877 - Don't undefine bool if defined by C99 stdbool.h - problem using + Perl 5.16 and later. + +2012-08-04: wsfulton + Remove incorrect warning (314) about target language keywords which were triggered + by using declarations and using directives. For example 'string' is a keyword in C#: + namespace std { class string; } + using std::string; + +2012-07-21: wsfulton + Fix display of pointers in various places on 64 bit systems - only 32 bits were being shown. + +2012-07-21: wsfulton + Fix gdb debugger functions 'swigprint' and 'locswigprint' to display to the gdb output window + rather than stdout. This fixes display problems in gdbtui and the ensures the output + appears where expected in other gdb based debuggers such as Eclipse CDT. + +2012-07-20: kwwette + [Octave] segfault-on-exit prevention hack now preserves exit status, and uses C99 _Exit(). + +2012-07-02: wsfulton + Fix Debian bug http://bugs.debian.org/672035, typemap copy failure - regression introduced + in swig-2.0.5: + %include + using std::pair; + %template(StrPair) pair; + +2012-07-02: wsfulton + Fix using declarations combined with using directives with forward class declarations so that + types are correctly found in scope for templates. Example: + + namespace Outer2 { + namespace Space2 { + template class Thing2; + } + } + using namespace Outer2; + using Space2::Thing2; + template class Thing2 {}; + // STILL BROKEN void useit2(Thing2 t) {} + void useit2a(Outer2::Space2::Thing2 t) {} + void useit2b(::Outer2::Space2::Thing2 t) {} + void useit2c(Space2::Thing2 t) {} + namespace Outer2 { + void useit2d(Space2::Thing2 t) {} + } + + %template(Thing2Int) Thing2; + + +2012-06-30: wsfulton + Fix template namespace problems for symbols declared with a forward class declarations, such as: + + namespace Space1 { + namespace Space2 { + template struct YYY; + } + template struct Space2::YYY { + T yyy(T h) { + return h; + } + }; + void testYYY1(Space1::Space2::YYY yy) {} + void testYYY2(Space2::YYY yy) {} + void testYYY3(::Space1::Space2::YYY yy) {} + } + + %template(YYYInt) Space1::Space2::YYY; + +2012-06-30: wsfulton + Fix namespace problems for symbols declared with a forward class declarations, such as: + + namespace Space1 { + namespace Space2 { + struct XXX; + struct YYY; + } + + struct Space2::YYY {}; + struct Space1::Space2::XXX {}; + + void testXXX2(Space2::XXX xx) {} + void testYYY2(Space2::YYY yy) {} + } + + where xx and yy were not recognised as the proxy classes XXX and YYY. + +2012-06-30: wsfulton + Fix using declarations combined with using directives with forward class declarations so that + types are correctly found in scope. + + namespace Outer2 { + namespace Space2 { + class Thing2; + } + } + using namespace Outer2; + using Space2::Thing2; + class Thing2 {}; + // None of the methods below correctly used the Thing2 proxy class + void useit2(Thing2 t) {} + void useit2a(Outer2::Space2::Thing2 t) {} + void useit2b(::Outer2::Space2::Thing2 t) {} + void useit2c(Space2::Thing2 t) {} + namespace Outer2 { + void useit2d(Space2::Thing2 t) {} + } + +2012-06-25: wsfulton + Fix using declarations combined with using directives so that types are correctly found in scope. + Example: + + namespace Outer2 { + namespace Space2 { + class Thing2 {}; + } + } + using namespace Outer2; // using directive + using Space2::Thing2; // using declaration + void useit2(Thing2 t) {} + + Similarly for templated classes. + +2012-05-29: wsfulton + Fix #3529601 - seg fault when a protected method has the "director" + feature but the parent class does not. Also fix similar problems with + the allprotected feature. + +2012-05-28: wsfulton + Fix seg fault when attempting to warn about an illegal destructor - #3530055, 3530078 and #3530118. + +Version 2.0.7 (26 May 2012) +=========================== +2012-05-26: wsfulton + std::string typemap modifications so they can be used with %apply for other string + classes. + +2012-05-25: wsfulton + [Lua] Fixes for -external-runtime to work again. + +2012-05-22: szager + [python] Disambiguate SWIG_From_unsigned_SS_int and SWIG_From_unsigned_SS_long. + +2012-05-18: olly + [PHP] Fix getters for template members. (SF#3428833, SF#3528035) + +2012-05-14: wsfulton + Fix some language's std::map wrappers to recognise difference_type, size_type, key_type + and mapped_type. + +2012-05-14: kwwette (signed off by xavier98) + [Octave] Prevent Octave from seg-faulting at exit when SWIG + modules are loaded, due to bugs in Octave's cleanup code: + * Wrapping functions now declared with Octave DEFUN_DLD macro, + and loaded through Octave's dynamic module loader + * Global variables of swigref type are now assigned a new() + copy of the swigref class, to prevent double-free errors + * SWIG module at-exit cleanup function now created in Octave + through eval(), so not dependent on loaded .oct library + * For Octave versions 3.1.* to 3.3.*, register C-level at-exit + function which terminates Octave immediately (with correct + status code) without performing memory cleanup. This function + can be controlled with macros in Lib/octave/octruntime.swg + + [Octave] New syntax for determing whether SWIG module should be + loaded globally or non-globally. To load module "example" globally, + type the module name + $ example; + as before; to load module non-globally, assign it to a variable: + $ example = example; + or + $ ex = example; + for a shorter (local) module name. -global/-noglobal command-line + options and module command line are deprecated. Added usage info + to module, so typing + $ help example + or incorrect usage should display proper usage, with examples. + + *** POTENTIAL INCOMPATIBILITY *** + +2012-05-12: olly + [PHP] Fix memory leak in code generated for a callback. Patch from + SF bug #3510806. + +2012-05-12: olly + [PHP] Avoid using zend_error_noreturn() as it doesn't work with all + builds of PHP (SF bug #3166423). Instead we now wrap it in a + SWIG_FAIL() function which we annotate as "noreturn" for GCC to + avoids warnings. This also reduces the size of the compiled + wrapper (e.g. the stripped size is reduced by 6% for Xapian's PHP + bindings). + +2012-05-11: wsfulton + [Java] SF patch #3522855 Fix unintended uninitialised memory access in OUTPUT typemaps. + +2012-05-11: wsfulton + [Java] SF patch #3522674 Fix possible uninitialised memory access in char **STRING_OUT + typemap. + +2012-05-11: wsfulton + [Java] SF patch #3522611 Fix uninitialised size regression in char **STRING_ARRAY + introduced in swig-2.0.6. + +2012-05-11: wsfulton + SF bug #3525050 - Fix regression introduced in swig-2.0.5 whereby defining one typemap + method such as an 'out' typemap may hide another typemap method such as an 'in' typemap - + only occurs when the type is a template type where the template parameters are the same + via a typedef. + +2012-05-10: olly + [PHP] Fix the constant typemaps for SWIGTYPE, etc - previously + these used the wrong name for renamed constants. Add + autodoc_runme.php to the testsuite as a regression test for this. + +2012-05-02: ianlancetaylor + [Go] Remove compatibility support for gccgo 4.6. Using + SWIG with gccgo will now require gccgo 4.7. Using SWIG + with the more commonly used gc compiler is unaffected. + +2012-05-01: wsfulton + Fix generated code for C forward enum declarations in some languages. + +Version 2.0.6 (30 April 2012) +============================= + +2012-04-25: wsfulton + [Lua] Fix uninitialised variable in SWIGTYPE **OUTPUT typemaps as reported by Jim Anderson. + +2012-04-28: wsfulton + [Python] Fix compilation errors when wrapping STL containers on Mac OS X and possibly other systems. + +2012-04-28: wsfulton + [Java] Patch 3521811 from Leo Davis - char **STRING_ARRAY typemaps fixed to handle + null pointers. + Version 2.0.5 (19 April 2012) ============================= @@ -304,7 +2308,7 @@ Version 2.0.5 (19 April 2012) -tmsearch and -tmused. 2011-08-26: wsfulton - [C#, D] Fix %callback which was generating uncompileable code. + [C#, D] Fix %callback which was generating uncompilable code. 2011-08-25: wsfulton Fix constructors in named typedef class declarations as reported by Gregory Bronner: @@ -349,7 +2353,7 @@ Version 2.0.5 (19 April 2012) namespace std { template struct map { class iterator; - } + }; } iterator was scoped as std::iterator, but now it is correctly std::map::iterator; @@ -361,10 +2365,10 @@ Version 2.0.5 (19 April 2012) template struct Map { typedef Key key_type; typedef T mapped_type; - } + }; } - tyepdef double DOUBLE; - %typemap(MM) Std::Map; + typedef double DOUBLE; + %template(MM) Std::Map; All symbols within Map will be resolved correctly, eg key_type and mapped_type no matter if the wrapped code uses Std::Map or std::Map or Std::Map @@ -543,7 +2547,7 @@ Version 2.0.4 (21 May 2011) PySlice_GetIndices, which changed signatures in python3.2. 2011-04-07: wsfulton - Fix wrapping of const array typedefs which were generating uncompileable code as + Fix wrapping of const array typedefs which were generating uncompilable code as reported by Karl Wette. 2011-04-03: szager @@ -692,7 +2696,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 @@ -770,8 +2774,8 @@ Version 2.0.2 (20 February 2011) Fix handling of multiple regex-using %renames attached to the same declaration. For example, now - %rename("%(regex/^Set(.*)/put\\1/)s") ""; - %rename("%(regex/^Get(.*)/get\\1/)s") ""; + %rename("%(regex:/^Set(.*)/put\\1/)s") ""; + %rename("%(regex:/^Get(.*)/get\\1/)s") ""; works as expected whereas before only the last anonymous rename was taken into account. @@ -981,7 +2985,7 @@ Version 2.0.1 (4 October 2010) in this case). 2010-06-03: wsfulton - Fix uncompileable code when %rename results in two enum items + Fix uncompilable code when %rename results in two enum items with the same name. Reported by Vadim Zeitlin. Version 2.0.0 (2 June 2010) @@ -1494,7 +3498,7 @@ Version 2.0.0 (2 June 2010) Fix #2310483 - function pointer typedef within extern "C" block. 2009-11-13: wsfulton - Fix usage of nested template classes within templated classes so that compileable code + Fix usage of nested template classes within templated classes so that compilable code is generated. 2009-11-13: olly @@ -1502,7 +3506,7 @@ Version 2.0.0 (2 June 2010) wasn't being used. Patch from gverbruggen in SF#2892647. 2009-11-12: wsfulton - Fix usage of nested template classes so that compileable code is generated - the nested + Fix usage of nested template classes so that compilable code is generated - the nested template class is now treated like a normal nested classes, that is, as an opaque type unless the nestedworkaround feature is used. @@ -1528,7 +3532,7 @@ Version 2.0.0 (2 June 2010) 2009-11-11: wsfulton There were a number of C++ cases where nested classes/structs/unions were being handled - as if C code was being parsed which would oftentimes lead to uncompileable code as an + as if C code was being parsed which would oftentimes lead to uncompilable code as an attempt was made to wrap the nested structs like it is documented for C code. Now all nested structs/classes/unions are ignored in C++ mode, as was always documented. However, there is an improvement as usage of nested structs/classes/unions is now always treated @@ -1540,7 +3544,7 @@ Version 2.0.0 (2 June 2010) Fix R for -fcompact and add std_map.i 2009-11-08: wsfulton - Fix inconsistency for nested structs/unions/classes. Uncompileable code was being + Fix inconsistency for nested structs/unions/classes. Uncompilable code was being generated when inner struct and union declarations were used as types within the inner struct. The inner struct/union is now treated as a forward declaration making the behaviour the same as an inner class. (C++ code), eg: @@ -1554,7 +3558,7 @@ Version 2.0.0 (2 June 2010) Ignored nested class/struct warnings now display the name of the ignored class/struct. 2009-11-07: wsfulton - Bug #1514681 - Fix nested template classes within a namespace generated uncompileable + Bug #1514681 - Fix nested template classes within a namespace generated uncompilable code and introduced strange side effects to other wrapper code especially code after the nested template class. Note that nested template classes are still ignored. @@ -1580,8 +3584,8 @@ Version 2.0.0 (2 June 2010) and in template parameter specializations: struct S {}; - template struct X { void a() {}; }; - template <> struct X { void b() {}; }; + template struct X { void a() {} }; + template <> struct X { void b() {} }; %template(MyTConcrete) X< ::S >; plus probably some other corner case usage of ::. @@ -2345,7 +4349,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 @@ -2409,7 +4413,7 @@ Version 1.3.36 (24 June 2008) 06/19/2008: wsfulton [Java, C#] C# and Java keywords will be renamed instead of just issuing a warning - and then generating uncompileable code. Warning 314 gives the new name when a + and then generating uncompilable code. Warning 314 gives the new name when a keyword is found. 06/19/2008: wsfulton @@ -2512,8 +4516,8 @@ Version 1.3.36 (24 June 2008) Makefile target being generated when generating makefiles with the -M family of options. For example: - $ swig -java -MM -MT overiddenname -c++ example.i - overiddenname: \ + $ swig -java -MM -MT overriddenname -c++ example.i + overriddenname: \ example.i \ example.h @@ -2852,7 +4856,7 @@ Version 1.3.34 (27 February 2008) 11/30/2007: wsfulton Fix using statements using a base class method where the methods were overloaded. Depending on the order of the using statements and method declarations, these - were previously generating uncompileable wrappers, eg: + were previously generating uncompilable wrappers, eg: struct Derived : Base { virtual void funk(); @@ -2990,7 +4994,7 @@ Version 1.3.32 (November 15, 2007) %attributeref(Class, AttributeType, AttributeName, AccessorMethod) 10/16/2007: olly - [Tcl] Fix several ocurrences of "warning: deprecated conversion + [Tcl] Fix several occurrences of "warning: deprecated conversion from string constant to 'char*'" from GCC 4.2 in generated C/C++ code. @@ -3199,7 +5203,7 @@ Version 1.3.32 (November 15, 2007) [C#] Added missing support for C++ class member pointers. 08/09/2007: wsfulton - [C#, Java] Add support for $owner in the "out" typemaps like in the the scripting + [C#, Java] Add support for $owner in the "out" typemaps like in the scripting language modules. Note that $owner has always been supported in the "javaout" / "csout" typemaps. @@ -3899,7 +5903,7 @@ Version 1.3.30 (November 13, 2006) 10/12/2006: wsfulton [Java] Remove potential race condition on the proxy class' delete() method (it is now a synchronized method, but is now customisable by changing the - methodmodifiers attribute in the the javadestruct or javadestruct_derived typemap) + methodmodifiers attribute in the javadestruct or javadestruct_derived typemap) [C#] Remove potential race condition on the proxy class' Dispose() method, similar to Java's delete() above. @@ -3940,7 +5944,7 @@ Version 1.3.30 (November 13, 2006) 10/03/2006: wsfulton [Ruby] Fix #1527885 - Overloaded director virtual methods sometimes produced - uncompileable code when used with the director:except feature. + uncompilable code when used with the director:except feature. 10/03/2006: wsfulton Directors: Directors are output in the order in which they are declared in @@ -4415,7 +6419,7 @@ Version 1.3.29 (March 21, 2006) 6146 _std_containers.so 174 _std_containers.so.hidden - Excecution times: + Execution times: real 0m0.050s user 0m0.039s sys 0m0.005s _std_containers.so real 0m0.039s user 0m0.026s sys 0m0.007s _std_containers.so.hidden @@ -4501,7 +6505,7 @@ Version 1.3.29 (March 21, 2006) protected methods by default. In previous releases, you needed to use the 'dirprot' - option to acheive the same. + option to achieve the same. If you want, you can disable the new default behaviour, use the 'nodirprot' option: @@ -4707,7 +6711,7 @@ Version 1.3.28 (February 12, 2006) %naturalvar std::string; %include - that will tell swig to use the the 'natural' wrapping + that will tell swig to use the 'natural' wrapping mechanism to all std::string global and member variables. @@ -4828,7 +6832,7 @@ Version 1.3.28 (February 12, 2006) %rename("%(utitle)s",%$isfunction,%$ismember) ""; - to avoid clashings with other swig macros/directives. + to avoid clashes with other swig macros/directives. 01/14/2006: cfisavage [Ruby] @@ -5849,7 +7853,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. @@ -8138,7 +10142,7 @@ Version 1.3.23 (November 11, 2004) wrapper method only and not the extra overloaded methods that SWIG generates. For example: - %feature("except") void hello(int i=0, double d=0.0); + %feature("except") hello(int i=0, double d=0.0); void hello(int i=0, double d=0.0); will apply the feature to all three wrapper methods, that is: @@ -8149,7 +10153,7 @@ Version 1.3.23 (November 11, 2004) If the default arguments are not specified in the feature: - %feature("except") void hello(int i, double d); + %feature("except") hello(int i, double d); void hello(int i=0, double d=0.0); then the feature will only apply to this wrapper method: @@ -8214,7 +10218,7 @@ Version 1.3.23 (November 11, 2004) b = B() b.bar(1) - note the the methods are emitted inside the classes, + note the methods are emitted inside the classes, and hence, the %template name refers to the 'member' method name, not a global namespace name. @@ -8756,7 +10760,7 @@ Version 1.3.23 (November 11, 2004) - Remove the ability to share type information by using c linking. All type sharing happens through a global variable in the target language. + Remove SWIG_NOIMPORT, SWIG_RUNTIME, and related defines. - + Depreciate -runtime, -noruntime command line options + + Deprecate -runtime, -noruntime command line options + Update test-suite common.mk to correctly build multicpptest + Remove reference to precommon.swg + Update the guile_gh interface to share data by a global var instead @@ -9184,7 +11188,7 @@ Version 1.3.23 (November 11, 2004) now if you have - %pythonnondynamic(1) A; + %pythonnondynamic A; struct A { int a; @@ -9202,11 +11206,11 @@ Version 1.3.23 (November 11, 2004) Since this is a feature, you can use - %pythonnondynamic(1); + %pythonnondynamic; or - %pythondynamic(0); [ Note: %pythondynamic since deprecated ] + %pythondynamic; [ Note: %pythondynamic since deprecated ] to force all the wrapped classes to be "nondynamic" ones. @@ -9524,7 +11528,7 @@ Version 1.3.22 (September 4, 2004) ... } - Previously, none of BIG, LARGE or BAR would have produced compileable code + Previously, none of BIG, LARGE or BAR would have produced compilable code when using %javaconst(1). 06/27/2004: wsfulton @@ -10931,7 +12935,7 @@ Version 1.3.20 (December 17, 2003) 11/30/2003: cheetah (William Fulton) [Java] Fixed [ 766409 ] missing symbol SWIG_JavaThrowException during module load - SWIGs internal functions are all static as there is no need for different SWIG + SWIG's internal functions are all static as there is no need for different SWIG generated modules to share any code at runtime. 11/30/2003: beazley @@ -11166,7 +13170,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) @@ -11728,7 +13732,7 @@ Version 1.3.20 (December 17, 2003) 06/25/2003: mrose (Mark Rose) [Python] Director typemap marshalling checks for null pointers when walking the parameter list instead of relying soley on the parameter - count. Cures a segfault that occured for multiple argument inv typemaps. + count. Cures a segfault that occurred for multiple argument inv typemaps. Someone with more Swig experience should probably review this code. 06/24/2003: mkoeppe (Matthias Koeppe) @@ -16162,7 +18166,7 @@ Version 1.3.12 (June 2, 2002) %feature, %rename, %ignore, %exception, and related directives: - Namespaces are fully integrated into the the renaming and declaration + Namespaces are fully integrated into the renaming and declaration matcher. For example: %rename(display) Foo::print; // Rename in namespace Foo @@ -17203,7 +19207,7 @@ Version 1.3.10 (December 10, 2001) shadow classes. In early implementations, shadow classes were merely Python wrappers around typed pointer objects. However, some users actually wanted to receive the shadow class object in C. - To accomodate this, the dereferencing of the "this" pointer in + To accommodate this, the dereferencing of the "this" pointer in a shadow class was moved to C as described in CHANGES [8/8/99]. However, the process of returning pointers to Python was still somewhat problematic. Specifically, shadow classes never worked @@ -18916,13 +20920,13 @@ Version 1.3.6 (July 9, 2001) class TestClass { public: - TestClass() {}; - TestClass(int a) {}; - ~TestClass() {}; - unsigned long xyz(short k) {}; - unsigned long xyz(int n) {}; - static void static_func() {}; - static void static_func(int a) {}; + TestClass() {} + TestClass(int a) {} + ~TestClass() {} + unsigned long xyz(short k) {} + unsigned long xyz(int n) {} + static void static_func() {} + static void static_func(int a) {} }; void delete_TestClass(int a); @@ -19117,7 +21121,7 @@ Version 1.3.6 (July 9, 2001) [Java] destructor (_delete()) was not aware of %name renaming [Java] extends baseclass did not know about %name renaming [Java] extends baseclass did extend even when the baseclass was not known to swig - [Java] sometimes enum-declarations occured before the Java class declaration + [Java] sometimes enum-declarations occurred before the Java class declaration [Java] unrelated enum initialisations no longer appear in Java class [Java] if module ends in '_' correct JNI names are now produced @@ -19998,9 +22002,9 @@ Version 1.3 Alpha 1 (February 11, 2000) *** POTENTIAL INCOMPATIBILITY *** 1/30/00 : loic - Conditionaly compile experimental code with --enable-experiment + Conditionally compile experimental code with --enable-experiment configure flag. - Fix .cvsignore to ignore configrue & yacc generated files + Fix .cvsignore to ignore configure & yacc generated files 1/28/00 : loic Apply automake everywhere @@ -20270,7 +22274,7 @@ Version 1.3 Alpha 1 (February 11, 2000) names or use %apply to map typemaps to alternate names. 8/8/99 : Handling of the 'this' pointer has been changed in Python shadow - classes. Previously, dereferencing of '.this' occured in the + classes. Previously, dereferencing of '.this' occurred in the Python shadow class itself. Now, this step occurs in the C wrappers using the following function: @@ -20512,7 +22516,7 @@ Version 1.1 Patch 4 (January 4, 1998) 12/29/97: Fixed configure script and a few makefiles to support Python 1.5 12/29/97: Added 'embed15.i' library file. This file should be used to - staticly link versions of Python 1.5. To make it the default, + statically link versions of Python 1.5. To make it the default, simply copy 'swig_lib/python/embed15.i' to 'swig_lib/python/embed.i' Version 1.1 Patch 3 (November 24, 1997) @@ -20827,7 +22831,7 @@ Version 1.1 Patch 1 (August 27, 1997) Would generate completely bogus code with garbage replacing the '%d'. Caused by one faulty use of printf (wasn't able to find - any other occurences). + any other occurrences). 7/7/97 : Fixed bug in Python shadow class generation with non-member functions that are returning more than one value. @@ -20943,7 +22947,7 @@ Version 1.1 (June 24, 1997) .... later ... int OldName(int); - Unlike %name, %rename will rename any occurence of the old name. + Unlike %name, %rename will rename any occurrence of the old name. This applies to functions, variables, class members and so forth. There is no way to disable %rename once set, but you can change the name by redeclaring it to something else. @@ -21572,7 +23576,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 cb64a7937..8ab562781 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,16 +2,155 @@ Below are the changes for the current release. See the CHANGES file for changes in older releases. See the RELEASENOTES file for a summary of changes in each release. -Version 2.0.6 (30 April 2012) -============================= +Version 3.0.9 (in progress) +=========================== -2012-04-25: wsfulton - [Lua] Fix uninitialised variable in SWIGTYPE **OUTPUT typemaps as reported by Jim Anderson. +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. -2012-04-28: wsfulton - [Python] Fix compilation errors when wrapping STL containers on Mac OSX and possibly other systems. +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' -2012-04-28: wsfulton - [Java] Patch 3521811 from Leo Davis - char **STRING_ARRAY typemaps fixed to handle - null pointers. +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). diff --git a/COPYRIGHT b/COPYRIGHT index 0f1f0ca21..18fc892ba 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -11,62 +11,69 @@ Portions also copyrighted by: Information-technology Promotion Agency, Japan Active SWIG Developers: - William Fulton (wsf@fultondesigns.co.uk) (SWIG core, Java, C#, Windows, Cygwin) - Olly Betts (olly@survex.com) (PHP) - Joseph Wang (joequant@gmail.com) (R) - Xavier Delacour (xavier.delacour@gmail.com) (Octave) - David Nadlinger (code@klickverbot.at) (D) - Leif Middelschulte (leif.middelschulte@gmail.com) (C) + William Fulton (wsf@fultondesigns.co.uk) (SWIG core, Java, C#, Windows, Cygwin) + Olly Betts (olly@survex.com) (PHP) + Joseph Wang (joequant@gmail.com) (R) + Xavier Delacour (xavier.delacour@gmail.com) (Octave) + David Nadlinger (code@klickverbot.at) (D) + Leif Middelschulte (leif.middelschulte@gmail.com) (C) + Oliver Buchtala (oliver.buchtala@gmail.com) (Javascript) + Neha Narang (narangneha03@gmail.com) (Javascript) + Simon Marchetto (simon.marchetto@scilab-enterprises.com) (Scilab) Past SWIG developers and major contributors include: - Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) - Henning Thielemann (swig@henning-thielemann.de) (Modula3) - Matthias Köppe (mkoeppe@mail.math.uni-magdeburg.de) (Guile, MzScheme) - Luigi Ballabio (luigi.ballabio@fastwebnet.it) (STL wrapping) - Mikel Bancroft (mikel@franz.com) (Allegro CL) - Surendra Singhi (efuzzyone@netscape.net) (CLISP, CFFI) - Marcelo Matus (mmatus@acms.arizona.edu) (SWIG core, Python, UTL[python,perl,tcl,ruby]) - Art Yerkes (ayerkes@speakeasy.net) (Ocaml) - Lyle Johnson (lyle@users.sourceforge.net) (Ruby) - Charlie Savage (cfis@interserv.com) (Ruby) - Thien-Thi Nguyen (ttn@glug.org) (build/test/misc) - Richard Palmer (richard@magicality.org) (PHP) - Sam Liddicott - Ananova Ltd (saml@liddicott.com) (PHP) - Tim Hockin - Sun Microsystems (thockin@sun.com) (PHP) - Kevin Ruland (PHP) - Shibukawa Yoshiki (Japanese Translation) - Jason Stewart (jason@openinformatics.com) (Perl5) - Loic Dachary (Perl5) - David Fletcher (Perl5) - Gary Holt (Perl5) - Masaki Fukushima (Ruby) - Scott Michel (scottm@cs.ucla.edu) (Java directors) - Tiger Feng (songyanf@cs.uchicago.edu) (SWIG core) - Mark Rose (mrose@stm.lbl.gov) (Directors) - Jonah Beckford (beckford@usermail.com) (CHICKEN) - Ahmon Dancy (dancy@franz.com) (Allegro CL) - Dirk Gerrits (Allegro CL) - Neil Cawse (C#) - Harco de Hilster (Java) - Alexey Dyachenko (dyachenko@fromru.com) (Tcl) - Bob Techentin (Tcl) - Martin Froehlich (Guile) - Marcio Luis Teixeira (Guile) - Duncan Temple Lang (R) - Miklos Vajna (PHP directors) - Mark Gossage (mark@gossage.cjb.net) (Lua) - Raman Gopalan (ramangopalan@gmail.com) (eLua) - Gonzalo Garramuno (ggarra@advancedsl.com.ar) (Ruby, Ruby's UTL) - John Lenz (Guile, MzScheme updates, Chicken module, runtime system) - Ian Lance Taylor (Go) - Vadim Zeitlin (PCRE) - Stefan Zager (szager@gmail.com) (Python) + Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) + Henning Thielemann (swig@henning-thielemann.de) (Modula3) + Matthias Köppe (mkoeppe@mail.math.uni-magdeburg.de) (Guile, MzScheme) + Luigi Ballabio (luigi.ballabio@fastwebnet.it) (STL wrapping) + Mikel Bancroft (mikel@franz.com) (Allegro CL) + Surendra Singhi (efuzzyone@netscape.net) (CLISP, CFFI) + Marcelo Matus (mmatus@acms.arizona.edu) (SWIG core, Python, UTL[python,perl,tcl,ruby]) + Art Yerkes (ayerkes@speakeasy.net) (Ocaml) + Lyle Johnson (lyle@users.sourceforge.net) (Ruby) + Charlie Savage (cfis@interserv.com) (Ruby) + Thien-Thi Nguyen (ttn@glug.org) (build/test/misc) + Richard Palmer (richard@magicality.org) (PHP) + Sam Liddicott - Ananova Ltd (saml@liddicott.com) (PHP) + Tim Hockin - Sun Microsystems (thockin@sun.com) (PHP) + Kevin Ruland (PHP) + Shibukawa Yoshiki (Japanese Translation) + Jason Stewart (jason@openinformatics.com) (Perl5) + Loic Dachary (Perl5) + David Fletcher (Perl5) + Gary Holt (Perl5) + Masaki Fukushima (Ruby) + Scott Michel (scottm@cs.ucla.edu) (Java directors) + Tiger Feng (songyanf@cs.uchicago.edu) (SWIG core) + Mark Rose (mrose@stm.lbl.gov) (Directors) + Jonah Beckford (beckford@usermail.com) (CHICKEN) + Ahmon Dancy (dancy@franz.com) (Allegro CL) + Dirk Gerrits (Allegro CL) + Neil Cawse (C#) + Harco de Hilster (Java) + Alexey Dyachenko (dyachenko@fromru.com) (Tcl) + Bob Techentin (Tcl) + Martin Froehlich (Guile) + Marcio Luis Teixeira (Guile) + Duncan Temple Lang (R) + Miklos Vajna (PHP directors) + Mark Gossage (mark@gossage.cjb.net) (Lua) + Raman Gopalan (ramangopalan@gmail.com) (eLua) + Gonzalo Garramuno (ggarra@advancedsl.com.ar) (Ruby, Ruby's UTL) + John Lenz (Guile, MzScheme updates, Chicken module, runtime system) + Baozeng Ding (Scilab) + Ian Lance Taylor (Go) + Vadim Zeitlin (PCRE, Python) + Stefan Zager (szager@gmail.com) (Python) + Vincent Couvert (Scilab) + Sylvestre Ledru (Scilab) + Wolfgang Frisch (Scilab) Past contributors include: James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran Kovuk, Oleg Tolmatcev, Tal Shalif, Lluis Padro, Chris Seatory, Igor Bely, Robin Dunn, Edward Zimmermann, David Ascher, Dominique Dumont, Pier Giorgio Esposito, Hasan Baran Kovuk, - Klaus Wiederänders + Klaus Wiederänders, Richard Beare, Hans Oesterholt. (See CHANGES and CHANGES.current and the bug tracker for a more complete list). Past students: diff --git a/Doc/Devel/cpp11.html b/Doc/Devel/cpp11.html new file mode 100644 index 000000000..fc35465ae --- /dev/null +++ b/Doc/Devel/cpp11.html @@ -0,0 +1,788 @@ + + + + + + + + + + + + + + + +

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

+

Summary

+

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

+

SVN branch

+

branches/gsoc2009-matevz

+

New C++11 features status

+

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

+

Rvalue reference and move semantics [done]

+

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

+

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

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

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

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

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

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

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

+

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

+

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

+

Generalized constant expressions [done]

+

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

+

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

+

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

+

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

+

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

+

Extern template [done]

+

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

+

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

+

Initializer lists [done]

+

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

+

One can now use: +

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

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

+

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

+

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

+

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

+

Uniform initialization [done]

+

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

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

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

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

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

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

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

+

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

+

Type inference [partially done]

+

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

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

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

+

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

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

+Calling operators are allowed as well:

+
decltype(i+j) k = 300;

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

+

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

+

Range-based for-loop [ignored]

+

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

+

Lambda functions and expressions [done]

+

C++11 introduces lambda functions defined as:

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

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

+

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

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

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

+

Lambda functions can be stored using:

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

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

+

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

+

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

+

Alternate function syntax [done]

+

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

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

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

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

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

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

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

+

Concepts, Axioms [ignored]

+

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

+

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

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

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

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

+Definition of the concepts: +

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

+Concept maps allow usage of a specific type: +

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

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

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

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

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

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

+

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

+

Object construction improvement [done]

+

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

+

The syntax is as follows: +

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

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

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

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

+

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

+

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

+

Null pointer constant [done]

+

nullptr is part of the standard library. +

+

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

+

nullptr_t is defined in <cstddef>. +

+

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

+

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

+

Strongly typed enumerations [partially done]

+

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

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

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

+

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

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

+And it can be forward declared as well: +

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

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

+

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

+

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

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

+should be mapped to

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

+Angle bracket [done]

+

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

+

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

+

Explicit conversion operators [done]

+

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

+

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

+

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

+

Template typedefs [partially done]

+

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

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

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

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

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

+

The same goes for the following example:

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

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

+
typedef List<int> intList;

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

+

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

+

Unrestricted unions [done]

+

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

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

+Swig already parses the given syntax.

+

Done: Added testcase cpp11_unrestricted_unions. R11435, R11447

+

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

+

Variadic templates [partially done]

+

The new C++11 offers the following syntax:

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

+This can be used for example:

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

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

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

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

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

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

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

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

+

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

+

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

+

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

+

New string literals [partially done]

+

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

+

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

+

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

+

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

+

User-defined literals [partially done]

+

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

+

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

+

The syntax is similar to other operator overloading functions: +

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

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

+

Other forms are: +

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

+Another possibility is to use variadic templates: +

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

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

+

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

+

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

+

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

+

Thread-local storage [done] +

+

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

+

Syntax: +

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

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

+

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

+

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

+

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

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

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

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

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

+

Done: Added testcase cpp11_default_delete. R11535

+

Type long long int [done]

+

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

+

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

+

Static assertions [done]

+

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

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

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

+

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

+

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

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

+This kind of syntax is already supported by Swig.

+

Done: Added testcase cpp11_sizeof_objects. R11538 +

+

Threading facilities [ignored]

+

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

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

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

+

Tuple types [TODO]

+

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

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

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

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

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

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

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

+

Hash tables [TODO]

+

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

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

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

+

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

+

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

+

Regular expressions [ignored]

+

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

+

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

+

General-purpose smart pointers [done]

+

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

+

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

+

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

+

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

+

Extensible random number facility [ignored]

+

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

+

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

+

Wrapper reference [ignored]

+

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

+

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

+

Polymorphous wrappers for function objects [done]

+

Two features are introduced: +

+
    +
  • The function template wrapper: +

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

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

+Swig already supports the two.

+

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

+

Type traits for metaprogramming [ignored]

+

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

+

Swig already supports the following code: +

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

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

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

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

+

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

+

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

+

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

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

+Swig correctly parses the result_of class.

+

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

+

Done: Added testcase cpp11_result_of. R11534

+ + diff --git a/Doc/Devel/engineering.html b/Doc/Devel/engineering.html index 2e78fbe35..c12eb1328 100644 --- a/Doc/Devel/engineering.html +++ b/Doc/Devel/engineering.html @@ -25,7 +25,7 @@
  • 8. Naming Conventions
  • 9. Visibility
  • 10. Miscellaneous Coding Guidelines -
  • 11. SVN Tagging Conventions +
  • 11. Git Tagging Conventions @@ -119,8 +119,8 @@ are case-insensitive on Windows so this convention will prevent you from inadver creating two files that differ in case-only.

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

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

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

    11. SVN Tagging Conventions

    +

    11. Git Tagging Conventions

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

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

    • Internal tags should start with the developer name and a hyphen. -
    • External tags should start with "v-". +
    • External tags should start with "rel-".
    That's all there is to it. Some example tags: @@ -402,10 +394,8 @@ That's all there is to it. Some example tags:
  • ttn-pre-xml-patch
  • ttn-post-xml-patch
  • ttn-going-on-vacation-so-dutifully-tagging-now -
  • v-1-3-a37-fixes-bug-2432 -
  • v-1-3-a37-fixes-bug-2433 -
  • v-1-3-a37-fixes-bug-2432-again -
  • v-1-3-a37-release +
  • rel-1.3.40 +
  • rel-2.0.9
    diff --git a/Doc/Devel/internals.html b/Doc/Devel/internals.html index d24869d10..c9082d3f6 100644 --- a/Doc/Devel/internals.html +++ b/Doc/Devel/internals.html @@ -42,6 +42,7 @@
  • 7. Debugging SWIG @@ -346,7 +347,7 @@ Delete(a); /* Destroy a */ All objects are referenced counted and given a reference count of 1 when initially created. The Delete() function only destroys an object when the reference count reaches zero. When -an object is placed in a list or hash table, it's reference count is automatically increased. For example: +an object is placed in a list or hash table, its reference count is automatically increased. For example:
    @@ -843,7 +844,7 @@ Returns a type object corresponding to the type string produced by the Swig_cloc
     
  • char *Swig_clocal_deref(DataType *t, char *name)
    This function is the inverse of the clocal() function. Given a type and a name, it produces a string containing the code needed to cast/convert the type produced by -Swig_clocal() back into it's original type. +Swig_clocal() back into its original type.

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

    7.2 Debugging DOH memory allocation problems

    +
    + +

    +The DOH objects are reference counted and use pools for memory allocation. +The implementation is in memory.c. When there are memory corruption problems, +various memory allocator tools are normally used to diagnose problems. These can be used +on SWIG and can be very useful. However, they won't necessarily find use of stale DOH objects, +that is, DOH objects +that are used after they have been deleted. This is because the DOH memory allocator +grabs a chunk of memory from the C memory allocator and manages the usage internally. +Stale DOH object usage can be checked for by defining DOH_DEBUG_MEMORY_POOLS in +memory.c. If an attempt to use an object is made after the reference count is +zero, an assertion is triggered instead of quietly re-using the stale object... +

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

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

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

    17 SWIG and Allegro Common Lisp

    +

    18 SWIG and Allegro Common Lisp

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

      -

      17.1 Basics

      +

      18.1 Basics

      -

      17.1.1 Running SWIG

      +

      18.1.1 Running SWIG

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

      -

      17.1.2 Command Line Options

      +

      18.1.2 Command Line Options

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

    -

    17.1.3 Inserting user code into generated files

    +

    18.1.3 Inserting user code into generated files

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

    -

    17.2 Wrapping Overview

    +

    18.2 Wrapping Overview

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

    -

    17.2.1 Function Wrapping

    +

    18.2.1 Function Wrapping

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

  • -

    17.2.2 Foreign Wrappers

    +

    18.2.2 Foreign Wrappers

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

    -

    17.2.3 FFI Wrappers

    +

    18.2.3 FFI Wrappers

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

    -

    17.2.4 Non-overloaded Defuns

    +

    18.2.4 Non-overloaded Defuns

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

    -

    17.2.5 Overloaded Defuns

    +

    18.2.5 Overloaded Defuns

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

    -

    17.2.6 What about constant and variable access?

    +

    18.2.6 What about constant and variable access?

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

    -

    17.2.7 Object Wrapping

    +

    18.2.7 Object Wrapping

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

    -

    17.3 Wrapping Details

    +

    18.3 Wrapping Details

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

    -

    17.3.1 Namespaces

    +

    18.3.1 Namespaces

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

    -

    17.3.2 Constants

    +

    18.3.2 Constants

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

    -

    17.3.3 Variables

    +

    18.3.3 Variables

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

    17.3.4 Enumerations

    +

    18.3.4 Enumerations

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

    For example, the following header file

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

    17.3.5 Arrays

    +

    18.3.5 Arrays

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

    17.3.6 Classes and Structs and Unions (oh my!)

    +

    18.3.6 Classes and Structs and Unions (oh my!)

    -

    17.3.6.1 CLOS wrapping of

    +

    18.3.6.1 CLOS wrapping of

    @@ -1118,12 +1118,12 @@ namespace BAR { function that returns an object (or pointer/reference) of C/C++ type X, the wrapping defun (or defmethod) on the Lisp side will automatically wrap the pointer returned in an instance - of the apropriate class. This makes it much easier to write and + of the appropriate class. This makes it much easier to write and debug code than if pointers were passed around as a jumble of integer values.

    -

    17.3.6.2 CLOS Inheritance

    +

    18.3.6.2 CLOS Inheritance

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

    -

    17.3.6.3 Member fields and functions

    +

    18.3.6.3 Member fields and functions

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

    -

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

    +

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

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

    -

    17.3.7 Templates

    +

    18.3.7 Templates

    -

    17.3.7.1 Generating wrapper code for templates

    +

    18.3.7.1 Generating wrapper code for templates

    -

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

    -

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

    -

    17.3.8 Typedef, Templates, and Synonym Types

    +

    18.3.8 Typedef, Templates, and Synonym Types

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

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

    17.3.9 Function overloading/Parameter defaulting

    +

    18.3.9 Function overloading/Parameter defaulting

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

    17.3.10 Operator wrapping and Operator overloading

    +

    18.3.10 Operator wrapping and Operator overloading

    @@ -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,28 +1607,28 @@ opoverload> -

    17.3.11 Varargs

    +

    18.3.11 Varargs

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

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

    -

    17.3.12 C++ Exceptions

    +

    18.3.12 C++ Exceptions

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

    -

    17.3.13 Pass by value, pass by reference

    +

    18.3.13 Pass by value, pass by reference

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

    -

    17.4 Typemaps

    +

    18.4 Typemaps

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

    -

    17.4.1 Code Generation in the C++ Wrapper

    +

    18.4.1 Code Generation in the C++ Wrapper

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

    17.4.1.1 IN Typemap

    +

    18.4.1.1 IN Typemap

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

    17.4.1.2 OUT Typemap

    +

    18.4.1.2 OUT Typemap

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

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

    17.4.1.3 CTYPE Typemap

    +

    18.4.1.3 CTYPE Typemap

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

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

    -

    17.4.2 Code generation in Lisp wrappers

    +

    18.4.2 Code generation in Lisp wrappers

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

    -

    17.4.2.1 LIN Typemap

    +

    18.4.2.1 LIN Typemap

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

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

    17.4.2.3 FFITYPE Typemap

    +

    18.4.2.3 FFITYPE Typemap

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

    17.4.2.4 LISPTYPE Typemap

    +

    18.4.2.4 LISPTYPE Typemap

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

    17.4.2.5 LISPCLASS Typemap

    +

    18.4.2.5 LISPCLASS Typemap

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

    17.4.3 Modifying SWIG behavior using typemaps

    +

    18.4.3 Modifying SWIG behavior using typemaps

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

    17.5 Identifier Converter functions

    +

    18.5 Identifier Converter functions

    -

    17.5.1 Creating symbols in the lisp environment

    +

    18.5.1 Creating symbols in the lisp environment

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

    -

    17.5.2 Existing identifier-converter functions

    +

    18.5.2 Existing identifier-converter functions

    Two basic identifier routines have been defined. -

    17.5.2.1 identifier-convert-null

    +

    18.5.2.1 identifier-convert-null

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

    -

    17.5.2.2 identifier-convert-lispify

    +

    18.5.2.2 identifier-convert-lispify

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

    -

    17.5.2.3 Default identifier to symbol conversions

    +

    18.5.2.3 Default identifier to symbol conversions

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

    -

    17.5.3 Defining your own identifier-converter

    +

    18.5.3 Defining your own identifier-converter

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

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

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

    -

    17.5.4 Instructing SWIG to use a particular identifier-converter

    +

    18.5.4 Instructing SWIG to use a particular identifier-converter

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

    18 SWIG and Android

    +

    19 SWIG and Android

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

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

    -

    18.2 Android examples

    +

    19.2 Android examples

    -

    18.2.1 Examples introduction

    +

    19.2.1 Examples introduction

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

    @@ -54,7 +57,7 @@ Add the SDK tools and NDK tools to your path and create a directory somewhere fo
     $ export PATH=$HOME/android/android-sdk-linux_x86/tools:$HOME/android/android-sdk-linux_x86/platform-tools:$HOME/android/android-ndk-r6b:$PATH
     $ mkdir AndroidApps 
    -$ cd AnrdoidApps
    +$ cd AndroidApps
     
    @@ -74,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.

    -

    18.2.2 Simple C example

    +

    19.2.2 Simple C example

    @@ -207,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
     
    @@ -219,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
     
    @@ -396,7 +399,7 @@ Run the app again and this time you will see the output pictured below, showing
    Android screenshot of SwigSimple example
    -

    18.2.3 C++ class example

    +

    19.2.3 C++ class example

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

    Android screenshot of SwigClass example
    +

    19.2.4 Other examples

    + + +

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

    + +

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

    + +

    19.3 C++ STL

    + + +

    +Should the C++ Standard Template Library (STL) be required, an Application.mk file needs to be created +in the same directory as the Android.mk directory containing information about the STL to use. +See the NDK documentation in the $NDKROOT/docs folder especially CPLUSPLUS-SUPPORT.html. +Below is an example of the Application.mk file to make the STLport static library available for use: +

    + +
    +
    +# File: Application.mk
    +APP_STL := gnustl_static
    +
    +
    + + diff --git a/Doc/Manual/Arguments.html b/Doc/Manual/Arguments.html index 1ae9a6d2f..48ec5c629 100644 --- a/Doc/Manual/Arguments.html +++ b/Doc/Manual/Arguments.html @@ -1,12 +1,13 @@ - + Argument Handling + -

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

      -

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

      -

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

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

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

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

    -

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

    -

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

    -

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

    -

    9.2.2 Constraint methods

    +

    10.2.2 Constraint methods

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

    9.2.3 Applying constraints to new datatypes

    +

    10.2.3 Applying constraints to new datatypes

    diff --git a/Doc/Manual/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 new file mode 100644 index 000000000..714845bba --- /dev/null +++ b/Doc/Manual/CPlusPlus11.html @@ -0,0 +1,1184 @@ + + + +SWIG and C++11 + + + + + +

    7 SWIG and C++11

    + + + + + + +

    7.1 Introduction

    + + +

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

    +

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

    + +

    7.2 Core language changes

    + + +

    7.2.1 Rvalue reference and move semantics

    + + +

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

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

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

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

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

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

    7.2.2 Generalized constant expressions

    + + +

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

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

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

    + +

    7.2.3 Extern template

    + + +

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

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

    7.2.4 Initializer lists

    + + +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    + +

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

    + +

    7.2.5 Uniform initialization

    + + +

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

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

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

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

    7.2.6 Type inference

    + + +

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

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

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

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

    7.2.7 Range-based for-loop

    + + +

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

    + +

    7.2.8 Lambda functions and expressions

    + + +

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

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

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

    + +

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

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

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

    + +

    7.2.9 Alternate function syntax

    + + +

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

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

    can now be written as in C++11:

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

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

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

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

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

    7.2.10 Object construction improvement

    + + +

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

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

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

    + +

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

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

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

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

    7.2.11 Explicit overrides and final

    + + +

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

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

    7.2.12 Null pointer constant

    + + +

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

    + +

    7.2.13 Strongly typed enumerations

    + + +

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

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

    +Strongly typed enums are often used to avoid name clashes such as the following: +

    + +
    +struct Color {
    +  enum class RainbowColors : unsigned int {
    +    Red, Orange, Yellow, Green, Blue, Indigo, Violet
    +  };
    +  
    +  enum class WarmColors {
    +    Yellow, Orange, Red
    +  };
    +
    +  // Note normal enum
    +  enum PrimeColors {
    +    Red=100, Green, Blue
    +  };
    +};
    +
    + +

    +There are various ways that the target languages handle enums, so it is not possible to precisely state how they are handled in this section. +However, generally, most scripting languages mangle in the strongly typed enumeration's class name, +but do not use any additional mangling for normal enumerations. For example, in Python, the following code +

    + +
    +print Color.RainbowColors_Red, Color.WarmColors_Red, Color.Red
    +
    + +

    +results in +

    + +
    +0 2 100
    +
    + +

    +The strongly typed languages often wrap normal enums into an enum class and so treat normal enums and strongly typed enums the same. +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

    + + +

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

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

    7.2.15 Explicit conversion operators

    + + +

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

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

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

    + +

    7.2.16 Alias templates

    + + +

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

    +template< typename T1, typename T2, int >
    +class SomeType {
    +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: +

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

    +A warning will be issued: +

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

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

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

    7.2.17 Unrestricted unions

    + + +

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

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

    7.2.18 Variadic templates

    + + +

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

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

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

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

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

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

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

    + +

    7.2.19 New string literals

    + + +

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

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

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

    + +

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

    + +

    7.2.20 User-defined literals

    + + +

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

    + +

    +Some examples are the raw literal: +

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

    +numeric cooked literals: +

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

    +and cooked string literals: +

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

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

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

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

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

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

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

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

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

    7.2.21 Thread-local storage

    + + +

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

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

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

    + +

    7.2.22 Explicitly defaulted functions and deleted functions

    + + +

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

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

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

    + +

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

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

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

    + +

    7.2.23 Type long long int

    + + +

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

    + +

    7.2.24 Static assertions

    + + +

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

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

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

    + + +

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

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

    In Python:

    +
    +>>> SIZE
    +8
    +
    + +

    7.2.26 Exception specifications and noexcept

    + + +

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

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

    7.2.27 Control and query object alignment

    + + +

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

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

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

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

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

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

    7.2.28 Attributes

    + + +

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

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

    7.3 Standard library changes

    + + +

    7.3.1 Threading facilities

    + + +

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

    + +

    7.3.2 Tuple types

    + + +

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

    + +

    7.3.3 Hash tables

    + + +

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

    + +

    7.3.4 Regular expressions

    + + +

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

    + +

    7.3.5 General-purpose smart pointers

    + + +

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

    + +

    7.3.6 Extensible random number facility

    + + +

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

    + +

    7.3.7 Wrapper reference

    + + +

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

    + + +

    7.3.8 Polymorphous wrappers for function objects

    + + +

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

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

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

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

    7.3.9 Type traits for metaprogramming

    + + +

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

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

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

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

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

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

    7.3.10 Uniform method for computing return type of function objects

    + + +

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

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

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

    + +

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

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

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

    + + + diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index b511dc126..26f0c740e 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -1,15 +1,20 @@ - + SWIG and C# + -

    19 SWIG and C#

    +

    20 SWIG and C#

    -
  • Multiples modules +
  • Multiple modules
  • C# Typemap examples
    • Memory management when returning references to member variables
    • Memory management for objects passed to the C++ layer
    • Date marshalling using the csin typemap and associated attributes
    • A date example demonstrating marshalling of C# properties +
    • Date example demonstrating the 'pre' and 'post' typemap attributes for directors
    • Turning wrapped classes into partial classes
    • Extending proxy classes with additional C# code
    • Underlying type for enums @@ -48,7 +54,7 @@ -

      19.1 Introduction

      +

      20.1 Introduction

      @@ -65,10 +71,70 @@ 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.

      -

      19.2 Differences to the Java module

      +

      20.1.1 SWIG 2 Compatibility

      + + +

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

      + + +

      20.1.2 Additional command line options

      + + +

      +The following table lists the additional commandline options available for the C# module. They can also be seen by using: +

      + +
      +swig -csharp -help 
      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      C# specific options
      -dllimport <dl>Override DllImport attribute name to <dl>
      -namespace <nm>Generate wrappers into C# namespace <nm>
      -noproxyGenerate the low-level functional interface instead of proxy classes
      -oldvarnamesOld intermediary method names for variable wrappers
      -outfile <file>Write all C# into a single <file> located in the output directory +
      + +

      +The -outfile option combines all the generated C# code into a single output file instead of creating multiple C# files. +The default, when this option is not provided, is to generate separate .cs files for the module class, +intermediary class and each of the generated proxy and type wrapper classes. +Note that the file extension (.cs) will not be automatically added and needs to be provided. +Due to possible compiler limits it is not advisable to use -outfile for large projects. +

      + +

      20.2 Differences to the Java module

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

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

    Additional typemap attributes:

    + +

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

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

    @@ -220,6 +301,9 @@ $*javaclassname             -> $*csclassname
     $javaclazzname              -> $csclazzname
     $javainput                  -> $csinput
     $jnicall                    -> $imcall
    +$javainterfacename          -> $csinterfacename
    +$&javainterfacename         -> $&csinterfacename
    +$*javainterfacename         -> $*csinterfacename
     
  • @@ -227,10 +311,12 @@ $jnicall -> $imcall

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

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

    19.3 Void pointers

    +

    20.3 Void pointers

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

    -

    19.4 C# Arrays

    +

    20.4 C# Arrays

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

    -

    19.4.1 The SWIG C arrays library

    +

    20.4.1 The SWIG C arrays library

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

    -

    19.4.2 Managed arrays using P/Invoke default array marshalling

    +

    20.4.2 Managed arrays using P/Invoke default array marshalling

    @@ -601,9 +687,9 @@ marshalling for the arrays:

    -[DllImport("example", EntryPoint="CSharp_myArrayCopy")]
    -public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
    -                                      [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
    +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
    +public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
    +                                      [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                            int jarg3);
     
    @@ -651,15 +737,15 @@ and intermediary class method
    -  [DllImport("example", EntryPoint="CSharp_myArraySwap")]
    -  public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
    -                                        [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
    +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArraySwap")]
    +  public static extern void myArraySwap([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
    +                                        [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                              int jarg3);
     
    -

    19.4.3 Managed arrays using pinning

    +

    20.4.3 Managed arrays using pinning

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

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

    19.5 C# Exceptions

    +

    20.5 C# Exceptions

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

    -

    19.5.1 C# exception example using "check" typemap

    +

    20.5.1 C# exception example using "check" typemap

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

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

    -

    19.5.2 C# exception example using %exception

    +

    20.5.2 C# exception example using %exception

    @@ -1048,6 +1134,7 @@ try { $action } catch (std::out_of_range e) { SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what()); + return $null; } %} @@ -1098,7 +1185,7 @@ The managed code generated does check for the pending exception as mentioned ear -

    19.5.3 C# exception example using exception specifications

    +

    20.5.3 C# exception example using exception specifications

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

    -

    19.5.4 Custom C# ApplicationException example

    +

    20.5.4 Custom C# ApplicationException example

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

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

    19.6 C# Directors

    +

    20.6 C# Directors

    @@ -1302,7 +1389,7 @@ The following sections provide information on the C# director implementation and However, the Java directors section should also be read in order to gain more insight into directors.

    -

    19.6.1 Directors example

    +

    20.6.1 Directors example

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

    19.6.2 Directors implementation

    +

    20.6.2 Directors implementation

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

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

    19.6.3 Director caveats

    +

    20.6.3 Director caveats

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

    -

    19.7 Multiples 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. @@ -1692,7 +1776,7 @@ the [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrows if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.

    -

    19.8 C# Typemap examples

    +

    20.8 C# Typemap examples

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

    19.8.1 Memory management when returning references to member variables

    +

    20.8.1 Memory management when returning references to member variables

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

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

    -

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

    +

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

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

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

    19.8.3 Date marshalling using the csin typemap and associated attributes

    +

    20.8.3 Date marshalling using the csin typemap and associated attributes

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

    -public class Action : IDisposable {
    +public class Action : global::System.IDisposable {
       ...
       public Action(CDate dateIn, CDate dateOut) 
           : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
    @@ -2040,13 +2124,13 @@ The typemaps to achieve this are shown below.
     
     
    -%typemap(cstype) const CDate& "System.DateTime"
    +%typemap(cstype) const CDate & "System.DateTime"
     %typemap(csin, 
              pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);"
             ) const CDate &
              "$csclassname.getCPtr(temp$csinput)"
     
    -%typemap(cstype) CDate& "out System.DateTime"
    +%typemap(cstype) CDate & "out System.DateTime"
     %typemap(csin, 
              pre="    CDate temp$csinput = new CDate();", 
              post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
    @@ -2064,7 +2148,7 @@ The resulting generated proxy code in the Action class follows:
     
     
    -public class Action : IDisposable {
    +public class Action : global::System.IDisposable {
       ...
       public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
         CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
    @@ -2082,7 +2166,7 @@ public class Action : IDisposable {
         }
       }
     
    -  static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
    +  static private global::System.IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
         CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
         CDate tempdateOut = new CDate();
         try {
    @@ -2229,7 +2313,7 @@ public class example {
     
    -

    19.8.4 A date example demonstrating marshalling of C# properties

    +

    20.8.4 A date example demonstrating marshalling of C# properties

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

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

    @@ -2282,8 +2366,8 @@ The typemap type required is thus CDate *. Given that the previous sect %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{ /* csvarout typemap code */ get { - IntPtr cPtr = $imcall; - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } %} @@ -2305,8 +2389,8 @@ public class example { } /* csvarout typemap code */ get { - IntPtr cPtr = examplePINVOKE.ImportantDate_get(); - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false); + global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get(); + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false); return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } @@ -2329,8 +2413,69 @@ Some points to note:
  • The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and these are all ignored in the property set. The code in these attributes must instead be replicated within the 'csvarin' typemap. The line creating the temp$csinput variable is such an example; it is identical to what is in the 'pre' attribute. +

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

    -

    19.8.5 Turning wrapped classes into partial classes

    + +

    +The 'pre' and 'post' attributes in the "csdirectorin" typemap act like the attributes of the same name in the "csin" typemap. +For example if we modify the Date marshalling example like this: +

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

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

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

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

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

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

    + + +

    20.8.6 Turning wrapped classes into partial classes

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

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

    -

    19.8.6 Extending proxy classes with additional C# code

    +

    20.8.7 Extending proxy classes with additional C# code

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

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

    19.8.7 Underlying type for enums

    +

    20.8.8 Underlying type for enums

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

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

      -

      20.1 Preliminaries

      +

      21.1 Preliminaries

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

      -

      20.1.1 Running SWIG in C mode

      +

      21.1.1 Running SWIG in C mode

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

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

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

      -

      20.1.2 Running SWIG in C++ mode

      +

      21.1.2 Running SWIG in C++ mode

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

      -

      20.2 Code Generation

      +

      21.2 Code Generation

      -

      20.2.1 Naming Conventions

      +

      21.2.1 Naming Conventions

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

      -

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

      -

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

      -

      20.2.4 Functions

      +

      21.2.4 Functions

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

      -

      20.2.5 Exceptions

      +

      21.2.5 Exceptions

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

    -

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

    -

    20.4 Linkage

    +

    21.4 Linkage

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

    -

    20.4.1 Static binary or shared library linked at compile time

    +

    21.4.1 Static binary or shared library linked at compile time

    We can easily use csc to build a static binary.

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

    -

    20.4.2 Building chicken extension libraries

    +

    21.4.2 Building chicken extension libraries

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

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

    -

    20.4.3 Linking multiple SWIG modules with TinyCLOS

    +

    21.4.3 Linking multiple SWIG modules with TinyCLOS

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

    -

    20.5 Typemaps

    +

    21.5 Typemaps

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

    Lib/chicken/chicken.swg.

    -

    20.6 Pointers

    +

    21.6 Pointers

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

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

    -

    20.6.1 Garbage collection

    +

    21.6.1 Garbage collection

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

    must be called manually.

    -

    20.7 Unsupported features and known problems

    +

    21.7 Unsupported features and known problems

    -

    20.7.1 TinyCLOS problems with Chicken version <= 1.92

    +

    21.7.1 TinyCLOS problems with Chicken version <= 1.92

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

    SWIG Users Manual

    @@ -16,13 +18,23 @@

    @@ -132,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
  • -

    7 Preprocessing

    +

    7 SWIG and C++11

    + + + + + +

    8 Preprocessing

    @@ -275,7 +341,7 @@
    -

    8 SWIG library

    +

    9 SWIG library

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

    9 Argument Handling

    +

    10 Argument Handling

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

    10 Typemaps

    +

    11 Typemaps

    -

    11 Customization Features

    +

    12 Customization Features

    @@ -449,7 +518,7 @@
    -

    12 Contracts

    +

    13 Contracts

    @@ -462,7 +531,7 @@
    -

    13 Variable Length Arguments

    +

    14 Variable Length Arguments

    @@ -480,7 +549,7 @@
    -

    14 Warning Messages

    +

    15 Warning Messages

    @@ -508,7 +577,7 @@
    -

    15 Working with Modules

    +

    16 Working with Modules

    @@ -524,7 +593,7 @@
    -

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

    +

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

    @@ -550,7 +619,7 @@
    -

    17 SWIG and Allegro Common Lisp

    +

    18 SWIG and Allegro Common Lisp

    @@ -634,7 +703,7 @@
    -

    18 SWIG and Android

    +

    19 SWIG and Android

    -

    19 SWIG and C#

    +

    20 SWIG and C#

    -

    20 SWIG and Chicken

    +

    21 SWIG and Chicken

    @@ -730,7 +806,7 @@
    -

    21 SWIG and D

    +

    22 SWIG and D

    -

    22 SWIG and Go

    +

    23 SWIG and Go

    -

    23 SWIG and Guile

    +

    24 SWIG and Guile

    -

    24 SWIG and Java

    +

    25 SWIG and Java

    -

    25 SWIG and Common Lisp

    +

    26 SWIG and Javascript

    + + + + + +

    27 SWIG and Common Lisp

    @@ -996,7 +1134,7 @@
    -

    26 SWIG and Lua

    +

    28 SWIG and Lua

    -

    27 SWIG and Modula-3

    +

    29 SWIG and Modula-3

    @@ -1093,7 +1240,7 @@
    -

    28 SWIG and MzScheme/Racket

    +

    30 SWIG and MzScheme/Racket

    @@ -1105,7 +1252,7 @@
    -

    29 SWIG and Ocaml

    +

    31 SWIG and Ocaml

    -

    30 SWIG and Octave

    +

    32 SWIG and Octave

    -

    31 SWIG and Perl5

    +

    33 SWIG and Perl5

    -

    32 SWIG and PHP

    +

    34 SWIG and PHP

    -

    33 SWIG and Pike

    +

    35 SWIG and Pike

    @@ -1323,7 +1484,7 @@
    -

    34 SWIG and Python

    +

    36 SWIG and Python

    -

    35 SWIG and R

    +

    37 SWIG and R

    @@ -1449,7 +1623,7 @@
    -

    36 SWIG and Ruby

    +

    38 SWIG and Ruby

    -

    37 SWIG and Tcl

    +

    39 SWIG and Scilab

    + + + + + +

    40 SWIG and Tcl

    @@ -1649,7 +1896,7 @@
    -

    38 Extending SWIG to support new languages

    +

    41 Extending SWIG to support new languages

    diff --git a/Doc/Manual/Contract.html b/Doc/Manual/Contract.html index de390fba4..4b4995819 100644 --- a/Doc/Manual/Contract.html +++ b/Doc/Manual/Contract.html @@ -1,12 +1,13 @@ - + Contract Checking + -

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

      -

      12.1 The %contract directive

      +

      13.1 The %contract directive

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

    -

    12.2 %contract and classes

    +

    13.2 %contract and classes

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

    -

    12.3 Constant aggregation and %aggregate_check

    +

    13.3 Constant aggregation and %aggregate_check

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

    -

    12.4 Notes

    +

    13.4 Notes

    diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index b98fbfc88..8705534f9 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -1,12 +1,13 @@ - + Customization Features + -

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

      -

      11.1 Exception handling with %exception

      +

      12.1 Exception handling with %exception

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

      -

      11.1.1 Handling exceptions in C code

      +

      12.1.1 Handling exceptions in C code

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

    -

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

    -

    11.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 {}; -

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

    11.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 */
     
    @@ -437,7 +442,7 @@ declarations.  However, it never really worked that well and the new
     %exception directive is much better.
     

    -

    11.1.6 Special variables for %exception

    +

    12.1.6 Special variables for %exception

    @@ -454,6 +459,11 @@ variables are replaced with. The actual operation to be performed (a function call, method invocation, variable access, etc.) + +$name +The C/C++ symbol name for the function. + + $symname The symbol name used internally by SWIG @@ -479,6 +489,16 @@ variables are replaced with. The fully qualified C/C++ declaration of the method being wrapped including the return type + +$parentclassname +The parent class name (if any) for a method. + + + +$parentclasssymname +The target language parent class name (if any) for a method. + +

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

    -

    11.1.7 Using The SWIG exception library

    +

    12.1.7 Using The SWIG exception library

    The exception.i library file provides support for creating language independent exceptions in your interfaces. To use it, simply put an "%include exception.i" in your interface file. This -creates a function SWIG_exception() that can be used to raise +provides a function SWIG_exception() that can be used to raise common scripting language exceptions in a portable manner. For example :

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

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

    -

    11.2 Object ownership and %newobject

    +

    12.2 Object ownership and %newobject

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

    -

    11.3 Features and the %feature directive

    +

    12.3 Features and the %feature directive

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

    -

    11.3.1 Feature attributes

    +

    12.3.1 Feature attributes

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

    -

    11.3.2 Feature flags

    +

    12.3.2 Feature flags

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

    -

    11.3.3 Clearing features

    +

    12.3.3 Clearing features

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

    11.3.4 Features and default arguments

    +

    12.3.4 Features and default arguments

    @@ -1069,7 +1087,7 @@ For example:

    -%feature("except") void hello(int i=0, double d=0.0) { ... }
    +%feature("except") hello(int i=0, double d=0.0) { ... }
     void hello(int i=0, double d=0.0);
     
    @@ -1092,7 +1110,7 @@ If the default arguments are not specified in the feature:
    -%feature("except") void hello(int i, double d) { ... }
    +%feature("except") hello(int i, double d) { ... }
     void hello(int i=0, double d=0.0);
     
    @@ -1128,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.

    -

    11.3.5 Feature example

    +

    12.3.5 Feature example

    diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html index 43fa69196..9e8e65358 100644 --- a/Doc/Manual/D.html +++ b/Doc/Manual/D.html @@ -1,4 +1,4 @@ - + SWIG and D @@ -6,7 +6,7 @@ -

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

      21.1 Introduction

      +

      22.1 Introduction

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

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

      -

      21.2 Command line invocation

      +

      22.2 Command line invocation

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

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

      21.3 Typemaps

      +

      22.3 Typemaps

      -

      21.3.1 C# <-> D name comparison

      +

      22.3.1 C# <-> D name comparison

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

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

    21.3.2 ctype, imtype, dtype

    +

    22.3.2 ctype, imtype, dtype

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

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

    -

    21.3.3 in, out, directorin, directorout

    +

    22.3.3 in, out, directorin, directorout

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

    -

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

    -

    21.3.4 din, dout, ddirectorin, ddirectorout

    +

    22.3.4 din, dout, ddirectorin, ddirectorout

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

    -

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

    21.3.5 typecheck typemaps

    +

    22.3.5 typecheck typemaps

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

    -

    21.3.6 Code injection typemaps

    +

    22.3.6 Code injection typemaps

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

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

    -

    21.3.7 Special variable macros

    +

    22.3.7 Special variable macros

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

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

    @@ -243,7 +243,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 +263,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 +295,7 @@ $importtype(AnotherInterface) -

    21.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 +325,7 @@ struct A { -

    21.5 Pragmas

    +

    22.5 Pragmas

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

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

    21.6 D Exceptions

    +

    22.6 D Exceptions

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

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

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

    -

    21.7 D Directors

    +

    22.7 D Directors

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

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

    -

    21.8 Other features

    +

    22.8 Other features

    -

    21.8.1 Extended namespace support (nspace)

    +

    22.8.1 Extended namespace support (nspace)

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

    -

    21.8.2 Native pointer support

    +

    22.8.2 Native pointer support

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

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

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

    -

    21.8.3 Operator overloading

    +

    22.8.3 Operator overloading

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

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

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

    -

    21.8.4 Running the test-suite

    +

    22.8.4 Running the test-suite

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

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

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

    -

    21.9 D Typemap examples

    +

    22.9 D Typemap examples

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

    -

    21.10 Work in progress and planned features

    +

    22.10 Work in progress and planned features

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

    diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index c3b2740f4..14dcbdccd 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -1,12 +1,13 @@ - + Extending SWIG to support new languages + -

    38 Extending SWIG to support new languages

    +

    41 Extending SWIG to support new languages

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

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

      -

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

      -

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

      -

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

      -

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

      -

      38.4.2 Parsing

      +

      41.4.2 Parsing

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

      -

      38.4.3 Parse Trees

      +

      41.4.3 Parse Trees

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

    -

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

    -

    38.4.5 Symbol Tables

    +

    41.4.5 Symbol Tables

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

    38.4.6 The %feature directive

    +

    41.4.6 The %feature directive

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

    -

    38.4.7 Code Generation

    +

    41.4.7 Code Generation

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

    -

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

    -

    38.5 Primitive Data Structures

    +

    41.5 Primitive Data Structures

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

    38.5.1 Strings

    +

    41.5.1 Strings

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

    38.5.2 Hashes

    +

    41.5.2 Hashes

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

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

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

    38.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: @@ -1394,7 +1395,7 @@ for (j = First(j); j.item; j= Next(j)) { -

    38.5.6 I/O

    +

    41.5.6 I/O

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

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

    -
    -

    Closes a file. Has no effect on strings.

    -

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

    -
    - -

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

    38.7 Working with attributes

    +

    41.7 Working with attributes

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

    38.8 Type system

    +

    41.8 Type system

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

    -

    38.8.1 String encoding of types

    +

    41.8.1 String encoding of types

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

    -

    38.8.2 Type construction

    +

    41.8.2 Type construction

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

    38.8.3 Type tests

    +

    41.8.3 Type tests

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

    38.8.4 Typedef and inheritance

    +

    41.8.4 Typedef and inheritance

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

    38.8.5 Lvalues

    +

    41.8.5 Lvalues

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

    38.8.6 Output functions

    +

    41.8.6 Output functions

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

    38.9 Parameters

    +

    41.9 Parameters

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

    38.10 Writing a Language Module

    +

    41.10 Writing a Language Module

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

    -

    38.10.1 Execution model

    +

    41.10.1 Execution model

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

    -

    38.10.2 Starting out

    +

    41.10.2 Starting out

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

    -

    38.10.3 Command line options

    +

    41.10.3 Command line options

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

    -

    38.10.4 Configuration and preprocessing

    +

    41.10.4 Configuration and preprocessing

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

    -

    38.10.5 Entry point to code generation

    +

    41.10.5 Entry point to code generation

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

    38.10.6 Module I/O and wrapper skeleton

    +

    41.10.6 Module I/O and wrapper skeleton

    @@ -2761,8 +2759,8 @@ Within SWIG wrappers, there are five main sections. These are (in order)
  • begin: This section is a placeholder for users to put code at the beginning of the C/C++ wrapper file.
  • runtime: This section has most of the common SWIG runtime code.
  • header: This section holds declarations and inclusions from the .i file. -
  • wrapper: This section holds all the wrappering code. -
  • init: This section holds the module initalisation function +
  • wrapper: This section holds all the wrapper code. +
  • init: This section holds the module initialisation function (the entry point for the interpreter).

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

    38.10.7 Low-level code generators

    +

    41.10.7 Low-level code generators

    @@ -2975,7 +2972,7 @@ There are a lot of issues to address.
     virtual int functionWrapper(Node *n) {
    -  /* get useful atributes */
    +  /* get useful attributes */
       String   *name   = Getattr(n,"sym:name");
       SwigType *type   = Getattr(n,"type");
       ParmList *parms  = Getattr(n,"parms");
    @@ -3005,7 +3002,7 @@ virtual int functionWrapper(Node *n) {
       /* write typemaps(in) */
       ....
     
    -  /* write constriants */
    +  /* write constraints */
       ....
     
       /* Emit the function call */
    @@ -3050,7 +3047,7 @@ but without the typemaps, there is still work to do.
     

    -

    38.10.8 Configuration files

    +

    41.10.8 Configuration files

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

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

    -

    38.10.9 Runtime support

    +

    41.10.9 Runtime support

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

    -

    38.10.10 Standard library files

    +

    41.10.10 Standard library files

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

    -

    38.10.11 User examples

    +

    41.10.11 User examples

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

    -

    38.10.12 Test driven development and the test-suite

    +

    41.10.12 Test driven development and the test-suite

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

    -

    38.10.12.1 Running the test-suite

    +

    41.10.12.1 Running the test-suite

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

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

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

    -

    38.10.13 Documentation

    +

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

    + +

    41.10.13 Documentation

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

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

    +

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

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

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

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

    -

    38.10.15 Coding style guidelines

    +

    41.10.15 Coding style guidelines

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

    -

    38.11 Debugging Options

    +

    41.11 Debugging Options

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

    -

    38.12 Guide to parse tree nodes

    +

    41.12 Guide to parse tree nodes

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

    38.13 Further Development Information

    +

    41.13 Further Development Information

    diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 8abeada81..f25e9850b 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -1,19 +1,21 @@ - + SWIG and Go + -

    22 SWIG and Go

    +

    23 SWIG and Go

    @@ -43,44 +57,135 @@ the Go programming language see golang.org.

    -

    22.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 under the names 6g, 8g, or 5g. 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.

    -

    22.2 Running SWIG with Go

    +

    23.2 Examples

    -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. +Working examples can be found in the +SWIG source tree +.

    -

    22.2.1 Additional Commandline Options

    +

    +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

    -These are the command line options for SWIG's GO module. They can +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. +

    + +

    +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

    + + +

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

    @@ -88,28 +193,35 @@ also be seen by using: swig -go -help - +
    - + + + + + + + + + + + - - - - - - - - - - @@ -119,34 +231,49 @@ 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. + + + + + - - - - - + corresponds to the -fgo-prefix option to gccgo. + If -go-pkgpath is used, -go-prefix will be + ignored.
    Go specific optionsGo-specific options
    -cgoGenerate files to be used as input for the Go cgo tool. This + option is required for Go 1.5 and later, and works for Go 1.2 and + later. In the future this option will likely become the + default.
    -intgosize <s>Set the size for the Go type int. This controls the size + that the C/C++ code expects to see. The <s> argument should + be 32 or 64. This option is currently required during the + transition from Go 1.0 to Go 1.1, as the size of int on + 64-bit x86 systems changes between those releases (from 32 bits to + 64 bits). In the future the option may become optional, and SWIG + will assume that the size of int is the size of a C + pointer.
    -gccgo Generate code for gccgo. The default is to generate code for - 6g/8g/5g.
    -gccgo-46Generate code for gccgo 4.6. The default is set by the configure - script. This generates code that does not use some facilities - that are only available in gccgo 4.7 and later.
    -no-gccgo-46Turn off -gccgo-46, whether set by default or earlier - on the command line. + the Go compiler of the Go distribution.
    -soname %lt;name%gt;-use-shlibTell SWIG to emit code that uses a shared library. This is only + meaningful for the Go compiler of the Go distribution, which needs to know at + compile time whether a shared library will be used.
    -soname <name> Set the runtime name of the shared library that the dynamic linker should include at runtime. The default is the package name with ".so" appended. This is only used when generating code for - 6g/8g/5g; when using gccgo, the equivalent name will be taken from - the -soname option passed to the linker.
    -go-pkgpath <pkgpath>When generating code for gccgo, set the pkgpath to use. This + corresponds to the -fgo-pkgpath option to gccgo.
    -go-prefix <prefix> When generating code for gccgo, set the prefix to use. This - corresponds to the -fgo-prefix option to gccgo.
    -long-type-size <s>Set the size for the C/C++ type long. This controls - whether long is converted to the Go type int32 - or int64. The <s> argument should be 32 or 64.
    -

    22.2.2 Go Output Files

    + +

    23.3.2 Generated Wrapper Files

    -

    When generating Go code, SWIG will generate the following - 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 wrapper code:

    • @@ -154,40 +281,34 @@ MODULE.go will contain the Go functions that your Go code will call. These functions will be wrappers for the C++ functions defined by your module. This file should, of course, be compiled with the Go compiler. +
    • MODULE_wrap.c or MODULE_wrap.cxx will contain C/C++ functions will be invoked by the Go wrapper code. This file should be compiled with the -usual C or C++ compiler and linked into a shared library. +usual C or C++ compiler. +
    • MODULE_wrap.h will be generated if you use the directors feature. It provides a definition of the generated C++ director classes. It is generally not necessary to use this file, but in some special cases it may be helpful to include it in your code, compiled with the usual C or C++ compiler. -
    • -If using the gc compiler, MODULE_gc.c will contain C code which should -be compiled with the C compiler distributed as part of the gc compiler: 6c, 8c, -or 5c. It should then be combined with the compiled MODULE.go using -gopack. This file will not be generated when using gccgo. +
    -

    -A typical command sequence would look like this: -

    +

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

    -
    -% swig -go example.i
    -% gcc -c -fpic example.c
    -% gcc -c -fpic example_wrap.c
    -% gcc -shared example.o example_wrap.o -o example.so
    -% 6g example.go
    -% 6c example_gc.c
    -% gopack grc example.a example.6 example_gc.6
    -% 6g main.go  # your code, not generated by SWIG
    -% 6l main.6
    -
    +
      +
    • +MODULE_gc.c will contain C code which should be compiled with the C +compiler distributed as part of the gc compiler. It should then be +combined with the compiled MODULE.go using go tool pack. +
    • +
    -

    22.3 A tour of basic C/C++ wrapping

    + +

    23.4 A tour of basic C/C++ wrapping

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

    -

    22.3.1 Go Package Name

    +

    23.4.1 Go Package Name

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

    -

    22.3.2 Go Names

    +

    23.4.2 Go Names

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

    -

    22.3.3 Go Constants

    +

    23.4.3 Go Constants

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

    22.3.4 Go Enumerations

    +

    23.4.4 Go Enumerations

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

    -

    22.3.5 Go Classes

    +

    23.4.5 Go Classes

    @@ -325,7 +446,7 @@ type MyClass interface { MyMethod() int } -MyClassMyFactoryFunction() MyClass { +func MyClassMyFactoryFunction() MyClass { // swig magic here } @@ -335,7 +456,129 @@ returns a go interface. If the returned pointer can be null, you can check for this by calling the Swigcptr() method.

    -

    22.3.5.1 Go Class Inheritance

    +

    23.4.5.1 Go Class Memory Management

    + + +

    +Calling NewClassName for a C++ class ClassName will allocate +memory using the C++ memory allocator. This memory will not be automatically +freed by Go's garbage collector as the object ownership is not tracked. When +you are done with the C++ object you must free it using +DeleteClassName.
    +
    +The most Go idiomatic way to manage the memory for some C++ class is to call +NewClassName followed by a +defer of +the DeleteClassName call. Using defer ensures that the memory +of the C++ object is freed as soon as the function containing the defer +statement returns. Furthemore defer works great for short-lived +objects and fits nicely C++'s RAII idiom. Example: +

    +
    +
    +func UseClassName(...) ... {
    +  o := NewClassName(...)
    +  defer DeleteClassName(o)
    +  // Use the ClassName object
    +  return ...
    +}
    +
    +
    + +

    +With increasing complexity, especially complex C++ object hierarchies, the +correct placement of defer statements becomes harder and harder as C++ +objects need to be freed in the correct order. This problem can be eased by +keeping a C++ object function local so that it is only available to the function +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...)
    +}
    +
    +func UseClassName(o ClassName, data ...interface{}) (err error) {
    +  // Use the ClassName object and additional data and return error.
    +}
    +
    +func main() {
    +  WithClassName(constructor args, UseClassName, additional data)
    +}
    +
    +
    + +

    +Using defer has limitations though, especially when it comes to +long-lived C++ objects whichs lifetimes are hard to predict. For such C++ +objects a common technique is to store the C++ object into a Go object, and to +use the Go function runtime.SetFinalizer to add a finalizer which frees +the C++ object when the Go object is freed. It is strongly recommended to read +the runtime.SetFinalizer + documentation before using this technique to understand the +runtime.SetFinalizer limitations.
    +

    +

    +Common pitfalls with runtime.SetFinalizer are: +

    +
      +
    • +If a hierarchy of C++ objects will be automatically freed by Go finalizers then +the Go objects that store the C++ objects need to replicate the hierarchy of the +C++ objects to prevent that C++ objects are freed prematurely while other C++ +objects still rely on them. +
    • +
    • +The usage of Go finalizers is problematic with C++'s RAII idiom as it isn't +predictable when the finalizer will run and this might require a Close or Delete +method to be added the Go object that stores a C++ object to mitigate. +
    • +
    • +The Go finalizer function typically runs in a different OS thread which can be +problematic with C++ code that uses thread-local storage. +
    • +
    + +

    +runtime.SetFinalizer Example: +

    +
    +
    +import (
    +  "runtime"
    +  "wrap" // SWIG generated wrapper code
    +)
    +
    +type GoClassName struct {
    +  wcn wrap.ClassName
    +}
    +
    +func NewGoClassName() *GoClassName {
    +  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
    +}
    +
    +func (o *GoClassName) 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.
    +}
    +
    +
    + +

    23.4.5.2 Go Class Inheritance

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

    -

    22.3.6 Go Templates

    +

    23.4.6 Go Templates

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

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

    -

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

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

    -

    22.3.9 Output arguments

    +

    23.4.9 Output arguments

    Because of limitations in the way output arguments are processed in swig, a function with output arguments will not have multiple return values. Instead, you must pass a pointer into the C++ function to tell it where to -store the ouput value. In go, you supply a slice in the place of the output +store the output value. In go, you supply a slice in the place of the output argument.

    For example, suppose you were trying to wrap the modf() function in the @@ -558,7 +1302,7 @@ void f(char *output); -

    22.3.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 @@ -627,9 +1371,174 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) { few, then you might as well define your own struct that includes the swig-wrapped object, instead of adding methods to the swig-generated object.

    -

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

    +

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

    +
    +
    +%go_import("fmt", _ "unusedPackage", rp "renamed/package")
    +
    +%insert(go_wrapper) %{
    +
    +func foo() {
    +  fmt.Println("Some string:", rp.GetString())
    +}
    +
    +// Importing the same package twice is permitted,
    +// Go code will be generated with only the first instance of the import.
    +%go_import("fmt")
    +
    +%insert(go_wrapper) %{
    +
    +func bar() {
    +  fmt.Println("Hello world!")
    +}
    +
    +%}
    +
    +
    + +

    23.4.11 Go typemaps

    + + +

    +You can use the %typemap directive to modify SWIG's default +wrapping behavior for specific C/C++ types. You need to be familiar +with the material in the general +"Typemaps" chapter. That chapter +explains how to define a typemap. This section describes some +specific typemaps used for Go. +

    + +

    +In general type conversion code may be written either in C/C++ or in +Go. The choice to make normally depends on where memory should be +allocated. To allocate memory controlled by the Go garbage collector, +write Go code. To allocate memory in the C/C++ heap, write C code. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TypemapDescription
    gotype +The Go type to use for a C++ type. This type will appear in the +generated Go wrapper function. If this is not defined SWIG will use a +default as described above. +
    imtype +An intermediate Go type used by the "goin", "goout", "godirectorin", +and "godirectorout" typemaps. If this typemap is not defined for a +C/C++ type, the gotype typemape will be used. This is useful when +gotype is best converted to C/C++ using Go code. +
    goin +Go code to convert from gotype to imtype when calling a C/C++ +function. SWIG will then internally convert imtype to a C/C++ type +and pass it down. If this is not defined, or is the empty string, no +conversion is done. +
    in +C/C++ code to convert the internally generated C/C++ type, based on +imtype, into the C/C++ type that a function call expects. If this is +not defined the value will simply be cast to the desired type. +
    out +C/C++ code to convert the C/C++ type that a function call returns into +the internally generated C/C++ type, based on imtype, that will be +returned to Go. If this is not defined the value will simply be cast +to the desired type. +
    goout +Go code to convert a value returned from a C/C++ function from imtype +to gotype. If this is not defined, or is the empty string, no +conversion is done. +
    argout +C/C++ code to adjust an argument value when returning from a function. +This is called after the real C/C++ function has run. This uses the +internally generated C/C++ type, based on imtype. This is only useful +for a pointer type of some sort. If this is not defined nothing will +be done. +
    goargout +Go code to adjust an argument value when returning from a function. +This is called after the real C/C++ function has run. The value will +be in imtype. This is only useful for a pointer type of some sort. +If this is not defined, or is the empty string, nothing will be done. +
    directorin +C/C++ code to convert the C/C++ type used to call a director method +into the internally generated C/C++ type, based on imtype, that will +be passed to Go. If this is not defined the value will simply be cast +to the desired type. +
    godirectorin +Go code to convert a value used to call a director method from imtype +to gotype. If this is not defined, or is the empty string, no +conversion is done. +
    godirectorout +Go code to convert a value returned from a director method from gotype +to imtype. If this is not defined, or is the empty string, no +conversion is done. +
    directorout +C/C++ code to convert a value returned from a director method from the +internally generated C/C++ type, based on imtype, into the type that +the method should return If this is not defined the value will simply +be cast to the desired type. +
    + diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 6f1300492..f30e139e5 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -1,19 +1,20 @@ - - + SWIG and Guile + -

    23 SWIG and Guile

    +

    24 SWIG and Guile

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

        This section details guile-specific support in SWIG. -

        23.1 Meaning of "Module"

        +

        24.1 Supported Guile Versions

        + + +

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

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

        24.2 Meaning of "Module"

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

        23.2 Using the SCM or GH Guile API

        +

        24.3 Old GH Guile API

        -

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

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

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

        -
        +

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

        - -

        This file is parsed by SWIG at wrapper generation time, so every reference to a gh_ function is replaced -by a scm_ function in the wrapper file. Thus the gh_ function calls will never be seen in the wrapper; -the wrapper will look exactly like it was generated -for the specific API. Currently only the guile language module has created a mapping policy from gh_ to scm_, -but there is no reason other languages (like mzscheme or chicken) couldn't also use this. -If that happens, there is A LOT less code duplication in the standard typemaps.

        - -

        23.3 Linkage

        +

        24.4 Linkage

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

        23.3.1 Simple Linkage

        +

        24.4.1 Simple Linkage

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

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

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

        + +
        +
        +(load-extension "./libexample" "SWIG_init")
         
        @@ -171,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))
         
        @@ -190,7 +177,7 @@ information by including a directive like this in the interface file:
        -%scheme %{ (load-extension "./example.so" "SWIG_init") %}
        +%scheme %{ (load-extension "./libexample.so" "SWIG_init") %}
         
        @@ -206,7 +193,7 @@ placed between the define-module form and the SWIG_init via a preprocessor define to avoid symbol clashes. For this case, however, passive linkage is available. -

        23.3.2 Passive Linkage

        +

        24.4.2 Passive Linkage

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

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

        23.3.3 Native Guile Module Linkage

        +

        24.4.3 Native Guile Module Linkage

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

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

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

      23.3.4 Old Auto-Loading Guile Module Linkage

      +

      24.4.4 Old Auto-Loading Guile Module Linkage

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

      23.3.5 Hobbit4D Linkage

      +

      24.4.5 Hobbit4D Linkage

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

      -

      23.4 Underscore Folding

      +

      24.5 Underscore Folding

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

      23.5 Typemaps

      +

      24.6 Typemaps

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

      -

      23.6 Representation of pointers as smobs

      +

      24.7 Representation of pointers as smobs

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

      23.6.1 GH Smobs

      +

      24.7.1 Smobs

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

      -

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

      - -

      23.6.2 SCM Smobs

      - - -

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

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

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

      -

      23.6.3 Garbage Collection

      +

      24.7.2 Garbage Collection

      -

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

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

      24.8 Exception Handling

      @@ -500,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");
       
      @@ -517,14 +479,13 @@ mapping: The default when not specified here is to use "swig-error". See Lib/exception.i for details. -

      23.8 Procedure documentation

      +

      24.9 Procedure documentation

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

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

      23.9 Procedures with setters

      +

      24.10 Procedures with setters

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

      23.10 GOOPS Proxy Classes

      +

      24.11 GOOPS Proxy Classes

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

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

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

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

      -

      23.10.1 Naming Issues

      +

      24.11.1 Naming Issues

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

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

    23.10.2 Linking

    +

    24.11.2 Linking

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

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

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

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

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

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

    @@ -862,7 +820,7 @@ Produces the following code at the top of the generated GOOPS guile-module (define-module (my modules foo)) ;; %goops directive goes here (if any) -(load-extension "./foo.so" "scm_init_my_modules_foo_module") +(load-extension "./libfoo.so" "scm_init_my_modules_foo_module") (use-modules (oop goops) (Swig common)) (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index a8d15a5c2..1c29f4760 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -1,12 +1,13 @@ - + Introduction + -

    2 Introduction

    +

    2 Introduction

      @@ -31,14 +32,14 @@ -

      2.1 What is SWIG?

      +

      2.1 What is SWIG?

      SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs. In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates -the wrappers needed to access those declarations from other languages including +the wrappers needed to access those declarations from other languages including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally requires no modifications to existing code and can often be used to build a usable interface in only a few minutes. Possible applications @@ -49,7 +50,7 @@ of SWIG include:

    • Building interpreted interfaces to existing C programs.
    • Rapid prototyping and application development.
    • Interactive debugging. -
    • Reengineering or refactoring of legacy software into a scripting language components. +
    • Reengineering or refactoring of legacy software into scripting language components.
    • Making a graphical user interface (using Tk for example).
    • Testing of C libraries and programs (using scripts).
    • Building high performance C modules for scripting languages. @@ -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?

      @@ -98,7 +99,7 @@ of other libraries).

    • Testing is time consuming (the compile/debug cycle).
    • Not easy to reconfigure or customize without recompilation.
    • Modularization can be tricky. -
    • Security concerns (buffer overflow for instance). +
    • Security concerns (buffer overflows for instance).

    To address these limitations, many programmers have arrived at the @@ -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,8 +336,7 @@ major features include:

    -Currently, the only major C++ feature not supported is nested classes--a limitation -that should be removed in a future release, but has some workarounds for the moment. +Most of C++11 is also supported. Details are in the C++11 section.

    @@ -345,11 +346,11 @@ not only parses C++, it implements the full C++ type system and it is able to understand C++ semantics. SWIG generates its wrappers with full knowledge of this information. As a result, you will find SWIG to be just as capable of dealing with nasty corner cases as it is in -wrapping simple C++ code. In fact, SWIG is able handle C++ code that +wrapping simple C++ code. In fact, SWIG is able to handle C++ code that stresses the very limits of many C++ compilers. -

    2.5 Non-intrusive interface building

    +

    2.5 Non-intrusive interface building

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

    @@ -384,12 +385,12 @@ for further information on this and other Autoconf macros.

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

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

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

    -

    2.8 SWIG and freedom

    +

    2.8 SWIG and freedom

    @@ -449,7 +450,7 @@ to work with complicated and unusual C/C++ applications.

    Ironically, the freedom that SWIG provides is countered by an -extremely conservative approach to code generation. At it's core, SWIG +extremely conservative approach to code generation. At its core, SWIG tries to distill even the most advanced C++ code down to a small well-defined set of interface building techniques based on ANSI C programming. Because of this, you will find that SWIG interfaces can @@ -458,6 +459,12 @@ be used on any platform. Again, this is an important part of staying out of the programmer's way----the last thing any developer wants to do is to spend their time debugging the output of a tool that relies on non-portable or unreliable programming features. +Dependencies are often a source of incompatibilities and problems and so +additional third party libraries are not used in the generated code. +SWIG will also generally avoid generating code that introduces a dependency +on the C++ Standard Template Library (STL). +SWIG will generate code that depends on the C libraries though. +

    diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 76e147be5..d3c592674 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -1,11 +1,12 @@ - + SWIG and Java + -

    24 SWIG and Java

    +

    25 SWIG and Java

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

    -

    24.1 Overview

    +

    25.1 Overview

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

    -

    24.2 Preliminaries

    +

    25.2 Preliminaries

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

    -

    24.2.1 Running SWIG

    +

    25.2.1 Running SWIG

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

    -

    24.2.2 Additional Commandline Options

    +

    25.2.2 Additional Commandline Options

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

    -

    24.2.3 Getting the right header files

    +

    25.2.3 Getting the right header files

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

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

    -

    24.2.4 Compiling a dynamic module

    +

    25.2.4 Compiling a dynamic module

    The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. -To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):

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

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

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

    @@ -355,9 +362,9 @@ more aggressive from gcc-4.0 onwards and will result in code that fails with str

    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.

    +The name of the module is specified using the %module directive or -module command line option.

    -

    24.2.5 Using your module

    +

    25.2.5 Using your module

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

    -

    24.2.6 Dynamic linking problems

    +

    25.2.6 Dynamic linking problems

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

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

    -

    24.2.7 Compilation problems and compiling with C++

    +

    25.2.7 Compilation problems and compiling with C++

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

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

    -

    24.2.8 Building on Windows

    +

    25.2.8 Building on Windows

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

    -

    24.2.8.1 Running SWIG from Visual Studio

    +

    25.2.8.1 Running SWIG from Visual Studio

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

    -

    24.2.8.2 Using NMAKE

    +

    25.2.8.2 Using NMAKE

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

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

    -

    24.3 A tour of basic C/C++ wrapping

    +

    25.3 A tour of basic C/C++ wrapping

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

    -

    24.3.1 Modules, packages and generated Java classes

    +

    25.3.1 Modules, packages and generated Java classes

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

    -

    24.3.2 Functions

    +

    25.3.2 Functions

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

    24.3.3 Global variables

    +

    25.3.3 Global variables

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

    24.3.4 Constants

    +

    25.3.4 Constants

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

    -

    24.3.5 Enumerations

    +

    25.3.5 Enumerations

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

    -

    24.3.5.1 Anonymous enums

    +

    25.3.5.1 Anonymous enums

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

    -

    24.3.5.2 Typesafe enums

    +

    25.3.5.2 Typesafe enums

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

    -

    24.3.5.3 Proper Java enums

    +

    25.3.5.3 Proper Java enums

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

    -

    24.3.5.4 Type unsafe enums

    +

    25.3.5.4 Type unsafe enums

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

    -

    24.3.5.5 Simple enums

    +

    25.3.5.5 Simple enums

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

    -

    24.3.6 Pointers

    +

    25.3.6 Pointers

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

    -

    24.3.7 Structures

    +

    25.3.7 Structures

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

     struct Vector {
    -	double x,y,z;
    +  double x,y,z;
     };
     
     
    @@ -1493,7 +1499,7 @@ x.setA(3); // Modify x.a - this is the same as b.f.a -

    24.3.8 C++ classes

    +

    25.3.8 C++ classes

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

    24.3.9 C++ inheritance

    +

    25.3.9 C++ inheritance

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

    -

    24.3.10 Pointers, references, arrays and pass by value

    +

    25.3.10 Pointers, references, arrays and pass by value

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

    -

    24.3.10.1 Null pointers

    +

    25.3.10.1 Null pointers

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

    -

    24.3.11 C++ overloaded functions

    +

    25.3.11 C++ overloaded functions

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

    24.3.12 C++ default arguments

    +

    25.3.12 C++ default arguments

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

    -

    24.3.13 C++ namespaces

    +

    25.3.13 C++ namespaces

    @@ -1921,25 +1927,30 @@ The default behaviour described above can be improved via the

    -example.i:16: Error: The nspace feature used on 'MyWorld::Material::Color' is not supported unless
    -a package is specified
    -with -package - Java does not support types declared in a named package accessing types declared
    -in an unnamed package.
    +example.i:16: Warning 826: The nspace feature is used on 'MyWorld::Material::Color' without -package. The generated code 
    +may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package.
     
    +

    +If it is undesirable to have a single top level package, the nspace feature may be used without the -package commandline option +(and the resulting warning ignored) if all of the types exposed using SWIG are placed in a package using the nspace feature and the +'jniclasspackage' pragma is used to specify a package for the JNI intermediary class. +

    +

    If the resulting use of the nspace feature and hence packages results in a proxy class in one package deriving or using a proxy class from another package, you will need to open up the visibility for the pointer constructor and getCPtr method from the default 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. See Java code typemaps.

    -

    24.3.14 C++ templates

    +

    25.3.14 C++ templates

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

    -

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

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

    24.4 Further details on the generated Java classes

    +

    25.4 Further details on the generated Java classes

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

    -

    24.4.1 The intermediary JNI class

    +

    25.4.1 The intermediary JNI class

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

    -

    24.4.1.1 The intermediary JNI class pragmas

    +

    25.4.1.1 The intermediary JNI class pragmas

    @@ -2223,6 +2248,9 @@ The intermediary JNI class can be tailored through the use of pragmas, but is no jniclassbase Base class for the intermediary JNI class + + jniclasspackage Package in which to place the intermediary JNI class + jniclassclassmodifiers Class modifiers and class type for the intermediary JNI class @@ -2261,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); @@ -2286,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.

    -

    24.4.2 The Java module class

    +

    25.4.2 The Java module class

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

    -

    24.4.2.1 The Java module class pragmas

    +

    25.4.2.1 The Java module class pragmas

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

    -

    24.4.3 Java proxy classes

    +

    25.4.3 Java proxy classes

    @@ -2380,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;
    @@ -2431,7 +2459,7 @@ It also contains all the methods in the C++ class it is proxying plus getters an
     member variables. These functions call the native methods in the intermediary JNI class. 
     The advantage of having this extra layer is the type safety that the proxy class functions offer. 
     It adds static type checking which leads to fewer surprises at runtime. 
    -For example, you can see that if you attempt to use the  spam()  
    +For example, you can see that if you attempt to use the spam()
     function it will only compile when the parameters passed are an int and a Foo. 
     From a user's point of view, it makes the class work as if it were a Java class:
     

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

    24.4.3.1 Memory management

    +

    25.4.3.1 Memory management

    @@ -2606,7 +2634,7 @@ and

    -

    24.4.3.2 Inheritance

    +

    25.4.3.2 Inheritance

    @@ -2631,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;
    @@ -2672,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);
    @@ -2722,7 +2750,7 @@ However, true cross language polymorphism can be achieved using the 24.4.3.3 Proxy classes and garbage collection
    +

    25.4.3.3 Proxy classes and garbage collection

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

    -

    24.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

    +

    25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

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

    -

    24.4.3.5 Single threaded applications and thread safety

    +

    25.4.3.5 Single threaded applications and thread safety

    @@ -2950,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;
    @@ -3015,7 +3043,7 @@ for (int i=0; i<100000; i++) {
     
    -

    24.4.4 Type wrapper classes

    +

    25.4.4 Type wrapper classes

    @@ -3024,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;
    @@ -3102,7 +3130,7 @@ public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
     
    -

    24.4.5 Enum classes

    +

    25.4.5 Enum classes

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

    -

    24.4.5.1 Typesafe enum classes

    +

    25.4.5.1 Typesafe enum classes

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

    -

    24.4.5.2 Proper Java enum classes

    +

    25.4.5.2 Proper Java enum classes

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

    -

    24.4.5.3 Type unsafe enum classes

    +

    25.4.5.3 Type unsafe enum classes

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

    -

    24.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)Proxy class name is unchanged, interface name has SwigInterface added as a suffix for C++ class CTYPE.
    %interface_impl(CTYPE)Proxy class name has SwigImpl as a suffix, interface name has SwigInterface added as a suffix for C++ class CTYPE.
    %interface_custom("PROXY", "INTERFACE", CTYPE)Proxy class name is given by the string PROXY, interface name is given by the string INTERFACE for C++ class CTYPE. 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. +

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

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

    -

    24.5.1 Enabling directors

    +

    25.5.1 Enabling directors

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

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

    24.5.2 Director classes

    +

    25.5.2 Director classes

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

    -

    24.5.3 Overhead and code bloat

    +

    25.5.3 Overhead and code bloat

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

    -

    24.5.4 Simple directors example

    +

    25.5.4 Simple directors example

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

    24.5.5 Director threading issues

    +

    25.5.5 Director threading issues

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

    24.6 Accessing protected members

    +

    25.5.6 Director performance tuning

    + + +

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

    + +

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

    + +
    +
    +%feature("director", assumeoverride=1) Foo;
    +
    +
    + +

    +The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++. As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical. +

    + +

    25.5.7 Java exceptions from directors

    + + +

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

    + +

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

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

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

    + +

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

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

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

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

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

    + +

    +Consider the following director method: +

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

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

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

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

    + +

    Because the default code generation maps any unhandled Java exceptions to +Swig::DirectorException, any director methods that have exception +specifications may cause program termination. To simply ignore +unexpected exceptions, the default handling can be changed with: +

    + +
    +
    +%feature("director:except") %{
    +   jthrowable $error = jenv->ExceptionOccurred();
    +   if ($error) {
    +     jenv->ExceptionClear();
    +     $directorthrowshandlers
    +     return $null; // exception is ignored
    +   }
    +%}
    +
    +
    + +

    Alternatively an exception compatible with the existing director +method exception specifications can be thrown. Assuming that all +methods allow std::runtime_error to be thrown, +the return $null; could be changed to: +

    + +
    +
    +   throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
    +
    +
    + +

    In more complex situations, a separate director:except feature +may need to be attached to specific methods. +

    + +

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

    +
    +%module(directors="1") example
    +
    +%{
    +  #include <string>
    +  #include <stdexcept>
    +%}
    +
    +// Define exceptions in header section using std::runtime_error
    +%define DEFINE_EXCEPTION(NAME)
    +%{
    +  namespace MyNS {
    +    struct NAME : public std::runtime_error { NAME(const std::string &what) : runtime_error(what) {} };
    +  }
    +%}
    +%enddef
    +
    +// Expose C++ exceptions as Java Exceptions by changing the Java base class and providing a getMessage()
    +%define DECLARE_EXCEPTION(NAME)
    +%typemap(javabase) MyNS::NAME "java.lang.Exception";
    +%rename(getMessage) MyNS::NAME::what;
    +namespace MyNS {
    +  struct NAME {
    +    NAME(const std::string& what);
    +    const char * what();
    +  };
    +}
    +%enddef
    +
    +DEFINE_EXCEPTION(ExceptionA)
    +DEFINE_EXCEPTION(ExceptionB)
    +DEFINE_EXCEPTION(Unexpected)
    +
    +// Mark three methods to map director thrown exceptions.
    +%feature("director:except") MyClass::meth1(int);
    +%feature("director:except") MyClass::meth2;
    +%feature("director:except") meth3;
    +
    +%typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{
    +  if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname"))
    +    throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message());
    +%}
    +
    +DECLARE_EXCEPTION(ExceptionA)
    +DECLARE_EXCEPTION(ExceptionB)
    +DECLARE_EXCEPTION(Unexpected)
    +
    +%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2();
    +
    +%inline {
    +  class MyClass {
    +  public:
    +    virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0;
    +    virtual void meth2() = 0;   /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */
    +    virtual void meth3(float x) throw(MyNS::Unexpected) = 0;
    +    virtual ~MyClass() {}
    +  };
    +}
    +
    +
    + +

    +In this case the three different "directorthrows" typemaps will be used +to generate the three different exception handlers for +meth1, meth2 and meth3. The generated +handlers will have "if" blocks for each exception type specified, in +the exception specification or %catches feature. +

    + +

    Note that the "directorthrows" typemaps are important +only if it is important for the the exceptions passed through the C++ +layer to be mapped to distinct C++ exceptions. If director methods +are being called by C++ code that is itself wrapped in a +SWIG generated Java wrapper and access is always through this wrapper, +the default Swig::DirectorException class provides enough information +to reconstruct the original exception. In this case removing the +$directorthrowshandlers special variable from the +default director:except feature and simply always +throwing a Swig::DirectorException will achieve the desired result. +Along with this a generic exception feature is added to convert any +caught Swig::DirectorExceptions back into the underlying +Java exceptions via the Swig::DirectorException::raiseJavaException method, +as demonstrated with %javaexception below: +

    + +
    +
    +%javaexception("Exception") MyClass::myMethod %{
    +  try {
    +    $action
    +  } catch (Swig::DirectorException &e) {
    +    // raise/throw the Java exception that originally caused the DirectorException
    +    e.raiseJavaException(jenv);
    +    return $null;
    +  }
    +%}
    +
    +
    + +

    +See the Exception handling with %exception and %javaexception +section for more on converting C++ exceptions to Java exceptions. +

    + +

    25.6 Accessing protected members

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

    24.7 Common customization features

    +

    25.7 Common customization features

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

    -

    24.7.1 C/C++ helper functions

    +

    25.7.1 C/C++ helper functions

    @@ -3701,7 +4300,7 @@ hard to implement. It is possible to improve on this using Java code, typemaps, customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.

    -

    24.7.2 Class extension with %extend

    +

    25.7.2 Class extension with %extend

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

    -

    24.7.3 Exception handling with %exception and %javaexception

    +

    25.7.3 Exception handling with %exception and %javaexception

    @@ -3837,8 +4436,8 @@ void *malloc(size_t nbytes);

    If no declaration name is given to %exception, it is applied to all wrapper functions. -The $action is a SWIG special variable and is replaced by the C/C++ function call being wrapped. -The return $null; handles all native method return types, namely those that have a void return and those that do not. +The $action is a SWIG special variable and is replaced by the C/C++ function call being wrapped. +The return $null; handles all native method return types, namely those that have a void return and those that do not. This is useful for typemaps that will be used in native method returning all return types. See the section on Java special variables for further explanation. @@ -3923,7 +4522,7 @@ to raise exceptions. See the SWIG Library ch The typemap example Handling C++ exception specifications as Java exceptions provides further exception handling capabilities.

    -

    24.7.4 Method access with %javamethodmodifiers

    +

    25.7.4 Method access with %javamethodmodifiers

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

    24.8 Tips and techniques

    +

    25.8 Tips and techniques

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

    -

    24.8.1 Input and output parameters using primitive pointers and references

    +

    25.8.1 Input and output parameters using primitive pointers and references

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

    -

    24.8.2 Simple pointers

    +

    25.8.2 Simple pointers

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

    -

    24.8.3 Wrapping C arrays with Java arrays

    +

    25.8.3 Wrapping C arrays with Java arrays

    @@ -4266,7 +4865,7 @@ Please be aware that the typemaps in this library are not efficient as all the e There is an alternative approach using the SWIG array library and this is covered in the next section.

    -

    24.8.4 Unbounded C Arrays

    +

    25.8.4 Unbounded C Arrays

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

    -

    24.8.5 Binary data vs Strings

    +

    25.8.5 Binary data vs Strings

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

    24.8.6 Overriding new and delete to allocate from Java heap

    +

    25.8.6 Overriding new and delete to allocate from Java heap

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

    -

    24.9 Java typemaps

    +

    25.9 Java typemaps

    @@ -4593,7 +5192,7 @@ Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the generated code. -

    24.9.1 Default primitive type mappings

    +

    25.9.1 Default primitive type mappings

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

    -

    24.9.2 Default typemaps for non-primitive types

    +

    25.9.2 Default typemaps for non-primitive types

    @@ -4760,7 +5359,7 @@ So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit The Java type is either the proxy class or type wrapper class.

    -

    24.9.3 Sixty four bit JVMs

    +

    25.9.3 Sixty four bit JVMs

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

    -

    24.9.4 What is a typemap?

    +

    25.9.4 What is a typemap?

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

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

    +

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

    @@ -5154,9 +5753,18 @@ These are listed below: Use for mapping NULL terminated arrays of C strings to Java String arrays + +unsigned char * +NIOBUFFER +various.i +input
    output +java.nio.Buffer +Use for mapping directly allocated buffers to c/c++. useful with directors and long lived memory objects + + -

    24.9.6 Java typemap attributes

    +

    25.9.6 Java typemap attributes

    @@ -5202,7 +5810,7 @@ The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' attributes. Note that when the 'pre' or 'post' attributes are specified and the associated type is used in a constructor, a constructor helper function is generated. This is necessary as the Java proxy constructor wrapper makes a call to a support constructor using a this call. In Java the this call must be the first statement in the constructor body. The constructor body thus calls the helper function and the helper function instead makes the JNI call, ensuring the 'pre' code is called before the JNI call is made. There is a Date marshalling example showing 'pre', 'post' and 'pgcppname' attributes in action.

    -

    24.9.7 Java special variables

    +

    25.9.7 Java special variables

    @@ -5223,6 +5831,8 @@ For example, $javaclassname is replaced by the proxy classname Foo< expands to the proxy classname when wrapping Foo *&. If the type does not have an associated proxy class, it expands to the type wrapper class name, for example, SWIGTYPE_p_unsigned_short is generated when wrapping unsigned short *. +The class name is fully qualified with the package name when using the +nspace feature.

    @@ -5234,7 +5844,7 @@ This special variable is usually used for making calls to a function in the inte

    -$null
    +$null
    Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:

    @@ -5338,7 +5948,7 @@ can be wrapped with the Java equivalent, that is, static inner proxy classes.

    -$jniinput, $javacall and $packagepath
    +$error, $jniinput, $javacall and $packagepath
    These special variables are used in the directors typemaps. See Director specific typemaps for details.

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

    -

    24.9.8 Typemaps for both C and C++ compilation

    +

    +$javainterfacename
    +This special variable is only expanded when the interface feature is applied to a class. +It works much like $javaclassname, but instead of expanding to the proxy classname, +it expands to the value in the name attribute in the interface feature. +For example: +

    + +
    +%feature("interface", name="MyInterface") MyClass;
    +%typemap(jstype) MyClass  "$&javainterfacename"
    +%typemap(jstype) MyClass * "$javainterfacename"
    +
    + +

    +will result in the jstype typemap expanding to MyInterface for both +MyClass and MyClass *. +The interface name is fully qualified with the package name when using the +nspace feature. +

    + +

    +$interfacename
    +This special variable is only expanded when the interface feature is applied to a class. +It expands to just the interface name and is thus different to $javainterfacename +in that it is not fully qualified with the package name when using the +nspace feature. +

    + +

    25.9.8 Typemaps for both C and C++ compilation

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

    -

    24.9.9 Java code typemaps

    +

    25.9.9 Java code typemaps

    @@ -5468,11 +6107,57 @@ interfaces (implements) for Java class: empty default

    %typemap(javafinalize)

    the finalize() method (proxy classes only): default calls the delete() method + +

    +Note that the default javafinalize typemap must contain the full implementation of the finalize method. +Any customization to this typemap must still declare a java finalize method with the correct signature. +Note also that the name of the generated "delete" method may be affected by javadestruct and javadestruct_derived typemaps. +Below shows an example modifying the finalizer, assuming the delete method has been renamed to swig_delete. +

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

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

    +
    +

    +The code in this typemap is added to the body of a Java proxy class but only when a class is +marked with the interface feature. +The typemap is used in the proxy class marked with the interface feature as well as all proxy classes derived from the marked C++ class, +as they are all generated as implementing the Java interface. +The default typemap used in the %interface family of macros mentioned in +the Java interfaces section, +where CTYPE is the C++ class macro argument, +is as follows: +

    + +
    +%typemap(javainterfacecode,
    +         declaration="  long $interfacename_GetInterfaceCPtr();\n",
    +         cptrmethod="$interfacename_GetInterfaceCPtr") CTYPE %{
    +  public long $interfacename_GetInterfaceCPtr() {
    +    return $imclassname.$javaclazzname$interfacename_GetInterfaceCPtr(swigCPtr);
    +  }
    +%}
    +
    +
    + +

    +The special variable $interfacename is expanded into the +name specified in the interface feature. +

    +

    Compatibility Note: In SWIG-1.3.21 and earlier releases, typemaps called "javagetcptr" and "javaptrconstructormodifiers" were available. These are deprecated and the "javabody" typemap can be used instead. +The javainterfacecode typemap and interface feature was introduced in SWIG-3.0.9.

    @@ -5488,6 +6173,7 @@ In summary the contents of the typemaps make up a proxy class like this: [ javafinalize typemap ] public synchronized void delete() [ javadestruct OR javadestruct_derived typemap ] [ javacode typemap ] +[ javainterfacecode typemap] ... proxy functions ... } @@ -5497,6 +6183,11 @@ public synchronized void delete() [ javadestruct OR javadestruct_derived Note the delete() methodname and method modifiers are configurable, see "javadestruct" and "javadestruct_derived" typemaps above.

    +

    +The javainterfacecode typemap is only used when bases are marked by the interface +feature and the implements list will also then be expanded to include these Java interfaces. +

    +

    The type wrapper class is similar in construction:

    @@ -5529,8 +6220,23 @@ The type wrapper class is similar in construction: The "javaimports" typemap is ignored if the enum class is wrapped by an inner Java class, that is when wrapping an enum declared within a C++ class.

    +

    The Java interface turned on by the interface feature is fairly simple:

    +
    +
    +[ javaimports typemap ]
    +public interface [ javainterfacename ] {
    +[ javainterfacecode:cptrmethod typemap attribute ]
    +... interface declarations ...
    +}
    +
    +
    +

    -The defaults can be overridden to tailor these classes. +where javainterfacename is the name attribute in the interface feature. +

    + +

    +The defaults can be overridden to tailor the generated classes. Here is an example which will change the getCPtr method and constructor from the default public access to protected access. If the classes in one package are not using the classes in another package, then these methods need not be public and removing access to these low level implementation details, is a good thing. If you are invoking SWIG more than once and generating the wrapped classes into different packages in each invocation, then you cannot do this as you will then have different packages. @@ -5539,8 +6245,8 @@ If you are invoking SWIG more than once and generating the wrapped classes into

     %typemap(javabody) SWIGTYPE %{
    -  private long swigCPtr;
    -  protected boolean swigCMemOwn;
    +  private transient long swigCPtr;
    +  protected transient boolean swigCMemOwn;
     
       protected $javaclassname(long cPtr, boolean cMemoryOwn) {
         swigCMemOwn = cMemoryOwn;
    @@ -5568,7 +6274,7 @@ For the typemap to be used in all type wrapper classes, all the different types
     
     %typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
    -  private long swigCPtr;
    +  private transient long swigCPtr;
     
       protected $javaclassname(long cPtr, boolean bFutureUse) {
         swigCPtr = cPtr;
    @@ -5590,7 +6296,7 @@ Again this is the same that is in "java.swg", barring the method modifi
     

    -When using multiple modules or the nspace feature it is common to invoke SWIG with a different -package +When using multiple modules or the nspace feature it is common to invoke SWIG with a different -package command line option for each module. However, by default the generated code may not compile if generated classes in one package use generated classes in another package. @@ -5612,12 +6318,12 @@ to make the method and constructor public:

    -

    24.9.10 Director specific typemaps

    +

    25.9.10 Director specific typemaps

    The Java directors feature requires the "javadirectorin", "javadirectorout", "directorin" and the "directorout" typemaps in order to work properly. -The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes. +The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes used in director methods.

    %typemap(directorin)

    @@ -5656,6 +6362,10 @@ is the package name passed from the SWIG command line and $javaclassname-package
    commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor. Do not forget the terminating ';' for JNI field descriptors starting with 'L'. If the ';' is left out, Java will generate a "method not found" runtime error. +Note that the $packagepath substitution always uses the path separator '/' when expanded. +The $javaclassname expansion can be confusing as it is normally expanded using the '.' separator. +However, $javaclassname is expanded using the path separator '/' in typemap's "descriptor" attribute +as well as in the "directorthrows" typemap.

    @@ -5751,6 +6461,40 @@ The target method is the method in the Java proxy class which overrides the virt +

    %typemap(directorthrows)

    +
    + +

    +Conversion of Java exceptions to C++ exceptions in director method's exception handling. +This typemap is expected to test the $error special variable for a matching Java exception +and if successful convert and throw it into a C++ exception given by the typemap's type. +The $error special variable is of type jthrowable and is +substituted with a unique variable name in the generated code. +

    + +

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

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

    +The utility function Swig::ExceptionMatches +and class Swig::JavaExceptionMessage are helpers available when using directors and are described +in the Java Exceptions from Directors section. +

    + +
    +

    %typemap(javapackage)

    @@ -5758,6 +6502,7 @@ The target method is the method in the Java proxy class which overrides the virt

    The "javapackage" typemap is optional; it serves to identify a class's Java package. This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file. +The typemap is only used if the type is used in a director method, that is, in a virtual method in a director class. For example:

    @@ -5774,7 +6519,7 @@ For example: class Example { public: virtual ~Example(); - void ping(Foo *arg1, Bar *arg2); + virtual void ping(Foo *arg1, Bar *arg2); }; } @@ -5799,7 +6544,7 @@ The corrected interface file looks like: class Example { public: virtual ~Example(); - void ping(Foo *arg1, Bar *arg2); + virtual void ping(Foo *arg1, Bar *arg2); }; } @@ -5837,7 +6582,7 @@ The basic strategy here is to provide a default package typemap for the majority
    -

    24.10 Typemap Examples

    +

    25.10 Typemap Examples

    @@ -5847,7 +6592,7 @@ the SWIG library.

    -

    24.10.1 Simpler Java enums for enums without initializers

    +

    25.10.1 Simpler Java enums for enums without initializers

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

    -

    24.10.2 Handling C++ exception specifications as Java exceptions

    +

    25.10.2 Handling C++ exception specifications as Java exceptions

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

    -

    24.10.3 NaN Exception - exception handling for a particular type

    +

    25.10.3 NaN Exception - exception handling for a particular type

    @@ -6206,7 +6951,7 @@ If we were a martyr to the JNI cause, we could replace the succinct code within If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.

    -

    24.10.4 Converting Java String arrays to char **

    +

    25.10.4 Converting Java String arrays to char **

    @@ -6350,7 +7095,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.

    -

    24.10.5 Expanding a Java object to multiple arguments

    +

    25.10.5 Expanding a Java object to multiple arguments

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

    24.10.6 Using typemaps to return arguments

    +

    25.10.6 Using typemaps to return arguments

    @@ -6478,7 +7223,7 @@ int spam(double a, double b, double *out1, double *out2) { *out1 = a*10.0; *out2 = b*100.0; return status; -}; +} %} /* @@ -6550,7 +7295,7 @@ $ java runme 1 12.0 340.0 -

    24.10.7 Adding Java downcasts to polymorphic return types

    +

    25.10.7 Adding Java downcasts to polymorphic return types

    @@ -6756,7 +7501,7 @@ SWIG usually generates code which constructs the proxy classes using Java code a Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.

    -

    24.10.8 Adding an equals method to the Java classes

    +

    25.10.8 Adding an equals method to the Java classes

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

    24.10.9 Void pointers and a common Java base class

    +

    25.10.9 Void pointers and a common Java base class

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

  • It also has a function which effectively implements a cast from the type of the proxy/type wrapper class to a void pointer. This is necessary for passing a proxy class or a type wrapper class to a function that takes a void pointer. -

    24.10.10 Struct pointer to pointer

    +

    25.10.10 Struct pointer to pointer

    @@ -7039,7 +7784,7 @@ The C functional interface has been completely morphed into an object-oriented i the Butler class would behave much like any pure Java class and feel more natural to Java users.

    -

    24.10.11 Memory management when returning references to member variables

    +

    25.10.11 Memory management when returning references to member variables

    @@ -7162,7 +7907,7 @@ public class Bike { Note the addReference call.

    -

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

    +

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

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

    24.10.13 Date marshalling using the javain typemap and associated attributes

    +

    25.10.13 Date marshalling using the javain typemap and associated attributes

    @@ -7455,7 +8200,7 @@ A few things to note: -

    24.11 Living with Java Directors

    +

    25.11 Living with Java Directors

    @@ -7636,10 +8381,10 @@ public abstract class UserVisibleFoo extends Foo {

  • -

    24.12 Odds and ends

    +

    25.12 Odds and ends

    -

    24.12.1 JavaDoc comments

    +

    25.12.1 JavaDoc comments

    @@ -7695,7 +8440,7 @@ public class Barmy { -

    24.12.2 Functional interface without proxy classes

    +

    25.12.2 Functional interface without proxy classes

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

    24.12.3 Using your own JNI functions

    +

    25.12.3 Using your own JNI functions

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

    -

    24.12.4 Performance concerns and hints

    +

    25.12.4 Performance concerns and hints

    @@ -7827,7 +8572,7 @@ However, you will have to be careful about memory management and make sure that This method normally calls the C++ destructor or free() for C code.

    -

    24.12.5 Debugging

    +

    25.12.5 Debugging

    @@ -7840,7 +8585,7 @@ where it is possible to step from Java code into a JNI method within one environ

    Alternatively, debugging can involve placing debug printout statements in the JNI layer using the %exception directive. See the special variables for %exception section. -Many of the default typemaps can also be overidden and modified for adding in extra logging/debug display information. +Many of the default typemaps can also be overridden and modified for adding in extra logging/debug display information.

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

    -

    24.13 Java Examples

    +

    25.13 Java Examples

    @@ -7864,4 +8609,3 @@ Many of these have runtime tests in the java subdirectory. - diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html new file mode 100644 index 000000000..16f674892 --- /dev/null +++ b/Doc/Manual/Javascript.html @@ -0,0 +1,999 @@ + + + + + + + + + +

    26 SWIG and Javascript

    + + + + + + +

    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

    + + +

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

    +

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

    +

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

    +

    WebKit is a modern browser implementation available as open-source which can be embedded into an application. +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.1 Running SWIG

    + + +

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

    +
    +
    +%module example
    +%{
    +#include "example.h"
    +%}
    +int gcd(int x, int y);
    +extern double Foo;
    +
    +

    To build a Javascript module, run SWIG using the -javascript option and a desired target engine -jsc, -v8, or -node. The generator for node is essentially delegating to the v8 generator and adds some necessary preprocessor definitions.

    +
    +
    +$ swig -javascript -jsc example.i
    +
    +

    If building a C++ extension, add the -c++ option:

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

    +

    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

    +
    +
    +bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports)
    +
    +

    and for v8:

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

    + + +

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

    +

    The default interpreter is node.js as it is available on all platforms and convenient to use.

    +

    Running the examples with JavascriptCore requires libjavascriptcoregtk-1.0 to be installed, e.g., under Ubuntu with

    +
    +
    +$ sudo apt-get install libjavascriptcoregtk-1.0-dev
    +
    +

    Running with V8 requires libv8:

    +
    +
    +$ sudo apt-get install libv8-dev
    +
    +

    Examples can be run using

    +
    +
    +$ make check-javascript-examples ENGINE=jsc
    +
    +

    ENGINE can be node, jsc, or v8.

    +

    The test-suite can be run using

    +
    +
    +$ make check-javascript-test-suite ENGINE=jsc
    +
    +

    You can specify a specific V8 version for running the examples and tests

    +
    +
    +$ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8
    +
    + +

    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.

    + +
      +
    • Default optional arguments do not work for all targeted interpreters

    • +
    • Multiple output arguments do not work for JSC

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

    • +
    • long long is not supported

    • +
    • %native is not supported

    • +
    • Javascript callbacks are not supported

    • +
    • instanceOf does not work under JSC

    • +
    + +

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

    + +

    26.3 Integration

    + + +

    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

    + + +

    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
    +$ sudo apt-get update
    +$ sudo apt-get install nodejs
    +
    +

    As v8 is written in C++ and comes as a C++ library it is crucial to compile your module using the same compiler flags as used for building v8. To make things easier, node.js provides a build tool called node-gyp.

    +

    You have to install it using npm:

    +
    +
    +$ sudo npm install -g node-gyp
    +
    +

    node-gyp expects a configuration file named binding.gyp which is basically in JSON format and conforms to the same format that is used with Google's build-tool gyp.

    +

    binding.gyp:

    +
    +
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example.cxx", "example_wrap.cxx" ]
    +    }
    +  ]
    +}
    +
    +

    First create the wrapper using SWIG:

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

    Then run node-gyp build to actually create the module:

    +
    +
    +$ node-gyp build
    +
    +

    This will create a build folder containing the native module. To use the extension you need to 'require' it in your Javascript source file:

    +
    +
    +require("./build/Release/example")
    +
    +

    A more detailed explanation is given in the Examples section.

    + +

    26.3.1.1 Troubleshooting

    + + +
      +
    • 'module' object has no attribute 'script_main'
    • +
    +

    This error happens when gyp is installed as a distribution package. It seems to be outdated. Removing it resolves the problem.

    +
    +
    +$ sudo apt-get remove gyp
    +
    + +

    26.3.2 Embedded Webkit

    + + +

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

    + +

    26.3.2.1 Mac OS X

    + + +

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

    +

    An integration of a native extension 'example' would look like this:

    +
    +
    +#import "appDelegate.h"
    +
    +extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports);
    +
    +
    +@implementation ExampleAppDelegate
    +
    +@synthesize webView;
    +
    +- (void)addGlobalObject:(JSContextRef) context:(NSString *)objectName:(JSObjectRef) theObject {
    +  JSObjectRef global = JSContextGetGlobalObject(context);
    +  JSStringRef objectJSName = JSStringCreateWithCFString( (CFStringRef) objectName )
    +  if ( objectJSName != NULL ) {
    +    JSObjectSetProperty(context, global, objectJSName, theObject, kJSPropertyAttributeReadOnly, NULL);
    +    JSStringRelease( objectJSName );
    +  }
    +}
    +
    +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    +
    +  // Start a webview with the bundled index.html file
    +  NSString *path = [[NSBundle mainBundle] bundlePath];
    +  NSString *url =  [NSString stringWithFormat: @"file://%@/Contents/Assets/index.html", path];
    +
    +  WebFrame *webframe = [webView mainFrame];
    +  JSGlobalContextRef context = [webframe globalContext];
    +
    +  JSObjectRef example;
    +  example_initialize(context, &example);
    +  [self addGlobalObject:context:@"example":example]
    +
    +  JSObjectSetProperty(context, global, JSStringRef propertyName, example, JSPropertyAttributes attributes, NULL);
    +
    +  [ [webView mainFrame] loadRequest:
    +    [NSURLRequest requestWithURL: [NSURL URLWithString:url] ]
    +  ];
    +}
    +
    +@end
    +
    + +

    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.

    +

    An integration of a native extension 'example' would look like this:

    +
    +
    +#include <gtk/gtk.h>
    +#include <webkit/webkit.h>
    +
    +extern bool example_initialize(JSGlobalContextRef context);
    +
    +int main(int argc, char* 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);
    +
    +    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/");
    +
    +    ...
    +
    +    // Run the main GTK+ event loop
    +    gtk_main();
    +
    +    return 0;
    +}
    +
    + +

    26.3.3 Creating Applications with node-webkit

    + + +

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

    +

    Similar to node.js, node-webkit is started from command line within a node.js project directory. +Native extensions are created in the very same way as for node.js, except that a customized gyp derivate has to be used: nw-gyp. +

    + +

    +A simple example would have the following structure: +

    + +
    +
    +- package.json
    +- app.html
    +- app.js
    +- node_modules
    +  / example
    +  ... (as known from node.js)
    +
    +
    + +

    +The configuration file essentially conforms to node.js syntax. +It has some extras to configure node-webkit. See the Manifest specification for more details. +

    + +

    +package.json: +

    +
    +
    +{
    +  "name": "example",
    +  "main": "app.html",
    +  "window": {
    +    "show": true,
    +    "width": 800,
    +    "height": 600
    +  }
    +}
    +
    + +

    +The 'main' property of package.json specifies a web-page to be rendered in +the main window.

    + +

    +app.html: +

    + +
    +
    +<html>
    +  <head>
    +    <script src="app.js"></script>
    +  </head>
    +  <body>
    +    <div>
    +      The greatest common divisor of
    +      <span id="x"></span> and
    +      <span id="y"></span> is
    +      <span id="z"></span>.
    +    </div>
    +  </body>
    +</html>
    +
    + +

    +As known from node.js one can use require to load javascript modules. +Additionally, node-webkit provides an API that allows to manipulate the window's menu, +open new windows, and many more things. +

    + +

    +app.js: +

    + +
    +
    window.onload = function() {
    +  var example = require("example");
    +  var x = 18;
    +  var y = 24;
    +  var z = example.gcd(x,y);
    +  document.querySelector('#x').innerHTML = x;
    +  document.querySelector('#y').innerHTML = y;
    +  document.querySelector('#z').innerHTML = z;
    +};
    +
    + +

    26.4 Examples

    + + +

    Some basic examples are shown here in more detail.

    + +

    26.4.1 Simple

    + + +

    The common example simple looks like this:

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

    To make this available as a node extension a binding.gyp has to be created:

    +
    +
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example.cxx", "example_wrap.cxx" ]
    +    }
    +  ]
    +}
    +
    +

    Then node-gyp is used to build the extension:

    +
    +
    +$ node-gyp configure build
    +
    +

    From a 'nodejs` application the extension would be used like this:

    +
    +
    +// import the extension via require
    +var example = require("./build/Release/example");
    +
    +// calling the global method
    +var x = 42;
    +var y = 105;
    +var g = example.gcd(x,y);
    +
    +// Accessing the global variable
    +var f = example.Foo;
    +example.Foo = 3.1415926;
    +
    +

    First the module example is loaded from the previously built extension. Global methods and variables are available in the scope of the module.

    + +

    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

    + + +

    The common example class defines three classes, Shape, Circle, and Square:

    +
    +
    +class Shape {
    +public:
    +  Shape() {
    +    nshapes++;
    +  }
    +  virtual ~Shape() {
    +    nshapes--;
    +  }
    +  double  x, y;
    +  void    move(double dx, double dy);
    +  virtual double area(void) = 0;
    +  virtual double perimeter(void) = 0;
    +  static  int nshapes;
    +};
    +
    +class Circle : public Shape {
    +private:
    +  double radius;
    +public:
    +  Circle(double r) : radius(r) { }
    +  virtual double area(void);
    +  virtual double perimeter(void);
    +};
    +
    +class Square : public Shape {
    +private:
    +  double width;
    +public:
    +  Square(double w) : width(w) { }
    +  virtual double area(void);
    +  virtual double perimeter(void);
    +};
    +
    +

    Circle and Square inherit from Shape. Shape has a static variable nshapes, a function move that can't be overridden (non-virtual), and two abstract functions area and perimeter (pure virtual) that must be overridden by the sub-classes.

    +

    A nodejs extension is built the same way as for the simple example.

    +

    In Javascript it can be used as follows:

    +
    +
    +var example = require("./build/Release/example");
    +
    +// local aliases for convenience
    +var Shape = example.Shape;
    +var Circle = example.Circle;
    +var Square = example.Square;
    +
    +// creating new instances using the 'new' operator
    +var c = new Circle(10);
    +var s = new Square(10);
    +
    +// accessing a static member
    +Shape.nshapes;
    +
    +// accessing member variables
    +c.x = 20;
    +c.y = 30;
    +s.x = -10;
    +s.y = 5;
    +
    +// calling some methods
    +c.area();
    +c.perimeter();
    +s.area();
    +s.perimeter();
    +
    +// instantiation of Shape is not permitted
    +new Shape();
    +
    +

    Running these commands in an interactive node shell results in the following output:

    +
    +
    +$ node -i
    +& var example = require("./build/Release/example");
    +undefined
    +& var Shape = example.Shape;
    +undefined
    +& var Circle = example.Circle;
    +undefined
    +& var Square = example.Square;
    +undefined
    +& var c = new Circle(10);
    +undefined
    +& var s = new Square(10);
    +undefined
    +& Shape.nshapes;
    +2
    +& c.x = 20;
    +20
    +& c.y = 30;
    +30
    +& s.x = -10;
    +-10
    +& s.y = 5;
    +5
    +& c.area();
    +314.1592653589793
    +& c.perimeter();
    +62.83185307179586
    +& s.area();
    +100
    +& s.perimeter();
    +40
    +& c.move(40, 40)
    +undefined
    +& c.x
    +60
    +& c.y
    +70
    +& new Shape()
    +Error: Class Shape can not be instantiated
    +at repl:1:2
    +at REPLServer.self.eval (repl.js:110:21)
    +at Interface.<anonymous> (repl.js:239:12)
    +at Interface.EventEmitter.emit (events.js:95:17)
    +at Interface._onLine (readline.js:202:10)
    +at Interface._line (readline.js:531:8)
    +at Interface._ttyWrite (readline.js:760:14)
    +at ReadStream.onkeypress (readline.js:99:10)
    +at ReadStream.EventEmitter.emit (events.js:98:17)
    +at emitKey (readline.js:1095:12)
    +
    +

    +Note: In ECMAScript 5 there is no concept for classes. Instead each function can be used as a constructor function which is executed by the 'new' operator. Furthermore, during construction the key property prototype of the constructor function is used to attach a prototype instance to the created object. A prototype is essentially an object itself that is the first-class delegate of a class used whenever the access to a property of an object fails. The very same prototype instance is shared among all instances of one type. Prototypal inheritance is explained in more detail on in Inheritance and the prototype chain, for instance. +

    + +

    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

    + + +

    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:

    +
    +
    +// module wide defines
    +
    +#define NAME "name"
    +...
    +
    +// ###############################
    +// #  Helper class declarations
    +
    +class JSEmitterState { ... };
    +
    +class Template { ... };
    +
    +// ###############################
    +// # JSEmitter declaration
    +
    +class JSEmitter { ... };
    +
    +// Emitter factory declarations
    +
    +JSEmitter *swig_javascript_create_JSCEmitter();
    +JSEmitter *swig_javascript_create_V8Emitter();
    +
    +// ###############################
    +// # Javascript module
    +
    +// Javascript module declaration
    +
    +class JAVASCRIPT:public Language { ... };
    +
    +// Javascript module implementation
    +
    +int JAVASCRIPT::functionWrapper(Node *n) { ... }
    +...
    +
    +// Module factory implementation
    +
    +static Language *new_swig_javascript() { ... }
    +
    +extern "C" Language *swig_javascript(void) { ... }
    +
    +// ###############################
    +// # JSEmitter base implementation
    +
    +JSEmitter::JSEmitter() { ... }
    +
    +Template JSEmitter::getTemplate(const String *name) { ... }
    +...
    +
    +// ###############################
    +// # JSCEmitter
    +
    +// JSCEmitter declaration
    +
    +class JSCEmitter: public JSEmitter { ... };
    +
    +// JSCEmitter implementation
    +
    +JSCEmitter::JSCEmitter() { ... }
    +
    +void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... }
    +...
    +
    +// JSCEmitter factory
    +
    +JSEmitter *swig_javascript_create_JSCEmitter() { ... }
    +
    +
    +// ###############################
    +// # V8Emitter
    +
    +// V8Emitter declaration
    +
    +class V8Emitter: public JSEmitter { ... };
    +
    +// V8Emitter implementation
    +
    +V8Emitter::V8Emitter() { ... }
    +
    +int V8Emitter::initialize(Node *n) { ... }
    +
    +// V8Emitter factory
    +
    +JSEmitter *swig_javascript_create_V8Emitter() { ... }
    +
    +
    +// ###############################
    +// # Helper implementation (JSEmitterState, Template)
    +
    +JSEmitterState::JSEmitterState() { ... }
    +...
    +
    +Template::Template(const String *code_) { ... }
    +...
    +
    + +

    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.

    +

    To track the originating code template for generated code you can run

    +
    +
    +$ swig -javascript -jsc -debug-codetemplates
    +
    +

    which wraps generated code with a descriptive comment

    +
    +
    +/* begin fragment("template_name") */
    +
    +...generated code ...
    +
    +/* end fragment("template_name") */
    +
    +

    The Template class is used like this:

    +
    +
    +Template t_register = getTemplate("jsv8_register_static_variable");
    +t_register.replace("$jsparent", state.clazz(NAME_MANGLED))
    +    .replace("$jsname", state.variable(NAME))
    +    .replace("$jsgetter", state.variable(GETTER))
    +    .replace("$jssetter", state.variable(SETTER))
    +    .trim().
    +    print(f_init_static_wrappers);
    +
    +

    A code template is registered with the JSEmitter via fragment(name, "template"), e.g.,

    +
    +
    +%fragment ("jsc_variable_declaration", "templates")
    +%{
    +  {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone},
    +%}
    +
    +

    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

    + + +

    The Javascript module delegates code generation to a JSEmitter instance. The following extract shows the essential interface:

    +
    +
    +class JSEmitter {
    +  ...
    +
    +  /**
    +   * Opens output files and temporary output DOHs.
    +   */
    +  virtual int initialize(Node *n);
    +
    +  /**
    +   * Writes all collected code into the output file(s).
    +   */
    +  virtual int dump(Node *n) = 0;
    +
    +  /**
    +   * Cleans up all open output DOHs.
    +   */
    +  virtual int close() = 0;
    +
    +  ...
    +
    +  /**
    +   * Invoked at the beginning of the classHandler.
    +   */
    +  virtual int enterClass(Node *);
    +
    +  /**
    +   * Invoked at the end of the classHandler.
    +   */
    +  virtual int exitClass(Node *) {
    +    return SWIG_OK;
    +  }
    +
    +  /**
    +   * Invoked at the beginning of the variableHandler.
    +   */
    +  virtual int enterVariable(Node *);
    +
    +  /**
    +   * Invoked at the end of the variableHandler.
    +   */
    +  virtual int exitVariable(Node *) {
    +    return SWIG_OK;
    +  }
    +
    +  /**
    +   * Invoked at the beginning of the functionHandler.
    +   */
    +  virtual int enterFunction(Node *);
    +
    +  /**
    +   * Invoked at the end of the functionHandler.
    +   */
    +  virtual int exitFunction(Node *) {
    +    return SWIG_OK;
    +  }
    +
    +  /**
    +   * Invoked by functionWrapper callback after call to Language::functionWrapper.
    +   */
    +  virtual int emitWrapperFunction(Node *n);
    +
    +  /**
    +   * Invoked from constantWrapper after call to Language::constantWrapper.
    +   **/
    +  virtual int emitConstant(Node *n);
    +
    +  /**
    +   * Registers a given code snippet for a given key name.
    +   *
    +   * This method is called by the fragmentDirective handler
    +   * of the JAVASCRIPT language module.
    +   **/
    +  int registerTemplate(const String *name, const String *code);
    +
    +  /**
    +   * Retrieve the code template registered for a given name.
    +   */
    +  Template getTemplate(const String *name);
    +
    +  State &getState();
    +
    +  ...
    +
    +}
    +
    +

    The module calls initialize, dump, and close from within the top method:

    +
    +
    +int JAVASCRIPT::top(Node *n) {
    +  emitter->initialize(n);
    +
    +  Language::top(n);
    +
    +  emitter->dump(n);
    +  emitter->close();
    +
    +  return SWIG_OK;
    +}
    +
    +

    The methods enterClass and exitClass are called from within the classHandler method:

    +
    +
    +int JAVASCRIPT::classHandler(Node *n) {
    +
    +  emitter->enterClass(n);
    +  Language::classHandler(n);
    +  emitter->exitClass(n);
    +
    +  return SWIG_OK;
    +}
    +
    +

    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

    + + +

    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.

    +
    +
    +class JSEmitterState {
    +
    +public:
    +
    +  JSEmitterState();
    +
    +  ~JSEmitterState();
    +
    +  DOH *global();
    +
    +  DOH *global(const char* key, DOH *initial = 0);
    +
    +  DOH *clazz(bool reset = false);
    +
    +  DOH *clazz(const char* key, DOH *initial = 0);
    +
    +  DOH *function(bool reset = false);
    +
    +  DOH *function(const char* key, DOH *initial = 0);
    +
    +  DOH *variable(bool reset = false);
    +
    +  DOH *variable(const char* key, DOH *initial = 0);
    +
    +  static int IsSet(DOH *val);
    +
    +  ...
    +};
    +
    +

    When entering a scope, such as in enterClass, the corresponding state is reset and new data is stored:

    +
    +
    +state.clazz(RESET);
    +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

    + + +

    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.

    +
    +
    +void script_exception_to_string(JSContextRef js_context,JSValueRef exception_value_ref,char* return_error_string, int return_error_string_max_length)
    +{
    +  JSObjectRef exception_object;
    +  JSValueRef value_ref;
    +  JSStringRef jsstring_property_name = NULL;
    +  JSValueRef temporary_exception = NULL;
    +  JSStringRef js_return_string = NULL;
    +  size_t bytes_needed;
    +  char* c_result_string = NULL;
    +  exception_object = JSValueToObject(js_context, exception_value_ref, NULL);
    +
    +  /* source url */
    +  strcpy(return_error_string,"[");
    +  jsstring_property_name = JSStringCreateWithUTF8CString("sourceURL");
    +  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception);
    +  JSStringRelease(jsstring_property_name);
    +  js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    +  bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    +  c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    +  JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    +  JSStringRelease(js_return_string);
    +  strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    +  free(c_result_string);
    +
    +  strncat(return_error_string, ":", return_error_string_max_length-1);
    +
    +  /* line number */
    +
    +  jsstring_property_name = JSStringCreateWithUTF8CString("line");
    +  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception);
    +  JSStringRelease(jsstring_property_name);
    +  js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    +  bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    +  c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    +  JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    +  JSStringRelease(js_return_string);
    +  strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    +  free(c_result_string);
    +
    +  strncat(return_error_string, "]", return_error_string_max_length-1);
    +
    +  /* error message */
    +
    +  jsstring_property_name = JSStringCreateWithUTF8CString("message");
    +  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception);
    +  JSStringRelease(jsstring_property_name);
    +  if(NULL == value_ref)
    +  {
    +    strncat(return_error_string, "Unknown Error", return_error_string_max_length-1);
    +  }
    +  else
    +  {
    +    js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    +    bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    +    c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    +    JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    +    JSStringRelease(js_return_string);
    +    strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    +    free(c_result_string);
    +  }
    +}
    +
    + +

    It would be used in the following way:

    +
    +
    +if(js_exception)
    +{
    +  char return_error_string[256];
    +  script_exception_to_string(js_context, js_exception, return_error_string, 256);
    +  printf("Compile error is %s", return_error_string);
    +}
    +
    + + + diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index dcec21c90..954de54f7 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -1,12 +1,13 @@ - + SWIG Library + -

    8 SWIG library

    +

    9 SWIG library

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

      -

      8.1 The %include directive and library search path

      +

      9.1 The %include directive and library search path

      @@ -66,18 +68,19 @@ Library files are included using the %include directive. When searching for files, directories are searched in the following order:

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

      -Within each directory, SWIG first looks for a subdirectory corresponding to a target language (e.g., python, -tcl, etc.). If found, SWIG will search the language specific directory first. This allows -for language-specific implementations of library files. +Within directories mentioned in points 3-5, SWIG first looks for a subdirectory +corresponding to a target language (e.g., python, tcl, etc.). +If found, SWIG will search the language specific directory first. This allows +for language-specific implementations of library files.

      @@ -89,7 +92,7 @@ Set the environment variable to hold an alternative library directory. The directories that are searched are displayed when using -verbose commandline option.

      -

      8.2 C Arrays and Pointers

      +

      9.2 C Arrays and Pointers

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

      -

      8.2.1 cpointer.i

      +

      9.2.1 cpointer.i

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

      -

      8.2.2 carrays.i

      +

      9.2.2 carrays.i

      @@ -495,7 +498,7 @@ you should consider using a special array object rather than a bare pointer. used with types of char or char *.

      -

      8.2.3 cmalloc.i

      +

      9.2.3 cmalloc.i

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

  • -

    8.2.4 cdata.i

    +

    9.2.4 cdata.i

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

    -

    8.3 C String Handling

    +

    9.3 C String Handling

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

    -

    8.3.1 Default string handling

    +

    9.3.1 Default string handling

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

    -

    8.3.2 Passing binary data

    +

    9.3.2 Passing binary data

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

    -

    8.3.3 Using %newobject to release memory

    +

    9.3.3 Using %newobject to release memory

    @@ -902,7 +905,7 @@ however, you may need to provide your own "newfree" typemap for other types. See Object ownership and %newobject for more details.

    -

    8.3.4 cstring.i

    +

    9.3.4 cstring.i

    @@ -1362,7 +1365,7 @@ structure or class instead. -

    8.4 STL/C++ Library

    +

    9.4 STL/C++ Library

    @@ -1382,6 +1385,7 @@ The following table shows which C++ classes are supported and the equivalent SWI SWIG Interface library file + std::auto_ptr memory std_auto_ptr.i std::deque deque std_deque.i std::list list std_list.i std::map map std_map.i @@ -1389,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 @@ -1399,7 +1404,7 @@ Please look for the library files in the appropriate language library directory.

    -

    8.4.1 std::string

    +

    9.4.1 std::string

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

    8.4.2 std::vector

    +

    9.4.2 std::vector

    @@ -1662,7 +1667,7 @@ if you want to make their head explode. details and the public API exposed to the interpreter vary.

    -

    8.4.3 STL exceptions

    +

    9.4.3 STL exceptions

    @@ -1712,13 +1717,28 @@ The %exception directive can be used by placing the following code befo Any thrown STL exceptions will then be gracefully handled instead of causing a crash.

    -

    8.4.4 shared_ptr smart pointer

    +

    9.4.4 shared_ptr smart pointer

    -Some target languages have support for handling the widely used boost::shared_ptr smart pointer. -This smart pointer is also available as std::tr1::shared_ptr before it becomes fully standardized as std::shared_ptr. -The boost_shared_ptr.i library provides support for boost::shared_ptr and std_shared_ptr.i provides support for std::shared_ptr, but if the following macro is defined as shown, it can be used for std::tr1::shared_ptr: +Some target languages have support for handling the shared_ptr reference counted smart pointer. +This smart pointer is available in the standard C++11 library as std::shared_ptr. +It was also in TR1 as std::tr1::shared_ptr before it was fully standardized. +Support for the widely used boost::shared_ptr is also available. +

    + +

    +In order to use std::shared_ptr, the std_shared_ptr.i library file should be included: +

    + +
    +
    +%include <std_shared_ptr.i>
    +
    +
    + +

    +The pre-standard std::tr1::shared_ptr can be used by including the following macro before including the std_shared_ptr.i library file:

    @@ -1728,6 +1748,16 @@ The boost_shared_ptr.i library provides support for boost::shared_p
    +

    +In order to use boost::shared_ptr, the boost_shared_ptr.i library file should be included: +

    + +
    +
    +%include <boost_shared_ptr.i>
    +
    +
    +

    You can only use one of these variants of shared_ptr in your interface file at a time. and all three variants must be used in conjunction with the %shared_ptr(T) macro, @@ -1871,10 +1901,66 @@ Adding the missing %shared_ptr macros will fix this: -

    8.5 Utility Libraries

    +

    +Note: There is somewhat limited support for %shared_ptr and the director feature +and the degress of success varies among the different target languages. +Please help to improve this support by providing patches with improvements. +

    -

    8.5.1 exception.i

    +

    9.4.5 auto_ptr smart pointer

    + + +

    +While std::auto_ptr is deprecated in C++11, some existing code may +still be using it, so SWIG provides limited support for this class: +std_auto_ptr.i defines the typemaps which apply to the functions +returning objects of this type. Any other use of std_auto_ptr.i is not +directly supported. +

    + +

    +A typical example of use would be +

    +
    +
    +%include <std_auto_ptr.i>
    +
    +%auto_ptr(Klass)
    +%inline %{
    +class Klass {
    +public:
    +  // Factory function creating objects of this class:
    +  static std::auto_ptr<Klass> Create(int value) {
    +    return std::auto_ptr<Klass>(new Klass(value));
    +  }
    +
    +  int getValue() const { return m_value; }
    +
    +private:
    +  DerivedIntValue(int value) : m_value(value) {}
    +  int m_value;
    +};
    +%}
    +
    +
    + +

    +The returned objects can be used naturally from the target language, e.g. from +C#: +

    + +
    +
    +Klass k = Klass.Create(17);
    +int value = k.getValue();
    +
    +
    + +

    9.5 Utility Libraries

    + + +

    9.5.1 exception.i

    diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index 01ff3a3ec..0867ba926 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -1,12 +1,13 @@ - + SWIG and Common Lisp + -

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

      -

      25.1 Allegro Common Lisp

      +

      27.1 Allegro Common Lisp

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

      -

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

      -

      25.2.1 Additional Commandline Options

      +

      27.2.1 Additional Commandline Options

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

      25.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 - files. To illustrate the use of it, lets assume that we have a + files. To illustrate the use of it, let's assume that we have a file named test.h with the following C code:
      @@ -219,19 +220,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 +248,9 @@ The generated SWIG Code will be:
         (array :pointer))
       
       (cffi:defcenum color
      -	:RED
      -	:BLUE
      -	:GREEN)
      +        :RED
      +        :BLUE
      +        :GREEN)
       

      @@ -284,9 +285,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 +313,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 +336,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 +363,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 +385,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))

    -

    25.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 @@ -568,7 +572,7 @@ If you have any questions, suggestions, patches, etc., related to CFFI module feel free to contact us on the SWIG mailing list, and also please add a "[CFFI]" tag in the subject line. -

    25.2.4 Inserting user code into generated files

    +

    27.2.4 Inserting user code into generated files

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

    -

    25.3 CLISP

    +

    27.3 CLISP

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

    -

    25.3.1 Additional Commandline Options

    +

    27.3.1 Additional Commandline Options

    @@ -658,33 +662,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. -

    25.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 +738,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 +757,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+))
     
    @@ -795,7 +799,7 @@ struct bar {
     
     
    -

    25.4 UFFI

    +

    27.4 UFFI

    diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index ec32c4449..004ca6f2b 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -1,12 +1,13 @@ - + SWIG and Lua + -

    26 SWIG and Lua

    +

    28 SWIG and Lua

  • Typemaps -
  • Writing typemaps +
  • Writing typemaps
  • Customization of your Bindings @@ -73,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

    -

    26.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 supports eLua and works with eLua 0.8. SWIG generated code for eLua has been tested on Stellaris ARM Cortex-M3 LM3S and Infineon TriCore. +The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also has support for eLua starting from eLua 0.8. Due to substantial changes between SWIG 2.x and SWIG 3.0 and unavailability of testing platform, eLua status was downgraded to 'experimental'.

    -

    26.2 Running SWIG

    +

    28.2 Running SWIG

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

    -

    26.2.1 Additional command line options

    +

    28.2.1 Additional command line options

    @@ -159,9 +169,17 @@ swig -lua -help Do not register the module name as a global variable but return the module table from calls to require. + + -no-old-metatable-bindings + Disable backward compatibility: old-style binding names generations and a few other things. Explanations are included in appropriate later sections. + + + -squash-bases + Squashes symbols from all inheritance tree of a given class into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly speeds things up, but increases memory consumption. + -

    26.2.2 Compiling and Linking and Interpreter

    +

    28.2.2 Compiling and Linking and Interpreter

    @@ -184,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 @@ -232,16 +250,16 @@ LUALIB_API int ( luaopen_mod )(lua_State *L ); More information on building and configuring eLua can be found here: http://www.eluaproject.net/doc/v0.8/en_building.html

    -

    26.2.3 Compiling a dynamic module

    +

    28.2.3 Compiling a dynamic module

    -Most, but not all platforms support the dynamic loading of modules (Windows & Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the same wrapper can be used. The commands will be something like this: +Most, but not all platforms support the dynamic loading of modules (Windows & Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the same wrapper can be used. Assuming you have code you need to link to in a file called example.c, the commands will be something like this:

     $ swig -lua example.i -o example_wrap.c
    -$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
    -$ gcc -c example.c -o example.o
    +$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o
    +$ gcc -fPIC -c example.c -o example.o
     $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
     

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

    26.2.4 Using your module

    +

    28.2.4 Using your module

    @@ -318,19 +336,19 @@ $ ./my_lua >

  • -

    26.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.

    -

    26.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.

    -

    26.3.2 Functions

    +

    28.3.2 Functions

    @@ -349,7 +367,10 @@ creates a built-in function example.fact(n) that works exactly like you >

    -To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care. +To avoid name collisions, SWIG create a Lua table which keeps all the functions, constants, classes and global variables in. +It is possible to copy the functions, constants and classes (but not variables) out of this and into the global environment with the following code. +This can easily overwrite existing functions, so this must be used with care. +This option is considered deprecated and will be removed in the near future.

     > for k,v in pairs(example) do _G[k]=v end
    @@ -368,7 +389,7 @@ It is also possible to rename the module with an assignment.
     24
     
    -

    26.3.3 Global variables

    +

    28.3.3 Global variables

    @@ -456,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.

    -

    26.3.4 Constants and enums

    +

    28.3.4 Constants and enums

    @@ -490,7 +511,64 @@ If you're using eLua and have used -elua or -eluac to generate > print(example.const.SCONST) Hello World -

    26.3.5 Pointers

    + +

    28.3.4.1 Constants/enums and classes/structures

    + + +

    +Enums are exported into a class table. For example, given some enums: +

    +
    %module example
    +enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
    +struct Test {
    +    enum { TEST1 = 10, TEST2 = 20 };
    +#ifdef __cplusplus // There are no static members in C
    +    static const int ICONST = 12;
    +#endif
    +};
    +
    +

    +There is a slight difference in behaviour wrapping C and C++ code due to the different scoping rules of C and C++. +The wrapped C++ code is used as follows from Lua code: +

    +
    +> print(example.SUNDAY)
    +0
    +> print(example.Test.TEST1)
    +10
    +> print(example.Test.ICONST)
    +12
    +
    + +

    Enums within a C struct are in the global namespace and are used as follows from Lua

    +
    +> print(example.SUNDAY)
    +0
    +> -- See the difference here
    +> print(example.TEST1)
    +10
    +
    + +

    +Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above. +There is no change in the C wrappers, but +the following code was the only way to access these constants/enums when wrapping C++ member constants: +

    +
    +> print(example.Test_TEST1)
    +10
    +> print(example.Test_ICONST)
    +12
    +
    +

    +The old-style bindings are still generated in addition to the new ones. +If the -no-old-metatable-bindings option is used, then these old-style bindings are not generated. +

    +

    +It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. +Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues. +

    +

    28.3.5 Pointers

    @@ -528,7 +606,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -

    26.3.6 Structures

    +

    28.3.6 Structures

    @@ -551,7 +629,7 @@ is used as follows:

    Similar access is provided for unions and the data members of C++ classes.
    -C structures are created using a function new_Point(), but for C++ classes are created using just the name Point(). +C structures can be created using a function new_Point(), and both C structures and C++ classes can be created using just the name Point().

    If you print out the value of p in the above example, you will see something like this: @@ -632,7 +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)

    -

    26.3.7 C++ classes

    +

    28.3.7 C++ classes

    @@ -676,12 +754,12 @@ public: };

    -In Lua, the static members can be accessed as follows: +In Lua, C++ static members can be accessed as follows:

    -> example.Spam_foo()            -- calling Spam::foo()
    -> a=example.Spam_bar            -- reading Spam::bar 
    -> example.Spam_bar=b            -- writing to Spam::bar
    +> example.Spam.foo()            -- calling Spam::foo()
    +> a=example.Spam.bar            -- reading Spam::bar 
    +> example.Spam.bar=b            -- writing to Spam::bar
     

    It is not (currently) possible to access static members of an instance: @@ -692,7 +770,22 @@ It is not (currently) possible to access static members of an instance: -- does NOT work -

    26.3.8 C++ inheritance

    +

    +Compatibility Note: In versions prior to SWIG-3.0.0 only the following names would work: +

    + +
    +> example.Spam_foo()            -- calling Spam::foo()
    +> a=example.Spam_bar            -- reading Spam::bar 
    +> example.Spam_bar=b            -- writing to Spam::bar
    +
    + +

    +Both style names are generated by default now. +However, if the -no-old-metatable-bindings option is used, then the backward compatible names are not generated in addition to ordinary ones. +

    + +

    28.3.8 C++ inheritance

    @@ -717,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.

    -

    26.3.9 Pointers, references, values, and arrays

    +

    28.3.9 Pointers, references, values, and arrays

    @@ -748,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.

    -

    26.3.10 C++ overloaded functions

    +

    28.3.10 C++ overloaded functions

    @@ -799,7 +892,7 @@ void spam(short);

    or

    -
    VOID FOO(bAR *B);
    +
    void foo(Bar *b);
     void foo(Bar &b);
     

    @@ -834,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.

    -

    26.3.11 C++ operators

    +

    28.3.11 C++ operators

    @@ -898,10 +991,10 @@ The current list of operators which can be overloaded (and the alternative funct

  • __sub__ operator-
  • __mul__ operator *
  • __div__ operator/ -
  • __neg__ unary minus +
  • __unm__ unary minus
  • __call__ operator() (often used in functor classes)
  • __pow__ the exponential fn (no C++ equivalent, Lua uses ^) -
  • __concat__ the concatenation operator (SWIG maps C++'s ~ to Lua's ..) +
  • __concat__ the concatenation operator (Lua's ..)
  • __eq__ operator==
  • __lt__ operator<
  • __le__ operator<= @@ -945,8 +1038,30 @@ It is also possible to overload the operator[], but currently this cann void __setitem__(int i,double d); // i is the index, d is the data };
  • - -

    26.3.12 Class extension with %extend

    +

    +C++ operators are mapped to Lua predefined metafunctions. Class inherits from its bases the following list of metafunctions ( thus inheriting the folloging +operators and pseudo-operators):

    +
      +
    • __add__ +
    • __sub__ +
    • __mul__ +
    • __div__ +
    • __unm__ +
    • __mod__ +
    • __call__ +
    • __pow__ +
    • __concat__ +
    • __eq__ +
    • __lt__ +
    • __le__ +
    • __len__ +
    • __getitem__ +
    • __setitem__ +
    • __tostring used internally by Lua for tostring() function. __str__ is mapped to this function +
    +

    No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. __tostring is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG. +

    +

    28.3.12 Class extension with %extend

    @@ -981,7 +1096,7 @@ Now we extend it with some new code return tmp; } bool operator==(const Complex& c) - { return ($self->re()==c.re() && $self->im()==c.im();} + { return ($self->re()==c.re() && $self->im()==c.im());} };

    @@ -1002,7 +1117,7 @@ true Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the '$self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).

    -

    26.3.13 Using %newobject to release memory

    +

    28.3.13 Using %newobject to release memory

    If you have a function that allocates memory like this,

    @@ -1026,7 +1141,7 @@ char *foo();

    This will release the allocated memory.

    -

    26.3.14 C++ templates

    +

    28.3.14 C++ templates

    @@ -1061,7 +1176,7 @@ In Lua:

    Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.

    -

    26.3.15 C++ Smart Pointers

    +

    28.3.15 C++ Smart Pointers

    @@ -1113,7 +1228,7 @@ If you ever need to access the underlying pointer returned by operator->( > f = p:__deref__() -- Returns underlying Foo * -

    26.3.16 C++ Exceptions

    +

    28.3.16 C++ Exceptions

    @@ -1256,13 +1371,164 @@ and the "Exception handling add exception specification to functions or globally (respectively).

    +

    28.3.17 Namespaces

    -

    26.4 Typemaps

    + +

    +Since SWIG-3.0.0 C++ namespaces are supported via the %nspace feature. +

    +

    Namespaces are mapped into Lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code: +

    +
    %module example
    +%nspace MyWorld::Nested::Dweller;
    +%nspace MyWorld::World;
    +
    +int module_function() { return 7; }
    +int module_variable = 9;
    +
    +namespace MyWorld {
    +  class World {
    +  public:
    +    World() : world_max_count(9) {}
    +    int create_world() { return 17; }
    +    const int world_max_count; // = 9
    +  };
    +  namespace Nested {
    +    class Dweller {
    +      public:
    +        enum Gender { MALE = 0, FEMALE = 1 };
    +        static int count() { return 19; }
    +    };
    +  }
    +}
    +
    + +

    +Now, from Lua usage is as follows: +

    + +
    +> print(example.module_function())
    +7
    +> print(example.module_variable)
    +9
    +> print(example.MyWorld.World():create_world())
    +17
    +> print(example.MyWorld.World.world_max_count)
    +9
    +> print(example.MyWorld.Nested.Dweller.MALE)
    +0
    +> print(example.MyWorld.Nested.Dweller.count())
    +19
    +>
    +
    +

    28.3.17.1 Compatibility Note

    + + +

    +If SWIG is running in a backwards compatible way, i.e. without the -no-old-metatable-bindings option, then additional old-style names are generated (notice the underscore): +

    +
    +9
    +> print(example.MyWorld.Nested.Dweller_MALE)
    +0
    +> print(example.MyWorld.Nested.Dweller_count())
    +11
    +>
    +
    + + +

    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 +to generate additional names for static functions, class static constants and class enums. +Those names are in a form $classname_$symbolname and are added to the scope surrounding the class. +If %nspace is enabled, then class namespace is taken as scope. If there is no namespace, or %nspace is disabled, +then module is considered a class namespace.

    +

    Consider the following C++ code

    +
    %module example
    +%nspace MyWorld::Test;
    +namespace MyWorld {
    +class Test {
    +  public:
    +  enum { TEST1 = 10, TEST2 }
    +  static const int ICONST = 12;
    +};
    +class Test2 {
    +  public:
    +  enum { TEST3 = 20, TEST4 }
    +  static const int ICONST2 = 23;
    +}
    +
    +

    When in backward compatible mode, in addition to the usual names, the following ones will be generated (notice the underscore):

    +
    +9
    +> print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled
    +10
    +> print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled
    +12
    +> print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled
    +20
    +> print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled
    +23
    +>
    +
    +

    There is a slight difference with enums when in C mode. As per C standard, enums from C structures are exported to +surrounding scope without any prefixing. Pretending that Test2 is a struct, not class, that would be:

    +
    +> print(example.TEST3) -- NOT Test2_TEST3
    +20
    +>
    +
    + +

    28.3.17.3 Inheritance

    + + +

    The internal organization of inheritance has changed. +Consider the following C++ code:

    +
    %module example
    +class Base {
    +  public:
    +  int base_func()
    +};
    +class Derived : public Base {
    +  public:
    +  int derived_func()
    +}
    +
    +

    Lets assume for a moment that class member functions are stored in .fn table. Previously, when classes +were exported to Lua during module initialization, for every derived class all service tables ST(i.e. ".fn") +were squashed and added to corresponding derived class ST: Everything from .fn table of class Base +was copied to .fn table of class Derived and so on. This was a recursive procedure, so in the end the whole +inheritance tree of derived class was squashed into derived class.

    +

    That means that any changes done to class Base after module initialization wouldn't affect class Derived:

    +
    +base = example.Base()
    +der = example.Derived()
    +> print(base.base_func)
    +function: 0x1367940
    +> getmetatable(base)[".fn"].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!)
    +> print(base.new_func) -- Checking this function
    +function
    +> print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more.
    +nil
    +>
    +
    +

    This behaviour was changed. Now unless -squash-bases option is provided, Derived store a list of it's bases and if some symbol is not found in it's own service tables +then its bases are searched for it. Option -squash-bases will effectively return old behaviour. +

    +> print(der.new_func) -- Now it works
    +function
    +>
    +
    + +

    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

    -

    26.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:

    @@ -1270,8 +1536,8 @@ add exception specification to functions or globally (respectively).
    %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);
    @@ -1290,7 +1556,7 @@ Received an integer : 6
     720
     
    -

    26.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.

    @@ -1343,7 +1609,7 @@ void swap(int *sx, int *sy);

    Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a const int& as an input parameter (since that it obviously input).

    -

    26.4.3 Typemaps and arrays

    +

    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 @@ -1359,7 +1625,7 @@ extern void sort_double(double* arr, int len); to create an array in C/C++ then this can be filled within Lua and passed into the function. It works, but it's a bit tedious. More details can be found in the carrays.i documentation.

    -

    The second and more intuitive way, would be to pass a Lua table directly into the function, and have SWIG automatically convert between Lua-table and C-array. Within the <typemaps.i> file there are typemaps ready written to perform this task. To use them is again a matter of using %appy in the correct manner.

    +

    The second and more intuitive way, would be to pass a Lua table directly into the function, and have SWIG automatically convert between Lua-table and C-array. Within the <typemaps.i> file there are typemaps ready written to perform this task. To use them is again a matter of using %apply in the correct manner.

    The wrapper file below, shows both the use of carrays as well as the use of the typemap to wrap arrays.

    @@ -1407,7 +1673,7 @@ and Lua tables to be 1..N, (the indexing follows the norm for the language). In

    Note: SWIG also can support arrays of pointers in a similar manner.

    -

    26.4.4 Typemaps and pointer-pointer functions

    +

    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:

    @@ -1441,7 +1707,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -

    26.5 Writing typemaps

    +

    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.

    @@ -1450,7 +1716,7 @@ ptr=nil -- the iMath* will be GC'ed as normal

    Before proceeding, you should read the previous section on using typemaps, and look at the existing typemaps found in luatypemaps.swg and typemaps.i. These are both well documented and fairly easy to read. You should not attempt to write your own typemaps until you have read and can understand both of these files (they may well also give you an idea to base your work on).

    -

    26.5.1 Typemaps you can write

    +

    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.

    @@ -1463,7 +1729,7 @@ ptr=nil -- the iMath* will be GC'ed as normal (the syntax for the typecheck is different from the typemap, see typemaps for details). -

    26.5.2 SWIG's Lua-C API

    +

    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.

    @@ -1512,7 +1778,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp
    Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.
    -

    26.6 Customization of your Bindings

    +

    28.6 Customization of your Bindings

    @@ -1521,7 +1787,7 @@ This section covers adding of some small extra bits to your module to add the la -

    26.6.1 Writing your own custom wrappers

    +

    28.6.1 Writing your own custom wrappers

    @@ -1540,7 +1806,7 @@ int native_function(lua_State*L) // my native code The %native directive in the above example, tells SWIG that there is a function int native_function(lua_State*L); which is to be added into the module under the name 'my_func'. SWIG will not add any wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.

    -

    26.6.2 Adding additional Lua code

    +

    28.6.2 Adding additional Lua code

    @@ -1578,7 +1844,7 @@ Good uses for this feature is adding of new code, or writing helper functions to See Examples/lua/arrays for an example of this code.

    -

    26.7 Details on the Lua binding

    +

    28.7 Details on the Lua binding

    @@ -1589,7 +1855,7 @@ See Examples/lua/arrays for an example of this code.

    -

    26.7.1 Binding global data into the module.

    +

    28.7.1 Binding global data into the module.

    @@ -1649,7 +1915,7 @@ end

    That way when you call 'a=example.Foo', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code 'example.Foo=10', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.

    -

    26.7.2 Userdata and Metatables

    +

    28.7.2 Userdata and Metatables

    @@ -1729,7 +1995,7 @@ Note: Both the opaque structures (like the FILE*) and normal wrapped classes/str

    Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the class' metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.

    -

    26.7.3 Memory management

    +

    28.7.3 Memory management

    diff --git a/Doc/Manual/Makefile b/Doc/Manual/Makefile index 42149ba3a..c7769dc97 100644 --- a/Doc/Manual/Makefile +++ b/Doc/Manual/Makefile @@ -9,7 +9,7 @@ # 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 +19,34 @@ 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 --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 +55,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,10 +71,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 065313fa2..f324495a3 100644
    --- a/Doc/Manual/Modula3.html
    +++ b/Doc/Manual/Modula3.html
    @@ -1,11 +1,12 @@
    -
    +
     
     
     SWIG and Modula-3
     
    +
     
     
    -

    27 SWIG and Modula-3

    +

    29 SWIG and Modula-3

      @@ -45,7 +46,7 @@

      -This chapter describes SWIG's support of +This chapter describes SWIG's support for Modula-3. You should be familiar with the basics @@ -54,7 +55,7 @@ especially typemaps.

      -

      27.1 Overview

      +

      29.1 Overview

      @@ -84,7 +85,7 @@ FFTW -

      27.1.1 Motivation

      +

      29.1.1 Motivation

      @@ -109,7 +110,7 @@ into exceptions.

      If the library API is ill designed -writing appropriate typemaps can be still time-consuming. +writing appropriate typemaps can still be time-consuming. E.g. C programmers are very creative to work-around missing data types like (real) enumerations and sets. You should turn such work-arounds back to the Modula-3 way @@ -120,21 +121,21 @@ otherwise you lose static safety and consistency. Without SWIG you would probably never consider trying to call C++ libraries from Modula-3, but with SWIG this is becomes feasible. SWIG can generate C wrappers to C++ functions and object methods -that may throw exceptions, and then wrap these C wrappers for Module-3. +that may throw exceptions, and then wrap these C wrappers for Modula-3. To make it complete you can then hide the C interface with Modula-3 classes and exceptions.

      SWIG allows you to call C and C++ libraries from Modula-3 (even with call back -functions), but it doesn't allow you to easily integrate a Module-3 module into +functions), but it doesn't allow you to easily integrate a Modula-3 module into a C/C++ project.

      -

      27.2 Conception

      +

      29.2 Conception

      -

      27.2.1 Interfaces to C libraries

      +

      29.2.1 Interfaces to C libraries

      @@ -283,7 +284,7 @@ and the principal type must be renamed (%typemap).

      -

      27.2.2 Interfaces to C++ libraries

      +

      29.2.2 Interfaces to C++ libraries

      @@ -384,10 +385,10 @@ There is no C++ library I wrote a SWIG interface for, so I'm not sure if this is possible or sensible, yet.

      -

      27.3 Preliminaries

      +

      29.3 Preliminaries

      -

      27.3.1 Compilers

      +

      29.3.1 Compilers

      @@ -400,7 +401,7 @@ For testing examples I use Critical Mass cm3.

      -

      27.3.2 Additional Commandline Options

      +

      29.3.2 Additional Commandline Options

      @@ -477,10 +478,10 @@ Instead generate templates for some basic typemaps. -

      27.4 Modula-3 typemaps

      +

      29.4 Modula-3 typemaps

      -

      27.4.1 Inputs and outputs

      +

      29.4.1 Inputs and outputs

      @@ -694,7 +695,7 @@ consist of the following parts: -

      27.4.2 Subranges, Enumerations, Sets

      +

      29.4.2 Subranges, Enumerations, Sets

      @@ -746,7 +747,7 @@ that I'd like to automate.

      -

      27.4.3 Objects

      +

      29.4.3 Objects

      @@ -759,7 +760,7 @@ is not really useful, yet.

      -

      27.4.4 Imports

      +

      29.4.4 Imports

      @@ -792,7 +793,7 @@ IMPORT M3toC;

    -

    27.4.5 Exceptions

    +

    29.4.5 Exceptions

    @@ -816,7 +817,7 @@ you should declare %typemap("m3wrapinconv:throws") blah * %{OSError.E%}.

    -

    27.4.6 Example

    +

    29.4.6 Example

    @@ -863,10 +864,10 @@ where almost everything is generated by a typemap:

    -

    27.5 More hints to the generator

    +

    29.5 More hints to the generator

    -

    27.5.1 Features

    +

    29.5.1 Features

    @@ -903,7 +904,7 @@ where almost everything is generated by a typemap:
    -

    27.5.2 Pragmas

    +

    29.5.2 Pragmas

    @@ -926,7 +927,7 @@ where almost everything is generated by a typemap:
    -

    27.6 Remarks

    +

    29.6 Remarks

      diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index 70b0f1181..089b1a4ad 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -1,12 +1,13 @@ - + Working with Modules + -

      15 Working with Modules

      +

      16 Working with Modules

        @@ -23,7 +24,7 @@ -

        15.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.

        -

        15.2 Basics

        +

        16.2 Basics

        @@ -130,7 +131,7 @@ public:

        To create the wrapper properly, module derived_module needs to know about the base class and that its interface is covered in another module. The -line %import "base_module.i" lets SWIG know exactly that. Oftentimes +line %import "base_module.i" lets SWIG know exactly that. Often the .h file is passed to %import instead of the .i, which unfortunately doesn't work for all language modules. For example, Python requires the name of module that the base class exists in so that the proxy classes can fully inherit the @@ -176,7 +177,7 @@ in parallel from multiple threads as SWIG provides no locking - for more on that issue, read on.

        -

        15.3 The SWIG runtime code

        +

        16.3 The SWIG runtime code

        @@ -242,7 +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.

        -

        15.4 External access to the runtime

        +

        16.4 External access to the runtime

        As described in The run-time type checker, @@ -250,7 +251,9 @@ the functions SWIG_TypeQuery, SWIG_NewPointerObj, and others s to be called. Calling these functions from a typemap is supported, since the typemap code is embedded into the _wrap.c file, which has those declarations available. If you need to call the SWIG run-time functions from another C file, there is one header you need -to include. To generate the header that needs to be included, run the following command: +to include. To generate the header that needs to be included, SWIG can be run in a different +mode via -external-runtime to generate the run-time instead of the normal mode of +processing an input interface file. For example:

         $ swig -python -external-runtime <filename>
        @@ -279,7 +282,7 @@ SWIG_TYPE_TABLE to be the same as the module whose types you are trying to
         access.
         

        -

        15.5 A word of caution about static libraries

        +

        16.5 A word of caution about static libraries

        @@ -290,7 +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.

        -

        15.6 References

        +

        16.6 References

        @@ -298,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.

        -

        15.7 Reducing the wrapper file size

        +

        16.7 Reducing the wrapper file size

        diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index 3b49a2974..c5c199262 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -1,14 +1,14 @@ - - + SWIG and MzScheme/Racket + -

        28 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. -

          28.1 Creating native structures

          +

          30.1 Creating native structures

          @@ -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...
           
          -

          28.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.
        -

        28.3 External documentation

        +

        30.3 External documentation

        diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index ba8aa5fa9..e489c4147 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -1,12 +1,13 @@ - + - SWIG and Ocaml +SWIG and Ocaml + - - -

        29 SWIG and Ocaml

        + + +

        31 SWIG and Ocaml

      @@ -59,74 +60,76 @@

      - This chapter describes SWIG's -support of Ocaml. Ocaml is a relatively recent addition to the ML family, -and is a recent addition to SWIG. It's the second compiled, typed -language to be added. Ocaml has widely acknowledged benefits for engineers, -mostly derived from a sophisticated type system, compile-time checking -which eliminates several classes of common programming errors, and good -native performance. While all of this is wonderful, there are well-written -C and C++ libraries that Ocaml users will want to take advantage of as -part of their arsenal (such as SSL and gdbm), as well as their own mature -C and C++ code. SWIG allows this code to be used in a natural, type-safe -way with Ocaml, by providing the necessary, but repetitive glue code -which creates and uses Ocaml values to communicate with C and C++ code. - In addition, SWIG also produces the needed Ocaml source that binds -variants, functions, classes, etc. +This chapter describes SWIG's support of Ocaml. +

      + +

      +Ocaml is a relatively recent addition to the ML family, +and is a recent addition to SWIG. It's the second compiled, typed +language to be added. Ocaml has widely acknowledged benefits for engineers, +mostly derived from a sophisticated type system, compile-time checking +which eliminates several classes of common programming errors, and good +native performance. While all of this is wonderful, there are well-written +C and C++ libraries that Ocaml users will want to take advantage of as +part of their arsenal (such as SSL and gdbm), as well as their own mature +C and C++ code. SWIG allows this code to be used in a natural, type-safe +way with Ocaml, by providing the necessary, but repetitive glue code +which creates and uses Ocaml values to communicate with C and C++ code. +In addition, SWIG also produces the needed Ocaml source that binds +variants, functions, classes, etc.

      If you're not familiar with the Objective Caml language, you can visit -The Ocaml Website. +The Ocaml Website.

      -

      29.1 Preliminaries

      +

      31.1 Preliminaries

      - SWIG 1.3 works with Ocaml 3.04 and above. Given the choice, - you should use the latest stable release. The SWIG Ocaml module has -been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The -best way to determine whether your system will work is to compile the -examples and test-suite which come with SWIG. You can do this by running -make check from the SWIG root directory after installing SWIG. - The Ocaml module has been tested using the system's dynamic linking (the -usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's -Dl package -. The ocaml_dynamic and ocaml_dynamic_cpp targets in the +SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice, +you should use the latest stable release. The SWIG Ocaml module has +been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The +best way to determine whether your system will work is to compile the +examples and test-suite which come with SWIG. You can do this by running +make check from the SWIG root directory after installing SWIG. +The Ocaml module has been tested using the system's dynamic linking (the +usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's +Dl package. +The ocaml_dynamic and ocaml_dynamic_cpp targets in the file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far.

      -

      29.1.1 Running SWIG

      +

      31.1.1 Running SWIG

      - The basics of getting a SWIG Ocaml module up and running - can be seen from one of SWIG's example Makefiles, but is also described - here. To build an Ocaml module, run SWIG using the -ocaml -option. +The basics of getting a SWIG Ocaml module up and running +can be seen from one of SWIG's example Makefiles, but is also described +here. To build an Ocaml module, run SWIG using the -ocaml +option.

      -
      -
      +
      +
       %swig -ocaml example.i
      -  
      +
      - -

      This will produce 3 files. The file example_wrap.c contains + +

      This will produce 3 files. The file example_wrap.c contains all of the C code needed to build an Ocaml module. To build the module, -you will compile the file example_wrap.c with ocamlc or +you will compile the file example_wrap.c with ocamlc or ocamlopt to create the needed .o file. You will need to compile the resulting .ml and .mli files as well, and do the final link with -custom -(not needed for native link).

      - -

      29.1.2 Compiling the code

      +(not needed for native link).

      + +

      31.1.2 Compiling the code

      -The O'Caml SWIG module now requires you to compile a module (Swig) +The OCaml SWIG module now requires you to compile a module (Swig) separately. In addition to aggregating common SWIG functionality, the Swig module contains the data structure that represents C/C++ values. This allows easier data sharing between modules if two or more are combined, because @@ -134,39 +137,40 @@ the type of each SWIG'ed module's c_obj is derived from Swig.c_obj_t. This also allows SWIG to acquire new conversions painlessly, as well as giving the user more freedom with respect to custom typing. - Use ocamlc or ocamlopt to compile your - SWIG interface like: +Use ocamlc or ocamlopt to compile your SWIG interface like:

      - -
      -
      +
      +
      +
       % swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
       % ocamlc -c swig.mli ; ocamlc -c swig.ml
       % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c
       % ocamlc -c example.mli
       % ocamlc -c example.ml
      -  
      -
      - -

      ocamlc is aware of .c files and knows how to handle them. Unfortunately, - it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked - in C++ mode, you must:

      - -
      -
      -% cp example_wrap.cxx example_wrap.cxx.c
      % ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
      % ...
      -
      +
      -

      29.1.3 The camlp4 module

      +

      ocamlc is aware of .c files and knows how to handle them. Unfortunately, +it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked +in C++ mode, you must:

      + +
      +
      +% cp example_wrap.cxx example_wrap.cxx.c
      +% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
      +% ...
      +
      +
      + +

      31.1.3 The camlp4 module

      The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple rewriter which -makes C++ code blend more seamlessly with objective caml code. It's use is +makes C++ code blend more seamlessly with objective caml code. Its use is optional, but encouraged. The source file is included in the Lib/ocaml -directory of the SWIG source distribution. You can checkout this file with -"swig -ocaml -co swigp4.ml". You should compile the file with +directory of the SWIG source distribution. You can checkout this file with +"swig -ocaml -co swigp4.ml". You should compile the file with "ocamlc -I `camlp4 -where` -pp 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"

      @@ -192,7 +196,7 @@ a '+= b (invoke object) "+=" argument as in
      (invoke a) "+=" b -Note that because camlp4 always recognizes << +Note that because camlp4 always recognizes << and >>, they are replaced by lsl and lsr in operator names. 'unop object as in
      @@ -234,21 +238,21 @@ let b = C_string (getenv "PATH") -

      29.1.4 Using your module

      +

      31.1.4 Using your module

      You can test-drive your module by building a toplevel ocaml interpreter. Consult the ocaml manual for details.

      - +

      When linking any ocaml bytecode with your module, use the -custom - option to build your functions into the primitive list. This - option is not needed when you build native code. +option to build your functions into the primitive list. This +option is not needed when you build native code.

      -

      29.1.5 Compilation problems and compiling with C++

      +

      31.1.5 Compilation problems and compiling with C++

      @@ -259,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.

      -

      29.2 The low-level Ocaml/C interface

      +

      31.2 The low-level Ocaml/C interface

      @@ -273,9 +277,9 @@ In the code as seen by the typemap writer, there is a value, swig_result, that always contains the current return data. It is a list, and must be appended with the caml_list_append function, or with functions and macros provided by -objective caml.
      +objective caml.

      - +
       type c_obj =
           C_void
      @@ -299,68 +303,67 @@ type c_obj =
       

      - A few functions exist which generate and return these: +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.
      • -
      • caml_long_val receives a c_obj and returns a long.  This - 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 - it's bool value.
      • -
      • caml_val_(u)?(char|short|int|long|float|double) receives an -appropriate C value and returns a c_obj representing it.
      • -
      • caml_val_string receives a char * and returns a string value.
      • -
      • caml_val_string_len receives a char * and a length and returns - 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.
      • - +
      • caml_ptr_val receives a c_obj and returns a void *. This + 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.
      • +
      • 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.
      • +
      • caml_val_(u)?(char|short|int|long|float|double) receives an + appropriate C value and returns a c_obj representing it.
      • +
      • caml_val_string receives a char * and returns a string value.
      • +
      • caml_val_string_len receives a char * and a length and returns + 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.

      Because of this style, a typemap can return any kind of value it -wants from a function.  This enables out typemaps and inout typemaps -to work well.  The one thing to remember about outputting values -is that you must append them to the return list with swig_result = caml_list_append(swig_result,v). +wants from a function. This enables out typemaps and inout typemaps +to work well. The one thing to remember about outputting values +is that you must append them to the return list with swig_result = caml_list_append(swig_result,v).

      - This function will return a new list that has your element - appended. Upon return to caml space, the fnhelper function - beautifies the result. A list containing a single item degrades to - only that item (i.e. [ C_int 3 ] -> C_int 3), and a list - containing more than one item is wrapped in C_list (i.e. [ C_char - 'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b - ]).  This is in order to make return values easier to handle - when functions have only one return value, such as constructors, - and operators.  In addition, string, pointer, and object - values are interchangeable with respect to caml_ptr_val, so you can - allocate memory as caml strings and still use the resulting - pointers for C purposes, even using them to construct simple objects - on. Note, though, that foreign C++ code does not respect the garbage - collector, although the SWIG interface does.

      +This function will return a new list that has your element +appended. Upon return to caml space, the fnhelper function +beautifies the result. A list containing a single item degrades to +only that item (i.e. [ C_int 3 ] -> C_int 3), and a list +containing more than one item is wrapped in C_list (i.e. [ C_char +'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b +]). This is in order to make return values easier to handle +when functions have only one return value, such as constructors, +and operators. In addition, string, pointer, and object +values are interchangeable with respect to caml_ptr_val, so you can +allocate memory as caml strings and still use the resulting +pointers for C purposes, even using them to construct simple objects +on. Note, though, that foreign C++ code does not respect the garbage +collector, although the SWIG interface does.

      -

      - The wild card type that you can use in lots of different ways is - C_obj. It allows you to wrap any type of thing you like as an - object using the same mechanism that the ocaml module - does.  When evaluated in caml_ptr_val, the returned value is - the result of a call to the object's "&" operator, taken as a pointer. -

      -

      - You should only construct values using objective caml, or using the - functions caml_val_* functions provided as static functions to a SWIG - ocaml module, as well as the caml_list_* functions. These functions - provide everything a typemap needs to produce values. In addition, - value items pass through directly, but you must make your own type - signature for a function that uses value in this way. -

      +

      +The wild card type that you can use in lots of different ways is +C_obj. It allows you to wrap any type of thing you like as an +object using the same mechanism that the ocaml module +does. When evaluated in caml_ptr_val, the returned value is +the result of a call to the object's "&" operator, taken as a pointer. +

      -

      29.2.1 The generated module

      +

      +You should only construct values using objective caml, or using the +functions caml_val_* functions provided as static functions to a SWIG +ocaml module, as well as the caml_list_* functions. These functions +provide everything a typemap needs to produce values. In addition, +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

      @@ -376,7 +379,7 @@ that the keywords are not the same as the C++ ones. You can introduce extra code into the output wherever you like with SWIG. These are the places you can introduce code: - @@ -385,25 +388,25 @@ file. - +
      "header"This code is inserted near the beginning of the +
      "header"This code is inserted near the beginning of the C wrapper file, before any function definitions.
      "wrapper"This code is inserted in the function definition section.
      "mli"This code is inserted into the caml interface file. Special signatures should be inserted here.
      "ml"This code is inserted in the caml code defining the +
      "ml"This code is inserted in the caml code defining the interface to your C code. Special caml code, as well as any initialization which should run when the module is loaded may be inserted here. -
      "classtemplate"The "classtemplate" place is special because it describes the output SWIG will generate for class definitions.
      - -

      29.2.2 Enums

      + +

      31.2.2 Enums

      SWIG will wrap enumerations as polymorphic variants in the output -Ocaml code, as above in C_enum.  In order to support all +Ocaml code, as above in C_enum. In order to support all C++-style uses of enums, the function int_to_enum and enum_to_int are provided for ocaml code to produce and consume these values as -integers.  Other than that, correct uses of enums will not have -a problem.  Since enum labels may overlap between enums, the +integers. Other than that, correct uses of enums will not have +a problem. Since enum labels may overlap between enums, the enum_to_int and int_to_enum functions take an enum type label as an argument. Example:

      @@ -416,9 +419,9 @@ enum c_enum_type { a = 1, b, c = 4, d = 8 }; enum c_enum_type { a = 1, b, c = 4, d = 8 };
      -

      +

      The output mli contains: -

      +

       type c_enum_type = [
      @@ -435,16 +438,16 @@ type c_enum_tag = [
       val int_to_enum c_enum_type -> int -> c_obj
       val enum_to_int c_enum_type -> c_obj -> c_obj
       
      -
      +

      - So it's possible to do this: +So it's possible to do this:

      -
      -
      +
      +
       bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
      -bash-2.05a$ ./enum_test_top 
      +bash-2.05a$ ./enum_test_top
               Objective Caml version 3.04
       
       # open Enum_test ;;
      @@ -455,9 +458,9 @@ val x : Enum_test.c_obj = C_enum `a
       # int_to_enum `c_enum_type 4 ;;
       - : Enum_test.c_obj = C_enum `c
       
      -
      +
      -

      29.2.2.1 Enum typing in Ocaml

      +

      31.2.2.1 Enum typing in Ocaml

      @@ -470,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.

      -

      29.2.3 Arrays

      +

      31.2.3 Arrays

      -

      29.2.3.1 Simple types of bounded arrays

      +

      31.2.3.1 Simple types of bounded arrays

      @@ -485,7 +488,7 @@ distribution.

      By including "carray.i", you will get access to some macros that help you -create typemaps for array types fairly easily. +create typemaps for array types fairly easily.

      @@ -494,7 +497,7 @@ arrays of simple types with known bounds in your code, but this only works for arrays whose bounds are completely specified.

      -

      29.2.3.2 Complex and unbounded arrays

      +

      31.2.3.2 Complex and unbounded arrays

      @@ -507,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.

      -

      29.2.3.3 Using an object

      +

      31.2.3.3 Using an object

      @@ -521,7 +524,7 @@ Consider writing an object when the ending condition of your array is complex, such as using a required sentinel, etc.

      -

      29.2.3.4 Example typemap for a function taking float * and int

      +

      31.2.3.4 Example typemap for a function taking float * and int

      @@ -541,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 ); @@ -572,30 +575,30 @@ void printfloats( float *tab, int len ); -

      29.2.4 C++ Classes

      +

      31.2.4 C++ Classes

      C++ classes, along with structs and unions are represented by C_obj -(string -> c_obj -> c_obj) wrapped closures.  These objects +(string -> c_obj -> c_obj) wrapped closures. These objects contain a method list, and a type, which allow them to be used like C++ objects. When passed into typemaps that use pointers, they -degrade to pointers through their "&" method.  Every method +degrade to pointers through their "&" method. Every method an object has is represented as a string in the object's method table, -and each method table exists in memory only once.  In addition +and each method table exists in memory only once. In addition to any other operators an object might have, certain builtin ones are -provided by SWIG: (all of these take no arguments (C_void)) +provided by SWIG: (all of these take no arguments (C_void))

      - - @@ -603,8 +606,8 @@ have been wrapped by SWIG. indicated parent class. This is mainly used internally by the SWIG module, but may be useful to client programs.
      "~"Delete this object
      "&"Return an ordinary C_ptr value representing this +
      "&"Return an ordinary C_ptr value representing this object's address
      "sizeof"If enabled with ("sizeof"="1") on the module node, return the object's size in char.
      ":methods"Returns a list of strings containing the names of the methods this object contains
      ":classof"Returns the name of the class this object belongs +
      ":classof"Returns the name of the class this object belongs to.
      ":parents"Returns a list of all direct parent classes which have been wrapped by SWIG.
      "[member-variable]"Each member variable is wrapped as a -method with an optional parameter. -Called with one argument, the member variable is set to the value of the +method with an optional parameter. +Called with one argument, the member variable is set to the value of the argument. With zero arguments, the value is returned.
      @@ -615,7 +618,7 @@ the underlying pointer, so using create_[x]_from_ptr alters the returned value for the same object.

      -

      29.2.4.1 STL vector and string Example

      +

      31.2.4.1 STL vector and string Example

      @@ -637,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" @@ -652,12 +655,12 @@ Since there's a makefile in that directory, the example is easy to build.

      Here's a sample transcript of an interactive session using a string vector -after making a toplevel (make toplevel). This example uses the camlp4 +after making a toplevel (make toplevel). This example uses the camlp4 module.

      -bash-2.05a$ ./example_top 
      +bash-2.05a$ ./example_top
               Objective Caml version 3.06
       
               Camlp4 Parsing version 3.06
      @@ -685,17 +688,17 @@ C_list
       - : Example.c_obj = C_void
       # x '[1] ;;
       - : Example.c_obj = C_string "spam"
      -# for i = 0 to (x -> size() as int) - 1 do 
      -    print_endline ((x '[i to int]) as string) 
      +# for i = 0 to (x -> size() as int) - 1 do
      +    print_endline ((x '[i to int]) as string)
         done ;;
       foo
       bar
       baz
       - : unit = ()
      -# 
      +#
       
      -

      29.2.4.2 C++ Class Example

      +

      31.2.4.2 C++ Class Example

      @@ -703,7 +706,7 @@ Here's a simple example using Trolltech's Qt Library:

      - +
      qt.i
      qt.i
       %module qt
       %{
      @@ -712,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();
       };
       
      -

      29.2.4.3 Compiling the example

      +

      31.2.4.3 Compiling the example

      @@ -733,9 +736,9 @@ bash-2.05a$ QTPATH=/your/qt/path
       bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
       bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml
       bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml
      -bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include  qt.i
      +bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i
       bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
      -bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c 
      +bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c
       bash-2.05a$ ocamlc -c qt.mli
       bash-2.05a$ ocamlc -c qt.ml
       bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
      @@ -743,11 +746,11 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
         -L$QTPATH/lib -cclib -lqt
       
      -

      29.2.4.4 Sample Session

      +

      31.2.4.4 Sample Session

      -bash-2.05a$ ./qt_top 
      +bash-2.05a$ ./qt_top
               Objective Caml version 3.06
       
               Camlp4 Parsing version 3.06
      @@ -767,13 +770,13 @@ val hello : Qt.c_obj = C_obj <fun>
       
       

      Assuming you have a working installation of QT, you will see a window -containing the string "hi" in a button. +containing the string "hi" in a button.

      -

      29.2.5 Director Classes

      +

      31.2.5 Director Classes

      -

      29.2.5.1 Director Introduction

      +

      31.2.5.1 Director Introduction

      @@ -800,7 +803,7 @@ class foo { };

      -

      29.2.5.2 Overriding Methods in Ocaml

      +

      31.2.5.2 Overriding Methods in Ocaml

      @@ -828,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.

      -

      29.2.5.3 Director Usage Example

      +

      31.2.5.3 Director Usage Example

      @@ -845,14 +848,14 @@ 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 ;; let triangle = - new_derived_object + new_derived_object new_shape (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) '() ;; @@ -887,7 +890,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the program in C++.

      -

      29.2.5.4 Creating director objects

      +

      31.2.5.4 Creating director objects

      @@ -896,7 +899,7 @@ The definition of the actual object triangle can be described this way:

       let triangle =
      -  new_derived_object 
      +  new_derived_object
           new_shape
           (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
           '()
      @@ -904,13 +907,13 @@ let triangle =
       
       

      The first argument to new_derived_object, new_shape is the method -which returns a shape instance. This function will be invoked with the +which returns a shape instance. This function will be invoked with the third argument will be appended to the argument list [ C_void ]. In the example, the actual argument list is sent as (C_list [ C_void ; C_void ]). The augmented constructor for a director class needs the first argument to determine whether it is being constructed as a derived object, or as an object of the indicated type only (in this case shape). The -Second argument is a closure that will be added to the final C_obj. +Second argument is a closure that will be added to the final C_obj.

      @@ -928,7 +931,7 @@ object from causing a core dump, as long as the object is destroyed properly.

      -

      29.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      +

      31.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      @@ -939,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.

      -

      29.2.5.6 directorin typemap

      +

      31.2.5.6 typemap

      @@ -950,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.

      -

      29.2.5.7 directorout typemap

      +

      31.2.5.7 directorout typemap

      @@ -961,7 +964,7 @@ for the same type, except when there are special requirements for object ownership, etc.

      -

      29.2.5.8 directorargout typemap

      +

      31.2.5.8 directorargout typemap

      @@ -978,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.

      -

      29.2.6 Exceptions

      +

      31.2.6 Exceptions

      diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 3229299d5..9b9744f65 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -1,14 +1,15 @@ - + SWIG and Octave + -

      30 SWIG and Octave

      +

      32 SWIG and Octave

        @@ -33,6 +34,10 @@
      • Class extension with %extend
      • C++ templates
      • C++ Smart Pointers +
      • Directors (calling Octave from C++ code)
      • Threads
      • Memory management @@ -55,18 +60,16 @@ More information can be found at O Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).

        -

        30.1 Preliminaries

        +

        32.1 Preliminaries

        -The SWIG implemention was first based on Octave 2.9.12, so this is the minimum version required. Testing has only been done on Linux. +As of SWIG 3.0.7, the Octave module is regularly tested with Octave versions 3.2.4, 3.8.1, and 4.0.0. +Use of older Octave versions is not recommended, as these versions are no longer tested with SWIG. +The SWIG runtime exports the function swig_octave_prereq() for checking the version of Octave.

        -

        -As of SWIG 2.0.5, the Octave module should work with Octave versions 3.0.5, 3.2.4, and 3.4.0. -

        - -

        30.2 Running SWIG

        +

        32.2 Running SWIG

        @@ -74,7 +77,7 @@ Let's start with a very simple SWIG interface file, example.i:

        -%module example
        +%module swigexample
         %{
         #include "example.h"
         %}
        @@ -95,10 +98,10 @@ The -c++ option is also required when wrapping C++ code:
         
        $ swig -octave -c++ -o example_wrap.cpp example.i 

        -This creates a C++ source file example_wrap.cpp. A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module. +This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.

        -

        30.2.1 Command-line options

        +

        32.2.1 Command-line options

        @@ -110,21 +113,18 @@ Options specific to the Octave module are:

        $ swig -octave -help
         ...
         Octave Options (available with -octave)
        -     -global       - Load all symbols into the global namespace [default]
              -globals name - Set name used to access C global variables [default: 'cvar']
        -                         - Use '.' to load C global variables into module namespace
        -     -noglobal     - Do not load all symbols into the global namespace
        +                     Use '.' to load C global variables into module namespace
              -opprefix str - Prefix str for global operator functions [default: 'op_']
         

        -The -global and -noglobal options determine whether the Octave module will load all symbols into the global namespace in addition to the global namespace. The -globals option sets the name of the variable which is the namespace for C global variables exported by the module. The special name "." loads C global variables into the module namespace, i.e. alongside C functions and structs exported by the module. The -opprefix options sets the prefix of the names of global/friend operator functions.

        -

        30.2.2 Compiling a dynamic module

        +

        32.2.2 Compiling a dynamic module

        @@ -138,7 +138,7 @@ $ mkoctfile example_wrap.cpp example.c

      - where example.c is the file containing the gcd() implementation. + where "example.c" is the file containing the gcd() implementation.

      @@ -146,12 +146,12 @@ $ mkoctfile example_wrap.cpp example.c

      - mkoctfile will produce example.oct, which contains the compiled extension module. Loading it into Octave is then a matter of invoking + mkoctfile will produce "swigexample.oct", which contains the compiled extension module. Loading it into Octave is then a matter of invoking

      -
      octave:1> example
      +
      octave:1> swigexample
      -

      30.2.3 Using your module

      +

      32.2.3 Using your module

      @@ -160,75 +160,42 @@ Assuming all goes well, you will be able to do this:

      $ octave -q
      -octave:1> example
      -octave:2> example.gcd(4,6)
      +octave:1> swigexample
      +octave:2> swigexample.gcd(4,6)
       ans =  2
      -octave:3> example.cvar.Foo
      +octave:3> swigexample.cvar.Foo
       ans =  3
      -octave:4> example.cvar.Foo=4;
      -octave:5> example.cvar.Foo
      +octave:4> swigexample.cvar.Foo=4;
      +octave:5> swigexample.cvar.Foo
       ans =  4 
      -

      30.3 A tour of basic C/C++ wrapping

      +

      32.3 A tour of basic C/C++ wrapping

      -

      30.3.1 Modules

      +

      32.3.1 Modules

      -The SWIG module directive specifies the name of the Octave module. If you specify `module example', then in Octave everything in the module will be accessible under "example", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name. +The SWIG module directive specifies the name of the Octave module. If you specify "module swigexample", then in Octave everything in the module will be accessible under "swigexample", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name.

      -When Octave is asked to invoke example, it will try to find the .m or .oct file that defines the function "example". It will thusly find example.oct, that upon loading will register all of the module's symbols. +When Octave is asked to invoke swigexample, it will try to find the ".m" or ".oct" file that defines the function "swigexample". You therefore need to make sure that "swigexample.oct" is in Octave's search path, which can be specified with the environment variable "OCTAVE_PATH".

      -An Octave module takes three options, -global, -noglobal, and -globals, which behave the same as the corresponding swig command-line options. -Here are some example usages: +To load an Octave module, simply type its name:

      -
      -octave:1> example -help
      -usage: example [-global|-noglobal] [-globals <name>]
      -octave:2> example -global
      -octave:3> gcd(4,6)
      +
      +octave:1> swigexample;
      +octave:2> gcd(4,6)
       ans =  2
      -octave:4> cvar.Foo
      -ans =  3
      -octave:5> cvar.Foo=4;
      -octave:6> cvar.Foo
      -ans =  4
      -
      -
      -
      -octave:1> example -noglobal
      -octave:2> gcd(6,9)
      -ans =  3
       octave:3> cvar.Foo
      -error: `cvar' undefined near line 3 column 1
      -octave:3> example.cvar.Foo
      -ans =  3
      -
      -
      -
      -octave:1> example -globals mycvar
      -octave:2> cvar.Foo
      -error: `cvar' undefined near line 2 column 1
      -octave:2> mycvar.Foo
      -ans =  3
      -
      - -

      - It is also possible to rename the module / global variables namespaces with an assignment, as in:
      -

      -octave:1> example
      -octave:2> c=example;
      -octave:3> c.gcd(10,4)
      -ans =  2
      -octave:4> some_vars = cvar;
      -octave:5> some_vars.Foo
       ans =  3
      +octave:4> cvar.Foo=4;
      +octave:5> cvar.Foo
      +ans =  4
       

      @@ -238,64 +205,64 @@ If the module is also used in the base context, however, it must first be loaded

       octave:1> function l = my_lcm(a,b)
      -> example
      -> l = abs(a*b)/example.gcd(a,b);
      +> swigexample
      +> l = abs(a*b)/swigexample.gcd(a,b);
       > endfunction
       octave:2> my_lcm(4,6)
       ans =  12
      -octave:3> example.gcd(4,6)
      +octave:3> swigexample.gcd(4,6)
       error: can't perform indexing operations for <unknown type> type
      -octave:3> example;
      -octave:4> example.gcd(4,6)
      +octave:3> swigexample;
      +octave:4> swigexample.gcd(4,6)
       ans =  2
       
      -

      30.3.2 Functions

      +

      32.3.2 Functions

      Global functions are wrapped as new Octave built-in functions. For example,

      -
      %module example
      +      
      %module swigexample
       int fact(int n); 

      - creates a built-in function example.fact(n) that works exactly like you think it does: + creates a built-in function swigexample.fact(n) that works exactly like you think it does:

      -
      octave:1> example.fact(4)
      +    
      octave:1> swigexample.fact(4)
       24 
      -

      30.3.3 Global variables

      +

      32.3.3 Global variables

      Global variables are a little special in Octave. Given a global variable:

      -
      %module example
      +
      %module swigexample
       extern double Foo;
      -      
      +

      To expose variables, SWIG actually generates two functions, to get and set the value. In this case, Foo_set and Foo_set would be generated. SWIG then automatically calls these functions when you get and set the variable-- in the former case creating a local copy in the interpreter of the C variables, and in the latter case copying an interpreter variables onto the C variable.

      -
      octave:1> example;
      -octave:2> c=example.cvar.Foo
      +    
      octave:1> swigexample;
      +octave:2> c=swigexample.cvar.Foo
       c =  3
      -octave:3> example.cvar.Foo=4;
      +octave:3> swigexample.cvar.Foo=4;
       octave:4> c
       c =  3
      -octave:5> example.cvar.Foo
      +octave:5> swigexample.cvar.Foo
       ans =  4

      If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Octave error. Given a global variable:

      -
      %module example
      +    
      %module swigexample
       %immutable;
       extern double Foo;
       %mutable;
      @@ -305,8 +272,8 @@ extern double Foo;
            SWIG will allow the reading of Foo but when a set attempt is made, an error function will be called. 
       

      -
      octave:1> example
      -octave:2> example.Foo=4
      +    
      octave:1> swigexample
      +octave:2> swigexample.Foo=4
       error: attempt to set immutable member variable
       error: assignment failed, or no method for `swig_type = scalar'
       error: evaluating assignment expression near line 2, column 12 
      @@ -315,19 +282,19 @@ error: evaluating assignment expression near line 2, column 12
      It is possible to add new functions or variables to the module. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so.

      -
      octave:1> example;
      -octave:2> example.PI=3.142;
      -octave:3> example.PI
      +    
      octave:1> swigexample;
      +octave:2> swigexample.PI=3.142;
      +octave:3> swigexample.PI
       ans =  3.1420 
      -

      30.3.4 Constants and enums

      +

      32.3.4 Constants and enums

      Because Octave doesn't really have the concept of constants, C/C++ constants are not really constant in Octave. They are actually just a copy of the value into the Octave interpreter. Therefore they can be changed just as any other value. For example given some constants:

      -
      %module example
      +    
      %module swigexample
       %constant int ICONST=42;
       #define    SCONST      "Hello World"
       enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
      @@ -337,12 +304,12 @@ enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
           This is 'effectively' converted into the following Octave code: 
       

      -
      example.ICONST=42
      -example.SCONST="Hello World"
      -example.SUNDAY=0
      +    
      swigexample.ICONST=42
      +swigexample.SCONST="Hello World"
      +swigexample.SUNDAY=0
       .... 
      -

      30.3.5 Pointers

      +

      32.3.5 Pointers

      @@ -350,7 +317,7 @@ example.SUNDAY=0 C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:

      -
      %module example
      +
      %module swigexample
       FILE *fopen(const char *filename, const char *mode);
       int fputs(const char *, FILE *);
       int fclose(FILE *);
      @@ -361,18 +328,18 @@ When wrapped, you will be able to use the functions in a natural way from Octave
       

      -octave:1> example;
      -octave:2> f=example.fopen("w","junk");
      -octave:3> example.fputs("Hello world",f);
      -octave:4> example.fclose(f);
      +octave:1> swigexample;
      +octave:2> f=swigexample.fopen("w","junk");
      +octave:3> swigexample.fputs("Hello world",f);
      +octave:4> swigexample.fclose(f);
       

      - Simply printing the value of a wrapped C++ type will print it's typename. E.g., + Simply printing the value of a wrapped C++ type will print its typename. E.g.,

      -
      octave:1> example;
      -octave:2> f=example.fopen("junk","w");
      +    
      octave:1> swigexample;
      +octave:2> f=swigexample.fopen("junk","w");
       octave:3> f
       f =
       
      @@ -384,12 +351,12 @@ f =
           As the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes and structs (see below).
       

      -
      octave:1> example;
      -octave:2> f=example.fopen("not there","r");
      +    
      octave:1> swigexample;
      +octave:2> f=swigexample.fopen("not there","r");
       error: value on right hand side of assignment is undefined
       error: evaluating assignment expression near line 2, column 2 
      -

      30.3.6 Structures and C++ classes

      +

      32.3.6 Structures and C++ classes

      @@ -407,8 +374,8 @@ For each wrapped structure and class, a swig_ref will be exposed that h

      -
      octave:1> example;
      -octave:2> p=example.Point();
      +      
      octave:1> swigexample;
      +octave:2> p=swigexample.Point();
       octave:3> p.x=3;
       octave:4> p.y=5;
       octave:5> p.x, p.y
      @@ -442,9 +409,9 @@ public:
       can be used from Octave like this
       

      -
      octave:1> example;
      -octave:2> p1=example.Point(3,5);
      -octave:3> p2=example.Point(1,2);
      +      
      octave:1> swigexample;
      +octave:2> p1=swigexample.Point(3,5);
      +octave:3> p2=swigexample.Point(1,2);
       octave:4> p1.distance(p2)
       ans =  3.6056
       
      @@ -524,7 +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.

      -

      30.3.7 C++ inheritance

      +

      32.3.7 C++ inheritance

      @@ -533,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.

      -

      30.3.8 C++ overloaded functions

      +

      32.3.8 C++ overloaded functions

      @@ -543,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.

      -

      30.3.9 C++ operators

      +

      32.3.9 C++ operators

      @@ -551,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 @@ -578,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.

      -

      30.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();
      @@ -674,10 +641,19 @@ octave:2> a
       a = 4
       octave:3> printf("%s\n",a);
       4
      -octave:4> a.__str()
      +octave:4> a.__str__()
       4
       
      -

      30.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

      @@ -685,7 +661,7 @@ C++ class and function templates are fully supported as in other modules, in tha For example, function templates can be instantiated as follows:

      -
      %module example
      +
      %module swigexample
       %inline {
        template<class __scalar>
          __scalar mul(__scalar a,__scalar b) {
      @@ -713,7 +689,7 @@ ans =  22 + 46i
       Similarly, class templates can be instantiated as in the following example,
       

      -
      %module example
      +
      %module swigexample
       %include <std_complex.i>
       %include <std_string.i>
       %inline {
      @@ -726,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();
      @@ -754,14 +730,28 @@ ans =
       
      -

      30.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.

      -

      30.3.13 Directors (calling Octave from C++ code)

      +

      32.3.13 Directors (calling Octave from C++ code)

      @@ -842,14 +832,14 @@ c-side routine called octave-side routine called

      -

      30.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.

      -

      30.3.15 Memory management

      +

      32.3.15 Memory management

      @@ -883,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).

      -

      30.3.16 STL support

      +

      32.3.16 STL support

      Various STL library files are provided for wrapping STL containers.

      -

      30.3.17 Matrix typemaps

      +

      32.3.17 Matrix typemaps

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 0a4b61bd5..8d7b866d6 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -1,12 +1,13 @@ - + SWIG and Perl5 + -

      31 SWIG and Perl5

      +

      33 SWIG and Perl5

      @@ -87,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.

      -

      31.1 Overview

      +

      33.1 Overview

      @@ -108,7 +118,7 @@ described. Advanced customization features, typemaps, and other options are found near the end of the chapter.

      -

      31.2 Preliminaries

      +

      33.2 Preliminaries

      @@ -133,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.

      -

      31.2.1 Getting the right header files

      +

      33.2.1 Getting the right header files

      @@ -165,13 +175,13 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'

      -

      31.2.2 Compiling a dynamic module

      +

      33.2.2 Compiling a dynamic module

      The preferred approach to building an extension module is to compile it into -a shared object file or DLL. To do this, you will need to compile your program -using commands like this (shown for Linux): +a shared object file or DLL. Assuming you have code you need to link to in a file called example.c, +you will need to compile your program using commands like this (shown for Linux):

      @@ -198,7 +208,7 @@ the target should be named `example.so',
       `example.sl', or the appropriate dynamic module name on your system.
       

      -

      31.2.3 Building a dynamic module with MakeMaker

      +

      33.2.3 Building a dynamic module with MakeMaker

      @@ -210,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 );
      @@ -232,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.

      -

      31.2.4 Building a static version of Perl

      +

      33.2.4 Building a static version of Perl

      @@ -291,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
       

      @@ -301,7 +311,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

      -

      31.2.5 Using the module

      +

      33.2.5 Using the module

      @@ -454,7 +464,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      31.2.6 Compilation problems and compiling with C++

      +

      33.2.6 Compilation problems and compiling with C++

      @@ -484,8 +494,8 @@ Solaris, you often need to add an extra library -lCrun like this:

       $ swig -c++ -perl example.i
      -$ CC -c example.cxx
      -$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
      +$ CC -Kpic -c example.cxx
      +$ CC -Kpic -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
       $ CC -shared example.o example_wrap.o -o example.so -lCrun
       
      @@ -597,7 +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.

      -

      31.2.7 Compiling for 64-bit platforms

      +

      33.2.7 Compiling for 64-bit platforms

      @@ -624,7 +634,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      31.3 Building Perl Extensions under Windows

      +

      33.3 Building Perl Extensions under Windows

      @@ -635,7 +645,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

      -

      31.3.1 Running SWIG from Developer Studio

      +

      33.3.1 Running SWIG from Developer Studio

      @@ -698,7 +708,7 @@ print "$a\n";

      -

      31.3.2 Using other compilers

      +

      33.3.2 Using other compilers

      @@ -706,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.

      -

      31.4 The low-level interface

      +

      33.4 The low-level interface

      @@ -716,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.

      -

      31.4.1 Functions

      +

      33.4.1 Functions

      @@ -739,7 +749,7 @@ use example; $a = &example::fact(2);

      -

      31.4.2 Global variables

      +

      33.4.2 Global variables

      @@ -809,7 +819,7 @@ extern char *path; // Declared later in the input

      -

      31.4.3 Constants

      +

      33.4.3 Constants

      @@ -849,7 +859,7 @@ print example::FOO,"\n";

      -

      31.4.4 Pointers

      +

      33.4.4 Pointers

      @@ -882,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.";
       }
       
       
      @@ -907,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.";
       }
       
       
      @@ -958,7 +968,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the SWIG and XS, this is no longer supported.

      -

      31.4.5 Structures

      +

      33.4.5 Structures

      @@ -968,7 +978,7 @@ accessor functions as described in the "SWIG Basics" chapter. For example,

       struct Vector {
      -	double x,y,z;
      +  double x,y,z;
       };
       
      @@ -1092,7 +1102,7 @@ void Bar_f_set(Bar *b, Foo *val) {
      -

      31.4.6 C++ classes

      +

      33.4.6 C++ classes

      @@ -1157,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.

      -

      31.4.7 C++ classes and type-checking

      +

      33.4.7 C++ classes and type-checking

      @@ -1193,7 +1203,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

      -

      31.4.8 C++ overloaded functions

      +

      33.4.8 C++ overloaded functions

      @@ -1237,7 +1247,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.

      -

      31.4.9 Operators

      +

      33.4.9 Operators

      @@ -1249,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
      -

      31.4.10 Modules and packages

      +

      33.4.10 Modules and packages

      @@ -1359,7 +1369,7 @@ print Foo::fact(4),"\n"; # Call a function in package FooBar

      --> -

      31.5 Input and output parameters

      +

      33.5 Input and output parameters

      @@ -1578,7 +1588,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

      -

      31.6 Exception handling

      +

      33.6 Exception handling

      @@ -1743,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.

      -

      31.7 Remapping datatypes with typemaps

      +

      33.7 Remapping datatypes with typemaps

      @@ -1760,7 +1770,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

      -

      31.7.1 A simple typemap example

      +

      33.7.1 A simple typemap example

      @@ -1773,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 %{ @@ -1819,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;
      @@ -1864,7 +1874,7 @@ example::count("e","Hello World");
       
      -

      31.7.2 Perl5 typemaps

      +

      33.7.2 Perl5 typemaps

      @@ -1969,7 +1979,7 @@ Return of C++ member data (all languages). Check value of input parameter.

      -

      31.7.3 Typemap variables

      +

      33.7.3 Typemap variables

      @@ -2040,7 +2050,7 @@ properly assigned. The Perl name of the wrapper function being created.

      -

      31.7.4 Useful functions

      +

      33.7.4 Useful functions

      @@ -2109,7 +2119,7 @@ int sv_isa(SV *, char *0;

      -

      31.8 Typemap Examples

      +

      33.8 Typemap Examples

      @@ -2118,7 +2128,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

      -

      31.8.1 Converting a Perl5 array to a char **

      +

      33.8.1 Converting a Perl5 array to a char **

      @@ -2133,47 +2143,47 @@ 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 @@ -2210,7 +2220,7 @@ print @$b,"\n"; # Print it out

      -

      31.8.2 Return values

      +

      33.8.2 Return values

      @@ -2230,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++;
       }
       
      -

      31.8.3 Returning values from arguments

      +

      33.8.3 Returning values from arguments

      @@ -2254,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; }; %} @@ -2293,7 +2303,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13);

      -

      31.8.4 Accessing array structure members

      +

      33.8.4 Accessing array structure members

      @@ -2356,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.

      -

      31.8.5 Turning Perl references into C pointers

      +

      33.8.5 Turning Perl references into C pointers

      @@ -2367,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;
       }
       
      @@ -2421,7 +2431,7 @@ print "$c\n";
      -

      31.8.6 Pointer handling

      +

      33.8.6 Pointer handling

      @@ -2500,7 +2510,7 @@ For example:

      -

      31.9 Proxy classes

      +

      33.9 Proxy classes

      @@ -2516,7 +2526,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

      -

      31.9.1 Preliminaries

      +

      33.9.1 Preliminaries

      @@ -2538,7 +2548,7 @@ SWIG creates a collection of high-level Perl wrappers. In your scripts, you wil high level wrappers. The wrappers, in turn, interact with the low-level procedural module.

      -

      31.9.2 Structure and class wrappers

      +

      33.9.2 Structure and class wrappers

      @@ -2548,9 +2558,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;
       };
       
       
      @@ -2600,8 +2610,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 { @@ -2653,8 +2664,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}; @@ -2664,7 +2675,7 @@ $v->DESTROY();
      -

      31.9.3 Object Ownership

      +

      33.9.3 Object Ownership

      @@ -2675,7 +2686,7 @@ problem---suppose you had a function like this:

       Vector *Vector_get(Vector *v, int index) {
      -	return &v[i];
      +  return &v[i];
       }
       
      @@ -2688,9 +2699,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;
       }
       
      @@ -2751,7 +2762,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages.

      -

      31.9.4 Nested Objects

      +

      33.9.4 Nested Objects

      @@ -2760,10 +2771,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;
       }
       
       
      @@ -2779,9 +2790,9 @@ look like this (along with some supporting code): package Particle; ... %BLESSEDMEMBERS = ( - r => `Vector', - v => `Vector', - f => `Vector', + r => `Vector', + v => `Vector', + f => `Vector', );
      @@ -2804,7 +2815,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0);
      -

      31.9.5 Proxy Functions

      +

      33.9.5 Proxy Functions

      @@ -2838,7 +2849,7 @@ This function replaces the original function, but operates in an identical manner.

      -

      31.9.6 Inheritance

      +

      33.9.6 Inheritance

      @@ -2857,23 +2868,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(); }

      @@ -2914,7 +2925,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).

      -

      31.9.7 Modifying the proxy methods

      +

      33.9.7 Modifying the proxy methods

      @@ -2942,7 +2953,7 @@ public: }; -

      31.10 Adding additional Perl code

      +

      33.10 Adding additional Perl code

      @@ -2993,6 +3004,363 @@ set_transform($im, $a); +

      33.11 Cross language polymorphism

      + + +

      +Proxy classes provide a more natural, object-oriented way to access +extension classes. As described above, each proxy instance has an +associated C++ instance, and method calls to the proxy are passed to the +C++ instance transparently via C wrapper functions. +

      + +

      +This arrangement is asymmetric in the sense that no corresponding +mechanism exists to pass method calls down the inheritance chain from +C++ to Perl. In particular, if a C++ class has been extended in Perl +(by extending the proxy class), these extensions will not be visible +from C++ code. Virtual method calls from C++ are thus not able access +the lowest implementation in the inheritance chain. +

      + +

      +Changes have been made to SWIG to address this problem and +make the relationship between C++ classes and proxy classes more +symmetric. To achieve this goal, new classes called directors are +introduced at the bottom of the C++ inheritance chain. The job of the +directors is to route method calls correctly, either to C++ +implementations higher in the inheritance chain or to Perl +implementations lower in the inheritance chain. The upshot is that C++ +classes can be extended in Perl and from C++ these extensions look +exactly like native C++ classes. Neither C++ code nor Perl code needs +to know where a particular method is implemented: the combination of +proxy classes, director classes, and C wrapper functions takes care of +all the cross-language method routing transparently. +

      + +

      33.11.1 Enabling directors

      + + +

      +The director feature is disabled by default. To use directors you +must make two changes to the interface file. First, add the "directors" +option to the %module directive, like this: +

      + +
      +
      +%module(directors="1") modulename
      +
      +
      + +

      +Without this option no director code will be generated. Second, you +must use the %feature("director") directive to tell SWIG which classes +and methods should get directors. The %feature directive can be applied +globally, to specific classes, and to specific methods, like this: +

      + +
      +
      +// generate directors for all classes that have virtual methods
      +%feature("director");         
      +
      +// generate directors for all virtual methods in class Foo
      +%feature("director") Foo;      
      +
      +
      + +

      +You can use the %feature("nodirector") directive to turn off +directors for specific classes or methods. So for example, +

      + +
      +
      +%feature("director") Foo;
      +%feature("nodirector") Foo::bar;
      +
      +
      + +

      +will generate directors for all virtual methods of class Foo except +bar(). +

      + +

      +Directors can also be generated implicitly through inheritance. +In the following, class Bar will get a director class that handles +the methods one() and two() (but not three()): +

      + +
      +
      +%feature("director") Foo;
      +class Foo {
      +public:
      +    Foo(int foo);
      +    virtual void one();
      +    virtual void two();
      +};
      +
      +class Bar: public Foo {
      +public:
      +    virtual void three();
      +};
      +
      +
      + +

      +then at the Perl side you can define +

      + +
      +
      +use mymodule;
      +
      +package MyFoo;
      +use base 'mymodule::Foo';
      +
      +sub one {
      +  print "one from Perl\n";
      +}
      +
      +
      + + +

      33.11.2 Director classes

      + + + + + +

      +For each class that has directors enabled, SWIG generates a new class +that derives from both the class in question and a special +Swig::Director class. These new classes, referred to as director +classes, can be loosely thought of as the C++ equivalent of the Perl +proxy classes. The director classes store a pointer to their underlying +Perl object and handle various issues related to object ownership. +

      + +

      +For simplicity let's ignore the Swig::Director class and refer to the +original C++ class as the director's base class. By default, a director +class extends all virtual methods in the inheritance chain of its base +class (see the preceding section for how to modify this behavior). +Thus all virtual method calls, whether they originate in C++ or in +Perl via proxy classes, eventually end up in at the implementation in +the director class. The job of the director methods is to route these +method calls to the appropriate place in the inheritance chain. By +"appropriate place" we mean the method that would have been called if +the C++ base class and its extensions in Perl were seamlessly +integrated. That seamless integration is exactly what the director +classes provide, transparently skipping over all the messy extension API +glue that binds the two languages together. +

      + +

      +In reality, the "appropriate place" is one of only two possibilities: +C++ or Perl. Once this decision is made, the rest is fairly easy. If +the correct implementation is in C++, then the lowest implementation of +the method in the C++ inheritance chain is called explicitly. If the +correct implementation is in Perl, the Perl API is used to call the +method of the underlying Perl object (after which the usual virtual +method resolution in Perl automatically finds the right +implementation). +

      + +

      +Now how does the director decide which language should handle the method call? +The basic rule is to handle the method in Perl, unless there's a good +reason not to. The reason for this is simple: Perl has the most +"extended" implementation of the method. This assertion is guaranteed, +since at a minimum the Perl proxy class implements the method. If the +method in question has been extended by a class derived from the proxy +class, that extended implementation will execute exactly as it should. +If not, the proxy class will route the method call into a C wrapper +function, expecting that the method will be resolved in C++. The wrapper +will call the virtual method of the C++ instance, and since the director +extends this the call will end up right back in the director method. Now +comes the "good reason not to" part. If the director method were to blindly +call the Perl method again, it would get stuck in an infinite loop. We avoid this +situation by adding special code to the C wrapper function that tells +the director method to not do this. The C wrapper function compares the +pointer to the Perl object that called the wrapper function to the +pointer stored by the director. If these are the same, then the C +wrapper function tells the director to resolve the method by calling up +the C++ inheritance chain, preventing an infinite loop. +

      + +

      +One more point needs to be made about the relationship between director +classes and proxy classes. When a proxy class instance is created in +Perl, SWIG creates an instance of the original C++ class. +This is exactly what happens without directors and +is true even if directors are enabled for the particular class in +question. When a class derived from a proxy class is created, +however, SWIG then creates an instance of the corresponding C++ director +class. The reason for this difference is that user-defined subclasses +may override or extend methods of the original class, so the director +class is needed to route calls to these methods correctly. For +unmodified proxy classes, all methods are ultimately implemented in C++ +so there is no need for the extra overhead involved with routing the +calls through Perl. +

      + +

      33.11.3 Ownership and object destruction

      + + +

      +Memory management issues are slightly more complicated with directors +than for proxy classes alone. Perl instances hold a pointer to the +associated C++ director object, and the director in turn holds a pointer +back to a Perl object. By default, proxy classes own their C++ +director object and take care of deleting it when they are garbage +collected. +

      + +

      +This relationship can be reversed by calling the special +DISOWN() method of the proxy class. After calling this +method the director +class increments the reference count of the Perl object. When the +director class is deleted it decrements the reference count. Assuming no +outstanding references to the Perl object remain, the Perl object +will be destroyed at the same time. This is a good thing, since +directors and proxies refer to each other and so must be created and +destroyed together. Destroying one without destroying the other will +likely cause your program to segfault. +

      + +

      +Also note that due to the proxy implementation, the DESTROY() +method on directors can be called for several reasons, many of which +have little to do with the teardown of an object instance. To help +disambiguate this, a second argument is added to the DESTROY() +call when a C++ director object is being released. So, to avoid running +your clean-up code when an object is not really going away, or after it +has already been reclaimed, it is suggested that custom destructors in +Perl subclasses looks something like: +

      + +
      +
      +sub DESTROY {
      +  my($self, $final) = @_;
      +  if($final) {
      +    # real teardown code
      +  }
      +  shift->SUPER::DESTROY(@_);
      +}
      +
      +
      + + +

      33.11.4 Exception unrolling

      + + +

      +With directors routing method calls to Perl, and proxies routing them +to C++, the handling of exceptions is an important concern. By default, the +directors ignore exceptions that occur during method calls that are +resolved in Perl. To handle such exceptions correctly, it is necessary +to temporarily translate them into C++ exceptions. This can be done with +the %feature("director:except") directive. The following code should +suffice in most cases: +

      + +
      +
      +%feature("director:except") {
      +    if ($error != NULL) {
      +        throw Swig::DirectorMethodException();
      +    }
      +}
      +
      +
      + +

      +This code will check the Perl error state after each method call from +a director into Perl, and throw a C++ exception if an error occurred. +This exception can be caught in C++ to implement an error handler. +

      + +

      +It may be the case that a method call originates in Perl, travels up +to C++ through a proxy class, and then back into Perl via a director +method. If an exception occurs in Perl at this point, it would be nice +for that exception to find its way back to the original caller. This can +be done by combining a normal %exception directive with the +director:except handler shown above. Here is an example of a +suitable exception handler: +

      + +
      +
      +%exception {
      +    try { $action }
      +    catch (Swig::DirectorException &e) { SWIG_fail; }
      +}
      +
      +
      + +

      +The class Swig::DirectorException used in this example is actually a +base class of Swig::DirectorMethodException, so it will trap this +exception. Because the Perl error state is still set when +Swig::DirectorMethodException is thrown, Perl will register the +exception as soon as the C wrapper function returns. +

      + +

      33.11.5 Overhead and code bloat

      + + +

      +Enabling directors for a class will generate a new director method for +every virtual method in the class' inheritance chain. This alone can +generate a lot of code bloat for large hierarchies. Method arguments +that require complex conversions to and from target language types can +result in large director methods. For this reason it is recommended that +you selectively enable directors only for specific classes that are +likely to be extended in Perl and used in C++. +

      + +

      +Compared to classes that do not use directors, the call routing in the +director methods does add some overhead. In particular, at least one +dynamic cast and one extra function call occurs per method call from +Perl. Relative to the speed of Perl execution this is probably +completely negligible. For worst case routing, a method call that +ultimately resolves in C++ may take one extra detour through Perl in +order to ensure that the method does not have an extended Perl +implementation. This could result in a noticeable overhead in some cases. +

      + +

      +Although directors make it natural to mix native C++ objects with Perl +objects (as director objects) via a common base class pointer, one +should be aware of the obvious fact that method calls to Perl objects +will be much slower than calls to C++ objects. This situation can be +optimized by selectively enabling director methods (using the %feature +directive) for only those methods that are likely to be extended in +Perl. +

      + +

      33.11.6 Typemaps

      + + +

      +Typemaps for input and output of most of the basic types from director +classes have been written. These are roughly the reverse of the usual +input and output typemaps used by the wrapper code. The typemap +operation names are 'directorin', 'directorout', and 'directorargout'. +The director code does not currently use any of the other kinds of typemaps. +It is not clear at this point which kinds are appropriate and +need to be supported. +

      + + diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 19ace7192..8c483b7a0 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -1,13 +1,13 @@ - - +SWIG and PHP + -

      32 SWIG and PHP

      +

      34 SWIG and PHP

      @@ -79,7 +80,7 @@ your extension into php directly, you will need the complete PHP source tree available.

      -

      32.1 Generating PHP Extensions

      +

      34.1 Generating PHP Extensions

      @@ -113,9 +114,7 @@ more detail in section 27.2.6.

      The usual (and recommended) way is to build the extension as a separate dynamically loaded module (which is supported by all modern operating -systems). You can then specify that this be loaded -automatically in php.ini or load it explicitly for any script which -needs it. +systems).

      @@ -126,7 +125,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.

      -

      32.1.1 Building a loadable extension

      +

      34.1.1 Building a loadable extension

      @@ -137,42 +136,59 @@ least work for Linux though):

      -	gcc `php-config --includes` -fpic -c example_wrap.c
      -	gcc -shared example_wrap.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
       
      -

      32.1.2 Using PHP Extensions

      +

      34.1.2 Using PHP Extensions

      -To test the extension from a PHP script, you need to load it first. You -can load it for every script by adding this line the [PHP] section of +To test the extension from a PHP script, you first need to tell PHP to +load it. To do this, add a line like this to the [PHP] section of php.ini:

      -	extension=/path/to/modulename.so
      +        extension=/path/to/modulename.so
       

      -Alternatively, you can load it explicitly only for scripts which need it -by adding this line: +If the module is in PHP's default extension directory, you can omit the path. +

      + +

      +For some SAPIs (for example, the CLI SAPI) you can instead use the +dl() function to load +an extension at run time, by adding a like like this to the start of each +PHP script which uses your extension:

      -	dl("/path/to/modulename.so");	// Load the module
      +        dl("/path/to/modulename.so"); // Load the module
       

      -to the start of each PHP file. SWIG also generates a php module, which -attempts to do the dl() call for you: +But note that this doesn't work when running PHP through a webserver in PHP5.3 +and later - you'll need to use extension in php.ini as +described above. +

      + +

      +The PHP module which SWIG generates will also attempt to do the dl() +call for you if the extension isn't already loaded:

      -	include("example.php");
      +        include("example.php");
       
      -

      32.2 Basic PHP interface

      +

      +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

      @@ -183,7 +199,7 @@ other symbols unless care is taken to %rename them. At present SWIG doesn't have support for the namespace feature added in PHP 5.3.

      -

      32.2.1 Constants

      +

      34.2.1 Constants

      @@ -220,9 +236,9 @@ echo "E = " . E . "\n";

      There's one peculiarity of how constants work in PHP which it is useful to note (this is not specific to SWIG though) - if you try to use an undeclared -constant, PHP will issue a warning and then expand the constant to a string -version of the constant's name. The warning will often be missed though as -if you're using PHP in a webserver, it will probably end up in error.log or +constant, PHP will emit a notice and then expand the constant to a string +version of the constant's name. Unfortunately it is easy to miss the notice +if you're using PHP in a webserver, as it will probably end up in error.log or similar.

      @@ -233,7 +249,7 @@ For example,
       %module example
       
      -#define EASY_TO_MISPELL	0
      +#define EASY_TO_MISPELL 0
       
      @@ -246,9 +262,9 @@ accessed incorrectly in PHP, include("example.php"); if(EASY_TO_MISPEL) { - .... + ... } else { - .... + ... } @@ -260,7 +276,7 @@ is treated as true by the if test, when the value of the intended constant would be treated as false!

      -

      32.2.2 Global Variables

      +

      34.2.2 Global Variables

      @@ -287,7 +303,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();
       
      @@ -309,7 +325,7 @@ undefined. At this time SWIG does not support custom accessor methods.

      -

      32.2.3 Functions

      +

      34.2.3 Functions

      @@ -332,7 +348,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

      @@ -362,7 +378,7 @@ print $s; # The value of $s was not changed. --> -

      32.2.4 Overloading

      +

      34.2.4 Overloading

      @@ -418,7 +434,7 @@ taking the integer argument.

      --> -

      32.2.5 Pointers and References

      +

      34.2.5 Pointers and References

      @@ -503,7 +519,20 @@ echo "The sum $in1 + $in2 = $result\n"; Because PHP has a native concept of reference, it may seem more natural to the PHP developer to use references to pass pointers. To enable this, one needs to include phppointers.i which defines the -named typemap REFERENCE. +named typemap REF. +

      + +

      +Prior to SWIG 3.0, the REF typemaps relied on PHP's call-time +pass-by-reference, which was deprecated in PHP 5.3 and removed in PHP 5.4. +So if you use these REF typemaps, you should ensure that SWIG≥3.0 is +used to generate wrappers from your interface file. +

      + +

      +In case you write your own typemaps, SWIG supports an attribute called +byref: if you set that, then SWIG will make sure that the generated +wrapper function will want the input parameter as a reference.

      @@ -526,7 +555,7 @@ include("example.php");
       $in1 = 3;
       $in2 = 5;
       $result = 0;
      -add(&$in1,&$in2,&$result);
      +add($in1,$in2,$result);
       
       echo "The sum $in1 + $in2 = $result\n";
       ?>
      @@ -550,7 +579,7 @@ PHP in a number of ways: by using unset on an existing
       variable, or assigning NULL to a variable.
       

      -

      32.2.6 Structures and C++ classes

      +

      34.2.6 Structures and C++ classes

      @@ -570,10 +599,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 +640,7 @@ Would be used in the following way from PHP5: Member variables and methods are accessed using the -> operator.

      -

      32.2.6.1 Using -noproxy

      +

      34.2.6.1 Using -noproxy

      @@ -637,7 +666,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj);

      -

      32.2.6.2 Constructors and Destructors

      +

      34.2.6.2 Constructors and Destructors

      @@ -678,7 +707,7 @@ the programmer can either reassign the variable or call unset($v)

      -

      32.2.6.3 Static Member Variables

      +

      34.2.6.3 Static Member Variables

      @@ -693,7 +722,7 @@ returns the current value of the class variable. For example %module example class Ko { - static int threats; + static int threats; }; @@ -705,7 +734,7 @@ would be accessed in PHP as,

       include("example.php");
       
      -echo "There has now been " . Ko::threats() . " threats\n";
      +echo "There have now been " . Ko::threats() . " threats\n";
       
       
      @@ -718,10 +747,10 @@ function, e.g. Ko::threats(10); -echo "There has now been " . Ko::threats() . " threats\n"; +echo "There have now been " . Ko::threats() . " threats\n"; -

      32.2.6.4 Static Member Functions

      +

      34.2.6.4 Static Member Functions

      @@ -743,7 +772,25 @@ Ko::threats(); -

      32.2.7 PHP Pragmas, Startup and Shutdown code

      +

      34.2.6.5 Specifying Implemented Interfaces

      + + +

      +PHP supports the concept of abstract interfaces which a class can implement. +Since SWIG 3.0.3, you can tell SWIG that a wrapped class (for example +MyIterator) implements the Iterator interface like +so: +

      + +
      +%typemap("phpinterfaces") MyIterator "Iterator";
      +
      + +

      +If there are multiple interfaces, just list them separated by commas. +

      + +

      34.2.7 PHP Pragmas, Startup and Shutdown code

      @@ -831,7 +878,7 @@ The %rinit and %rshutdown statements are very similar but inse into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.

      -

      32.3 Cross language polymorphism

      +

      34.3 Cross language polymorphism

      @@ -866,7 +913,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

      -

      32.3.1 Enabling directors

      +

      34.3.1 Enabling directors

      @@ -895,9 +942,6 @@ globally, to specific classes, and to specific methods, like this: // generate directors for all virtual methods in class Foo %feature("director") Foo; - -// generate a director for just Foo::bar() -%feature("director") Foo::bar; @@ -958,7 +1002,7 @@ class MyFoo extends Foo { -

      32.3.2 Director classes

      +

      34.3.2 Director classes

      @@ -1038,7 +1082,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

      -

      32.3.3 Ownership and object destruction

      +

      34.3.3 Ownership and object destruction

      @@ -1094,7 +1138,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

      -

      32.3.4 Exception unrolling

      +

      34.3.4 Exception unrolling

      @@ -1153,7 +1197,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

      -

      32.3.5 Overhead and code bloat

      +

      34.3.5 Overhead and code bloat

      @@ -1186,7 +1230,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.

      -

      32.3.6 Typemaps

      +

      34.3.6 Typemaps

      @@ -1200,7 +1244,7 @@ need to be supported.

      -

      32.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 8c1eb2d36..22ab4e2a2 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -1,12 +1,13 @@ - + SWIG and Pike + -

      33 SWIG and Pike

      +

      35 SWIG and Pike

        @@ -46,10 +47,10 @@ least, make sure you read the "SWIG Basics" chapter.

        -

        33.1 Preliminaries

        +

        35.1 Preliminaries

        -

        33.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
        -

        33.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.

        -

        33.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

      -

      33.2 Basic C/C++ Mapping

      +

      35.2 Basic C/C++ Mapping

      -

      33.2.1 Modules

      +

      35.2.1 Modules

      @@ -143,7 +144,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

      -

      33.2.2 Functions

      +

      35.2.2 Functions

      @@ -168,7 +169,7 @@ exactly as you'd expect it to: (1) Result: 24 -

      33.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 -

      33.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.

      -

      33.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.

      -

      33.2.6 Static Members

      +

      35.2.6 Static Members

      diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index 2d0aa093e..3b654a6d2 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -1,31 +1,42 @@ - + Preface + -

      1 Preface

      +

      1 Preface

      -

      1.1 Introduction

      +

      1.1 Introduction

      @@ -48,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

      @@ -57,13 +68,26 @@ In the late 1990's, the most stable version of SWIG was release over a period of 10 years starting from the year 2000. The final version in the 1.3.x series was 1.3.40, but in truth the 1.3.x series had been stable for many years. An official stable version was released along with the decision to make SWIG -license changes and this gave rise to version 2.0.0 in 2010. The license was clarified +license changes and this gave rise to version 2.0.0 in 2010. +

      + +

      1.3 SWIG License

      + + +

      +The LICENSE file shipped with SWIG in the top level directory contains the SWIG license. +For further insight into the license including the license of SWIG's output code, please visit +the SWIG legal page - http://www.swig.org/legal.html. +

      + +

      +The license was clarified in version 2.0.0 so that the code that SWIG generated could be distributed under license terms of the user's choice/requirements and at the same time the SWIG source was placed under the GNU General Public License version 3.

      -

      1.3 SWIG resources

      +

      1.4 SWIG resources

      @@ -93,16 +117,17 @@ SWIG along with information about beta releases and future work.

      -Subversion access to the latest version of SWIG is also available. More information +Git and Subversion access to the latest version of SWIG is also available. More information about this can be obtained at:

      -

      1.4 Prerequisites

      + +

      1.5 Prerequisites

      @@ -127,7 +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.5 Organization of this manual

      +

      1.6 Organization of this manual

      @@ -139,7 +164,7 @@ can probably skip to that chapter and find almost everything you need to know.

      -

      1.6 How to avoid reading the manual

      +

      1.7 How to avoid reading the manual

      @@ -151,7 +176,7 @@ The SWIG distribution also comes with a large directory of examples that illustrate different topics.

      -

      1.7 Backwards compatibility

      +

      1.8 Backwards compatibility

      @@ -162,8 +187,8 @@ this isn't always possible as the primary goal over time is to make SWIG better---a process that would simply be impossible if the developers are constantly bogged down with backwards compatibility issues. -Potential incompatibilities are clearly marked in the detailed release notes -(CHANGES files). +Potential incompatibilities are clearly marked in the detailed +release notes.

      @@ -187,7 +212,16 @@ Note: The version symbol is not defined in the generated SWIG wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.

      -

      1.8 Credits

      +

      1.9 Release notes

      + + +

      +The CHANGES.current, CHANGES and RELEASENOTES files shipped with SWIG in the top level directory +contain, respectively, detailed release notes for the current version, +detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards. +

      + +

      1.10 Credits

      @@ -200,7 +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.9 Bug reports

      +

      1.11 Bug reports

      @@ -215,5 +249,211 @@ used, and any important pieces of the SWIG generated wrapper code. We can only fix bugs if we know about them.

      +

      1.12 Installation

      + + +

      1.12.1 Windows installation

      + + +

      +Please see the dedicated Windows chapter for instructions on installing +SWIG on Windows and running the examples. The Windows distribution is +called swigwin and includes a prebuilt SWIG executable, swig.exe, included in +the top level directory. Otherwise it is exactly the same as +the main SWIG distribution. There is no need to download anything else. +

      + +

      1.12.2 Unix installation

      + + +

      +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. +

      + +

      +PCRE +needs to be installed on your system to build SWIG, in particular +pcre-config must be available. If you have PCRE headers and libraries but not +pcre-config itself or, alternatively, wish to override the compiler or linker +flags returned by pcre-config, you may set PCRE_LIBS and PCRE_CFLAGS variables +to be used instead. And if you don't have PCRE at all, the configure script +will provide instructions for obtaining it. +

      + +

      +To build and install SWIG, simply type the following: +

      + +
      +$ ./configure
      +$ make
      +$ make install
      +
      + +

      +By default SWIG installs itself in /usr/local. If you need to install SWIG in +a different location or in your home directory, use the --prefix option +to ./configure. For example: +

      + +
      +$ ./configure --prefix=/home/yourname/projects
      +$ make
      +$ make install
      +
      + +

      +Note: the directory given to --prefix must be an absolute pathname. Do not use +the ~ shell-escape to refer to your home directory. SWIG won't work properly +if you do this. +

      + +

      +The INSTALL file shipped in the top level directory details more about using configure. Also try +

      + +
      +$ ./configure --help.
      +
      + +

      +The configure script will attempt to locate various packages on your machine +including Tcl, Perl5, Python and all the other target languages that SWIG +supports. Don't panic if you get 'not found' messages -- SWIG does not need these +packages to compile or run. The configure script is actually looking for +these packages so that you can try out the SWIG examples contained +in the 'Examples' directory without having to hack Makefiles. +Note that the --without-xxx options, where xxx is a target language, have +minimal effect. All they do is reduce the amount of testing done with +'make check'. The SWIG executable and library files installed cannot currently +be configured with a subset of target languages. +

      + +

      +SWIG used to include a set of runtime libraries for some languages for working +with multiple modules. These are no longer built during the installation stage. +However, users can build them just like any wrapper module as described in +the Modules chapter. +The CHANGES file shipped with SWIG in the top level directory +also lists some examples which build the runtime library. +

      + +

      +Note: +

      + +
        +
      • +If you checked the code out via Git, you will have to run ./autogen.sh +before ./configure. In addition, a full build of SWIG requires +a number of packages to be installed. Full instructions at +SWIG bleeding edge. +
      • +
      + +

      1.12.3 Macintosh OS X installation

      + + +

      +SWIG is known to work on various flavors of OS X. Follow the Unix installation +instructions above. However, as of this writing, there is still great deal of +inconsistency with how shared libaries are handled by various scripting languages +on OS X. +

      + +

      +Users of OS X should be aware that Darwin handles shared libraries and linking in +a radically different way than most Unix systems. In order to test SWIG and run +the examples, SWIG configures itself to use flat namespaces and to allow undefined +symbols (-flat_namespace -undefined suppress). This mostly closely follows the Unix +model and makes it more likely that the SWIG examples will work with whatever +installation of software you might have. However, this is generally not the recommended +technique for building larger extension modules. Instead, you should utilize +Darwin's two-level namespaces. Some details about this can be found here + +Understanding Two-Level Namespaces. + +

      + +

      +Needless to say, you might have to experiment a bit to get things working at first. +

      + +

      1.12.4 Testing

      + + +

      +If you want to test SWIG after building it, a check can be performed on Unix operating systems. +Type the following: +

      + +
      +    $ make -k check
      +
      + +

      +This step can be performed either before or after installation. +The check requires at least one of the target languages to be +installed. If it fails, it may mean that you have an uninstalled +language module or that the file 'Examples/Makefile' has been +incorrectly configured. It may also fail due to compiler issues such +as a broken C++ compiler. Even if the check fails, there is a +pretty good chance SWIG still works correctly --- you will just have to +mess around with one of the examples and some makefiles to get it to work. +Some tests may also fail due to missing dependency packages, eg PCRE +or Boost, but this will require careful analysis of the configure output +done during configuration. +

      + +

      +The test suite executed by the check is designed to stress-test +many parts of the implementation including obscure corner cases. If some +of these tests fail or generate warning messages, there is no reason for +alarm --- the test may be related to some new SWIG feature or a difficult bug +that we're trying to resolve. Chances are that SWIG will work just fine +for you. Note that if you have more than one CPU/core, then you can use +parallel make to speed up the check as it does take quite some time to run, +for example: +

      + +
      +    $ make -j2 -k check
      +
      + +

      +Also, SWIG's support for C++ is sufficiently advanced that certain +tests may fail on older C++ compilers (for instance if your compiler +does not support member templates). These errors are harmless if you +don't intend to use these features in your own programs. +

      + +

      +Note: The test-suite currently contains over 500 tests. If you +have many different target languages installed and a slow machine, it +might take more than an hour to run the test-suite. +

      + +

      1.12.5 Examples

      + + +

      +The Examples directory contains a variety of examples of using SWIG +and it has some browsable documentation. Simply point your browser to +the file "Example/index.html". +

      + +

      +The Examples directory also includes Visual C++ project 6 (.dsp) files for +building some of the examples on Windows. Later versions of Visual Studio +will convert these old style project files into a current solution file. +

      + diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index 8fcbe9206..2538f8f18 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -1,12 +1,13 @@ - +SWIG Preprocessor + -

      7 Preprocessing

      +

      8 Preprocessing

        @@ -37,7 +38,7 @@ However, a number of modifications and enhancements have been made. This chapter describes some of these modifications.

        -

        7.1 File inclusion

        +

        8.1 File inclusion

        @@ -63,7 +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. -

        7.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. -

        7.3 Conditional Compilation

        +

        8.3 Conditional Compilation

        @@ -115,9 +116,12 @@ SWIGCLISP Defined when using CLISP SWIGCSHARP Defined when using C# SWIGGUILE Defined when using Guile SWIGJAVA Defined when using Java +SWIGJAVASCRIPT Defined when using Javascript +SWIG_JAVASCRIPT_JSC Defined when using Javascript for JavascriptCore +SWIG_JAVASCRIPT_V8 Defined when using Javascript for v8 or node.js SWIGLUA Defined when using Lua SWIGMODULA3 Defined when using Modula-3 -SWIGMZSCHEME Defined when using Mzscheme +SWIGMZSCHEME Defined when using Mzscheme SWIGOCAML Defined when using Ocaml SWIGOCTAVE Defined when using Octave SWIGPERL Defined when using Perl @@ -126,6 +130,7 @@ SWIGPIKE Defined when using Pike SWIGPYTHON Defined when using Python SWIGR Defined when using R SWIGRUBY Defined when using Ruby +SWIGSCILAB Defined when using Scilab SWIGSEXP Defined when using S-expressions SWIGTCL Defined when using Tcl SWIGXML Defined when using XML @@ -152,7 +157,7 @@ SWIG (except for the symbol `SWIG' which is only defined within the SWIG compiler).

        -

        7.4 Macro Expansion

        +

        8.4 Macro Expansion

        @@ -207,7 +212,7 @@ like #x. This is a non-standard SWIG extension.

      -

      7.5 SWIG Macros

      +

      8.5 SWIG Macros

      @@ -253,7 +258,7 @@ many of SWIG's advanced features and libraries are built using this mechanism (s support).

      -

      7.6 C99 and GNU Extensions

      +

      8.6 C99 and GNU Extensions

      @@ -309,14 +314,14 @@ interface building. However, they are used internally to implement a number of SWIG directives and are provided to make SWIG more compatible with C99 code.

      -

      7.7 Preprocessing and delimiters

      +

      8.7 Preprocessing and delimiters

      The preprocessor handles { }, " " and %{ %} delimiters differently.

      -

      7.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      +

      8.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      @@ -341,7 +346,7 @@ the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).

      -

      7.7.2 Preprocessing and { ... } delimiters

      +

      8.7.2 Preprocessing and { ... } delimiters

      @@ -383,7 +388,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.

      -

      7.8 Preprocessor and Typemaps

      +

      8.8 Preprocessor and Typemaps

      @@ -454,7 +459,7 @@ would generate

      -

      7.9 Viewing preprocessor output

      +

      8.9 Viewing preprocessor output

      @@ -464,7 +469,7 @@ Instead the results after the preprocessor has run are displayed. This might be useful as an aid to debugging and viewing the results of macro expansions.

      -

      7.10 The #error and #warning directives

      +

      8.10 The #error and #warning directives

      diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index a9a9bc44e..099d406bf 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -1,12 +1,13 @@ - + SWIG and Python + -

      34 SWIG and Python

      +

      36 SWIG and Python

      @@ -135,7 +149,7 @@ very least, make sure you read the "SWIG Basics" chapter.

      -

      34.1 Overview

      +

      36.1 Overview

      @@ -162,10 +176,10 @@ described followed by a discussion of low-level implementation details.

      -

      34.2 Preliminaries

      +

      36.2 Preliminaries

      -

      34.2.1 Running SWIG

      +

      36.2.1 Running SWIG

      @@ -187,7 +201,7 @@ int fact(int n);

      -The #define SWIG_FILE_WITH_INIT line inserts a macro that specifies that the +The #define SWIG_FILE_WITH_INIT line inserts a macro that specifies that the resulting C file should be built as a python extension, inserting the module init code. This .i file wraps the following simple C file:

      @@ -263,13 +277,13 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files.

      -

      34.2.2 Using distutils

      +

      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).

      @@ -355,7 +369,7 @@ This same approach works on all platforms if the appropriate compiler is install can even build extensions to the standard Windows Python using MingGW)

      -

      34.2.3 Hand compiling a dynamic module

      +

      36.2.3 Hand compiling a dynamic module

      @@ -388,7 +402,7 @@ of the module prefixed by an underscore. If the name of your module is "_example.so" or "_examplemodule.so". The name of the module is specified using the %module directive or the - -module command line option. +-module command line option.

      @@ -403,7 +417,7 @@ module actually consists of two files; socket.py and

      -

      34.2.4 Static linking

      +

      36.2.4 Static linking

      @@ -448,14 +462,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 @@ -476,13 +490,13 @@ 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).

      -

      34.2.5 Using your module

      +

      36.2.5 Using your module

      @@ -639,7 +653,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      34.2.6 Compilation of C++ extensions

      +

      36.2.6 Compilation of C++ extensions

      @@ -731,7 +745,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

      -

      34.2.7 Compiling for 64-bit platforms

      +

      36.2.7 Compiling for 64-bit platforms

      @@ -768,7 +782,7 @@ and -m64 allow you to choose the desired binary format for your python extension.

      -

      34.2.8 Building Python Extensions under Windows

      +

      36.2.8 Building Python Extensions under Windows

      @@ -776,8 +790,8 @@ Building a SWIG extension to Python under Windows is roughly similar to the process used with Unix. Using the distutils, it is essentially identical. If you have the same version of the MS compiler that Python was built with (the python2.4 and python2.5 distributed by python.org -are built with Visual Studio 2003), the standard python setup.py -build should just work. +are built with Visual Studio 2003), the standard python setup.py +build should just work.

      @@ -795,7 +809,9 @@ If you need to build it on your own, the following notes are provided: You will need to create a DLL that can be loaded into the interpreter. This section briefly describes the use of SWIG with Microsoft Visual C++. As a starting point, many of SWIG's examples include project -files. You might want to take a quick look at these in addition to +files (.dsp files) for Visual C++ 6. These can be opened by more +recent versions of Visual Studio. +You might want to take a quick look at these examples in addition to reading this section.

      @@ -868,6 +884,24 @@ set of Win32 debug or thread libraries. You will have to fiddle around with the build options of project to try and track this down.

      +

      +A 'Debug' build of the wrappers requires a debug build of the Python interpreter. +This normally requires building the Python interpreter from source, which is not a +job for the feint-hearted. Alternatively you can use the 'Release' build of the +Python interpreter with a 'Debug' build of your wrappers by defining the SWIG_PYTHON_INTERPRETER_NO_DEBUG +symbol under the preprocessor options. Or you can ensure this macro is defined at the beginning +of the wrapper code using the following in your interface file, where _MSC_VER ensures it is +only used by the Visual Studio compiler: +

      + +
      +%begin %{
      +#ifdef _MSC_VER
      +#define SWIG_PYTHON_INTERPRETER_NO_DEBUG
      +#endif
      +%}
      +
      +

      Some users have reported success in building extension modules using Cygwin and other compilers. However, the problem of building usable DLLs with these @@ -877,7 +911,7 @@ SWIG Wiki.

      -

      34.3 A tour of basic C/C++ wrapping

      +

      36.3 A tour of basic C/C++ wrapping

      @@ -886,7 +920,7 @@ to your C/C++ code. Functions are wrapped as functions, classes are wrapped as This section briefly covers the essential aspects of this wrapping.

      -

      34.3.1 Modules

      +

      36.3.1 Modules

      @@ -899,7 +933,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.

      -

      34.3.2 Functions

      +

      36.3.2 Functions

      @@ -923,7 +957,7 @@ like you think it does: >>> -

      34.3.3 Global variables

      +

      36.3.3 Global variables

      @@ -1061,7 +1095,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

      -

      34.3.4 Constants and enums

      +

      36.3.4 Constants and enums

      @@ -1101,7 +1135,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

      -

      34.3.5 Pointers

      +

      36.3.5 Pointers

      @@ -1127,7 +1161,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)
       
      @@ -1242,7 +1276,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

      -

      34.3.6 Structures

      +

      36.3.6 Structures

      @@ -1252,7 +1286,7 @@ a very natural interface. For example,

       struct Vector {
      -	double x,y,z;
      +  double x,y,z;
       };
       
       
      @@ -1431,7 +1465,7 @@ everything works just like you would expect. For example:
      -

      34.3.7 C++ classes

      +

      36.3.7 C++ classes

      @@ -1520,7 +1554,7 @@ they are accessed through cvar like this: -

      34.3.8 C++ inheritance

      +

      36.3.8 C++ inheritance

      @@ -1575,7 +1609,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

      -

      34.3.9 Pointers, references, values, and arrays

      +

      36.3.9 Pointers, references, values, and arrays

      @@ -1636,7 +1670,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.

      -

      34.3.10 C++ overloaded functions

      +

      36.3.10 C++ overloaded functions

      @@ -1759,7 +1793,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      34.3.11 C++ operators

      +

      36.3.11 C++ operators

      @@ -1848,7 +1882,7 @@ Also, be aware that certain operators don't map cleanly to Python. For instance overloaded assignment operators don't map to Python semantics and will be ignored.

      -

      34.3.12 C++ namespaces

      +

      36.3.12 C++ namespaces

      @@ -1915,7 +1949,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

      -

      34.3.13 C++ templates

      +

      36.3.13 C++ templates

      @@ -1969,7 +2003,21 @@ Some more complicated examples will appear later.

      -

      34.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

      @@ -2053,7 +2101,7 @@ simply use the __deref__() method. For example: -

      34.3.15 C++ reference counted objects

      +

      36.3.15 C++ reference counted objects

      @@ -2062,7 +2110,7 @@ Python examples of memory management using referencing counting.

      -

      34.4 Further details on the Python class interface

      +

      36.4 Further details on the Python class interface

      @@ -2085,7 +2133,7 @@ the -builtin option are in the Built-in section.

      -

      34.4.1 Proxy classes

      +

      36.4.1 Proxy classes

      @@ -2142,15 +2190,15 @@ for Python 2.2): import _example class Foo(object): - def __init__(self): - self.this = _example.new_Foo() - self.thisown = 1 - def __del__(self): - if self.thisown: - _example.delete_Foo(self.this) - def spam(self,arg1): - return _example.Foo_spam(self.this,arg1) - x = property(_example.Foo_x_get, _example.Foo_x_set) + def __init__(self): + self.this = _example.new_Foo() + self.thisown = 1 + def __del__(self): + if self.thisown: + _example.delete_Foo(self.this) + def spam(self,arg1): + return _example.Foo_spam(self.this,arg1) + x = property(_example.Foo_x_get, _example.Foo_x_set) @@ -2174,7 +2222,7 @@ you can attach new Python methods to the class and you can even inherit from it by Python built-in types until Python 2.2).

      -

      34.4.2 Built-in Types

      +

      36.4.2 Built-in Types

      @@ -2192,9 +2240,9 @@ like in a proxy class:

       class Foo(object):
      -     def __init__(self):
      -         self.this = _example.new_Foo()
      -         self.thisown = 1
      +    def __init__(self):
      +        self.this = _example.new_Foo()
      +        self.thisown = 1
       
      @@ -2218,7 +2266,7 @@ please refer to the python documentation:

      http://docs.python.org/extending/newtypes.html

      -

      34.4.2.1 Limitations

      +

      36.4.2.1 Limitations

      Use of the -builtin option implies a couple of limitations: @@ -2286,11 +2334,11 @@ private:

      -class MyPyException (Exception) :
      -    def __init__(self, msg, *args) :
      +class MyPyException(Exception):
      +    def __init__(self, msg, *args):
               Exception.__init__(self, *args)
               self.myexc = MyException(msg)
      -    def what (self) :
      +    def what(self):
               return self.myexc.what()
       
      @@ -2345,7 +2393,7 @@ doesn't know how to add an instance of MyString to itself.
    • If you have multiple SWIG modules that share type information (more info), -the -builtin option requiress a bit of extra discipline to ensure that base classes are initialized before derived classes. Specifically:

      +the -builtin option requires a bit of extra discipline to ensure that base classes are initialized before derived classes. Specifically:

      • There must be an unambiguous dependency graph for the modules.

      • Module dependencies must be explicitly stated with %import statements in the SWIG interface file.

        @@ -2386,7 +2434,7 @@ assert(issubclass(B.Derived, A.Base))
      -

      34.4.2.2 Operator overloads -- use them!

      +

      36.4.2.2 Operator overloads -- use them!

      The entire justification for the -builtin option is improved @@ -2487,7 +2535,7 @@ structs.

      -

      34.4.3 Memory management

      +

      36.4.3 Memory management

      NOTE: Although this section refers to proxy objects, everything here also applies @@ -2682,7 +2730,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

      -

      34.4.4 Python 2.2 and classic classes

      +

      36.4.4 Python 2.2 and classic classes

      @@ -2692,7 +2740,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.

      @@ -2707,7 +2755,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.

      @@ -2719,7 +2767,7 @@ class itself. In Python-2.1 and earlier, they have to be accessed as a global function or through an instance (see the earlier section).

      -

      34.5 Cross language polymorphism

      +

      36.5 Cross language polymorphism

      @@ -2753,7 +2801,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      34.5.1 Enabling directors

      +

      36.5.1 Enabling directors

      @@ -2782,9 +2830,6 @@ globally, to specific classes, and to specific methods, like this: // generate directors for all virtual methods in class Foo %feature("director") Foo; - -// generate a director for just Foo::bar() -%feature("director") Foo::bar; @@ -2817,6 +2862,7 @@ the methods one() and two() (but not three()): class Foo { public: Foo(int foo); + virtual ~Foo(); virtual void one(); virtual void two(); }; @@ -2837,16 +2883,17 @@ then at the python side you can define import mymodule class MyFoo(mymodule.Foo): - def __init__(self, foo): - mymodule.Foo(self, foo) + def __init__(self, foo): + mymodule.Foo.__init__(self, foo) +# super().__init__(foo) # Alternative construction for Python3 - def one(self): - print "one from python" + def one(self): + print "one from python" -

      34.5.2 Director classes

      +

      36.5.2 Director classes

      @@ -2928,7 +2975,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

      -

      34.5.3 Ownership and object destruction

      +

      36.5.3 Ownership and object destruction

      @@ -2995,7 +3042,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

      -

      34.5.4 Exception unrolling

      +

      36.5.4 Exception unrolling

      @@ -3054,7 +3101,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

      -

      34.5.5 Overhead and code bloat

      +

      36.5.5 Overhead and code bloat

      @@ -3088,7 +3135,7 @@ directive) for only those methods that are likely to be extended in Python.

      -

      34.5.6 Typemaps

      +

      36.5.6 Typemaps

      @@ -3102,7 +3149,7 @@ need to be supported.

      -

      34.5.7 Miscellaneous

      +

      36.5.7 Miscellaneous

      @@ -3149,7 +3196,7 @@ methods that return const references.

      -

      34.6 Common customization features

      +

      36.6 Common customization features

      @@ -3162,7 +3209,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

      -

      34.6.1 C/C++ helper functions

      +

      36.6.1 C/C++ helper functions

      @@ -3243,7 +3290,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.

      -

      34.6.2 Adding additional Python code

      +

      36.6.2 Adding additional Python code

      @@ -3297,6 +3344,77 @@ what can be done without having to rely on any of the more advanced customization features.

      +

      +There is also %pythonbegin which is another directive very similar to %pythoncode, +but generates the given Python code at the beginning of the .py file. +This directive works in the same way as %pythoncode, except the code is copied +just after the SWIG banner (comment) at the top of the file, before any real code. +This provides an opportunity to add your own description in a comment near the top of the file as well +as Python imports that have to appear at the top of the file, such as "from __future__ import" +statements. +

      + +

      +The following shows example usage for Python 2.6 to use print as it can in Python 3, that is, as a function instead of a statement: +

      + +
      +
      +%pythonbegin %{
      +# This module provides wrappers to the Whizz Bang library
      +%}
      +
      +%pythonbegin %{
      +from __future__ import print_function
      +print("Loading", "Whizz", "Bang", sep=' ... ')
      +%}
      +
      +
      + +

      +which can be seen when viewing the first few lines of the generated .py file: +

      + +
      +
      +# This file was automatically generated by SWIG (http://www.swig.org).
      +# Version 2.0.11
      +#
      +# Do not make changes to this file unless you know what you are doing--modify
      +# the SWIG interface file instead.
      +
      +# This module provides wrappers to the Whizz Bang library
      +
      +from __future__ import print_function
      +print("Loading", "Whizz", "Bang", sep=' ... ')
      +
      +
      +
      + +

      When using %pythoncode and %pythonbegin you generally +want to make sure that the block is delimited by %{ and %}. +If you delimit it with { and } then any lines with a +leading # will be handled by SWIG as preprocessor directives, when +you probably meant them as Python comments. Prior to SWIG 3.0.3, invalid +preprocessor directives were silently ignored, so generally using the wrong +delimiters resulted in such comments not appearing in the generated output +(though a comment starting with a valid preprocessor directive could cause +problems, for example: # error handling). SWIG 3.0.3 and later report +an error for invalid preprocessor directives, so you may have to update +existing interface files to delimit blocks of Python code correctly.

      + +

      As an alternative to providing a block containing Python code, you can +include python code from a file. The code is inserted exactly as in the +file, so this avoids any issues with the SWIG preprocessor. It's a good +approach if you have a non-trivial chunk of Python code to insert. To +use this feature you specify a filename in double quotes, for example:

      + +
      +
      +%pythoncode "somecode.py"
      +
      +
      +

      Sometimes you may want to replace or modify the wrapper function that SWIG creates in the proxy .py file. The Python module in SWIG provides some features that enable you to do this. First, to @@ -3319,7 +3437,7 @@ def bar(*args): class Foo { public: int bar(int x); -} +}; @@ -3356,7 +3474,7 @@ proxy, just before the return statement. class Foo { public: int bar(int x); -} +}; @@ -3385,14 +3503,46 @@ SWIG version 1.3.28 you can use the directive forms class Foo { public: int bar(int x); -} +}; +

      +Note that when the underlying C++ method is overloaded, there is only one proxy Python method +for multiple C++ methods. In this case, only one of parsed methods is examined +for the feature. You are better off specifying the feature without the argument list to ensure it will get used, +as it will then get attached to all the overloaded C++ methods. For example: +

      + +
      +
      +%module example
      +
      +// Add python code to bar()
      +
      +%pythonprepend Foo::bar %{
      +   #do something before C++ call
      +%}
      +
      +%pythonappend Foo::bar %{
      +   #do something after C++ call
      +%}
       
       
      +class Foo {
      +public:
      +    int bar(int x);
      +    int bar();
      +};
      +
      +
      -

      34.6.3 Class extension with %extend

      +

      +The same applies for overloaded constructors. +

      + + +

      36.6.3 Class extension with %extend

      @@ -3481,7 +3631,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.

      -

      34.6.4 Exception handling with %exception

      +

      36.6.4 Exception handling with %exception

      @@ -3607,7 +3757,7 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.

      -

      34.7 Tips and techniques

      +

      36.7 Tips and techniques

      @@ -3617,7 +3767,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

      -

      34.7.1 Input and output parameters

      +

      36.7.1 Input and output parameters

      @@ -3830,7 +3980,7 @@ void foo(Bar *OUTPUT); may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

      -

      34.7.2 Simple pointers

      +

      36.7.2 Simple pointers

      @@ -3899,7 +4049,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.

      -

      34.7.3 Unbounded C Arrays

      +

      36.7.3 Unbounded C Arrays

      @@ -3961,7 +4111,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.

      -

      34.7.4 String handling

      +

      36.7.4 String handling

      @@ -4030,7 +4180,107 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.

      -

      34.8 Typemaps

      + +

      36.7.5 Default arguments

      + + +

      +C++ default argument code generation is documented in the main +Default arguments section. +There is also an optional Python specific feature that can be used called the python:cdefaultargs +feature flag. +By default, SWIG attempts to convert C++ default argument values +into Python values and generates code into the Python layer containing these values. +For example: +

      + +
      +
      +struct CDA {
      +  int fff(int a = 1, bool b = false);
      +};
      +
      +
      + +

      +From Python this can be called as follows: +

      + +
      +
      +>>> CDA().fff()        # C++ layer receives a=1 and b=false
      +>>> CDA().fff(2)       # C++ layer receives a=2 and b=false
      +>>> CDA().fff(3, True) # C++ layer receives a=3 and b=true
      +
      +
      + +

      +The default code generation in the Python layer is: +

      + +
      +
      +class CDA(object):
      +    ...
      +    def fff(self, a=1, b=False):
      +        return _default_args.CDA_fff(self, a, b)
      +
      +
      + +

      +Adding the feature: +

      + +
      +
      +%feature("python:cdefaultargs") CDA::fff;
      +struct CDA {
      +  int fff(int a = 1, bool b = false);
      +
      +
      + +

      +results in identical behaviour when called from Python, however, it results in different code generation: +

      + +
      +
      +class CDA(object):
      +    ...
      +    def fff(self, *args):
      +        return _default_args.CDA_fff(self, *args)
      +
      +
      + +

      +The default arguments are obtained in the C++ wrapper layer instead of the Python layer. +Some code generation modes are quite different, eg -builtin and -fastproxy, +and are unaffected by python:cdefaultargs as the default values are always obtained from the C++ layer. +

      + +

      +Note that not all default arguments can be converted into a Python equivalent. +When SWIG does not convert them, it will generate code to obtain them from the C++ layer as if +python:cdefaultargs was specified. +This will happen if just one argument cannot be converted into a Python equivalent. +This occurs typically when the argument is not fully numeric, such as int(1): +

      + +
      +
      +struct CDA {
      +  int fff(int a = int(1), bool b = false);
      +};
      +
      +
      + +

      +Compatibility Note: SWIG-3.0.6 introduced the python:cdefaultargs feature. +Versions of SWIG prior to this varied in their ability to convert C++ default values into +equivalent Python default argument values. +

      + +

      36.8 Typemaps

      @@ -4047,7 +4297,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Python interface or if you want to elevate your guru status.

      -

      34.8.1 What is a typemap?

      +

      36.8.1 What is a typemap?

      @@ -4060,8 +4310,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); @@ -4098,11 +4348,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."); + return NULL; + } } %inline %{ extern int fact(int nonnegative); @@ -4124,8 +4374,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;
      @@ -4163,7 +4413,7 @@ parameter is omitted):
       
      -

      34.8.2 Python typemaps

      +

      36.8.2 Python typemaps

      @@ -4204,7 +4454,7 @@ a look at the SWIG library version 1.3.20 or so.

      -

      34.8.3 Typemap variables

      +

      36.8.3 Typemap variables

      @@ -4275,7 +4525,7 @@ properly assigned. The Python name of the wrapper function being created. -

      34.8.4 Useful Python Functions

      +

      36.8.4 Useful Python Functions

      @@ -4403,7 +4653,7 @@ write me -

      34.9 Typemap Examples

      +

      36.9 Typemap Examples

      @@ -4412,7 +4662,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

      -

      34.9.1 Converting Python list to a char **

      +

      36.9.1 Converting Python list to a char **

      @@ -4435,11 +4685,11 @@ object to be used as a char ** object. for (i = 0; i < size; i++) { PyObject *o = PyList_GetItem($input,i); if (PyString_Check(o)) - $1[i] = PyString_AsString(PyList_GetItem($input,i)); + $1[i] = PyString_AsString(PyList_GetItem($input,i)); else { - PyErr_SetString(PyExc_TypeError,"list must contain strings"); - free($1); - return NULL; + PyErr_SetString(PyExc_TypeError,"list must contain strings"); + free($1); + return NULL; } } $1[i] = 0; @@ -4475,7 +4725,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
      @@ -4492,7 +4742,7 @@ memory allocation is used to allocate memory for the array, the
       the C function. 
       

      -

      34.9.2 Expanding a Python object into multiple arguments

      +

      36.9.2 Expanding a Python object into multiple arguments

      @@ -4513,7 +4763,7 @@ allows the function to be used from Python as follows:

      ->>> foo(4, ["foo","bar","spam","1"])
      +>>> foo(4, ["foo", "bar", "spam", "1"])
       
      @@ -4534,11 +4784,11 @@ previous example: for (i = 0; i < $1; i++) { PyObject *o = PyList_GetItem($input,i); if (PyString_Check(o)) - $2[i] = PyString_AsString(PyList_GetItem($input,i)); + $2[i] = PyString_AsString(PyList_GetItem($input,i)); else { - PyErr_SetString(PyExc_TypeError,"list must contain strings"); - free($2); - return NULL; + PyErr_SetString(PyExc_TypeError,"list must contain strings"); + free($2); + return NULL; } } $2[i] = 0; @@ -4567,11 +4817,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"])
       
      -

      34.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

      @@ -4582,12 +4872,11 @@ 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;
      +}
       

      @@ -4660,7 +4949,7 @@ function can now be used as follows: >>>

      -

      34.9.4 Mapping Python tuples into small arrays

      +

      36.9.4 Mapping Python tuples into small arrays

      @@ -4709,7 +4998,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.

      -

      34.9.5 Mapping sequences to C arrays

      +

      36.9.5 Mapping sequences to C arrays

      @@ -4798,7 +5087,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -

      34.9.6 Pointer handling

      +

      36.9.6 Pointer handling

      @@ -4895,7 +5184,7 @@ class object (if applicable). -

      34.10 Docstring Features

      +

      36.10 Docstring Features

      @@ -4923,7 +5212,7 @@ of your users much simpler.

      -

      34.10.1 Module docstring

      +

      36.10.1 Module docstring

      @@ -4957,7 +5246,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." -

      34.10.2 %feature("autodoc")

      +

      36.10.2 %feature("autodoc")

      @@ -4985,7 +5274,7 @@ four levels for autodoc controlled by the value given to the feature, %feature("autodoc", "level"). The four values for level are covered in the following sub-sections. -

      34.10.2.1 %feature("autodoc", "0")

      +

      36.10.2.1 %feature("autodoc", "0")

      @@ -5014,7 +5303,7 @@ def function_name(*args, **kwargs): -

      34.10.2.2 %feature("autodoc", "1")

      +

      36.10.2.2 %feature("autodoc", "1")

      @@ -5039,13 +5328,13 @@ def function_name(*args, **kwargs): -

      34.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:

      @@ -5054,11 +5343,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 * """ ... @@ -5089,17 +5379,18 @@ 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 * """
      -

      34.10.2.4 %feature("autodoc", "3")

      +

      36.10.2.4 %feature("autodoc", "3")

      @@ -5112,11 +5403,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 * """ ... @@ -5124,7 +5416,7 @@ def function_name(*args, **kwargs): -

      34.10.2.5 %feature("autodoc", "docstring")

      +

      36.10.2.5 %feature("autodoc", "docstring")

      @@ -5143,7 +5435,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

      34.10.3 %feature("docstring")

      +

      36.10.3 %feature("docstring")

      @@ -5175,13 +5467,70 @@ with more than one line. -

      34.11 Python Packages

      +

      36.11 Python Packages

      + + +

      Python has concepts of modules and packages. Modules are separate units of +code and may be grouped together to form a package. Packages may be nested, +that is they may contain subpackages. This leads to tree-like hierarchy, with +packages as intermediate nodes and modules as leaf nodes.

      + +

      The hierarchy of Python packages/modules follows the hierarchy of +*.py files found in a source tree (or, more generally, in the Python path). +Normally, the developer creates new module by placing a *.py file +somewhere under Python path; the module is then named after that *.py +file. A package is created by placing an __init__.py file within a +directory; the package is then named after that directory. For example, the +following source tree:

      + +
      +
      +mod1.py
      +pkg1/__init__.py
      +pkg1/mod2.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/mod3.py
      +
      +
      + +

      +defines the following Python packages and modules: +

      + +
      +
      +pkg1            # package
      +pkg1.pkg2       # package
      +mod1            # module
      +pkg1.mod2       # module
      +pkg1.pkg2.mod3  # module
      +
      +
      + +

      +The purpose of an __init__.py file is two-fold. First, the existence of +__init__.py in a directory informs the Python interpreter that this +directory contains a Python package. Second, the code in __init__.py is +loaded/executed automatically when the package is initialized (when it or its +submodule/subpackage gets import'ed). By default, SWIG generates +proxy Python code – one *.py file for each *.i +interface. The __init__.py files, however, are not generated by SWIG. +They should be created by other means. Both files (module *.py and +__init__.py) should be installed in appropriate destination +directories in order to obtain a desirable package/module hierarchy. +

      + +

      The way Python defines its modules and packages impacts SWIG users. Some +users may need to use special features such as the package option in the +%module directive or import related command line options. These are +explained in the following sections.

      + +

      36.11.1 Setting the Python package

      -Using the package option of the %module directive -allows you to specify what Python package that the module will be -living in when installed. +Using the package option in the %module directive allows you +to specify a Python package that the module will be in when installed.

      @@ -5194,15 +5543,330 @@ living in when installed. This is useful when the .i file is %imported by another .i file. By default SWIG will assume that the importer is able to find the importee with just the module name, but -if they live in separate Python packages then that won't work. +if they live in separate Python packages then this won't work. However if the importee specifies what its package is with the %module option then the Python code generated for the importer will use that package name when importing the other module -and also in base class declarations, etc. if the package name is -different than its own. +and in base class declarations, etc..

      -

      34.12 Python 3 Support

      +

      SWIG assumes that the package option provided to %module +together with the module name (that is, wx.xrc in the above +example) forms a fully qualified (absolute) name of a module (in Python terms). +This is important especially for Python 3, where absolute imports are used by +default. It's up to you to place the generated module files (.py, +.so) in appropriate subdirectories. For example, if you have an +interface file foo.i with: +

      + +
      +
      +%module(package="pkg1.pkg2") foo
      +
      +
      + +

      +then the resulting directory layout should be +

      + +
      +
      +pkg1/
      +pkg1/__init__.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/foo.py        # (generated by SWIG)
      +pkg1/pkg2/_foo.so       # (shared library built from C/C++ code generated by SWIG)
      +
      +
      + +

      36.11.2 Absolute and relative imports

      + + +

      Suppose, we have the following hierarchy of files:

      + +
      +
      +pkg1/
      +pkg1/__init__.py
      +pkg1/mod2.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/mod3.py
      +
      +
      + +

      Let the contents of pkg1/pkg2/mod3.py be

      +
      +
      +class M3: pass
      +
      +
      + +

      +We edit pkg1/mod2.py and want to import module +pkg1/pkg2/mod3.py in order to derive from class M3. We can +write appropriate Python code in several ways, for example: +

      + +
        +
      1. Using "import <>" syntax with absolute package name:

        +
        +
        +# pkg1/mod2.py
        +import pkg1.pkg2.mod3
        +class M2(pkg1.pkg2.mod3.M3): pass
        +
        +
        +
      2. + +
      3. Using "import <>" syntax with package name relative to + pkg1 (only in Python 2.7 and earlier):

        +
        +
        +# pkg1/mod2.py
        +import pkg2.mod3
        +class M2(pkg2.mod3.M3): pass
        +
        +
        +
      4. + +
      5. Using "from <> import <>" syntax (relative import + syntax, only in Python 2.5 and later):

        +
        +
        +# pkg1/mod2.py
        +from .pkg2 import mod3
        +class M2(mod3.M3): pass
        +
        +
        +
      6. + +
      7. Other variants, for example the following construction in order to + have the pkg2.mod3.M3 symbol available in mod2 as + in point 2 above (but now under Python 3):

        +
        +
        +# pkg1/mod2.py
        +from . import pkg2
        +from .pkg2 import mod3
        +class M2(pkg2.mod3.M3): pass
        +
        +
        +
      8. + +
      + +

      Now suppose we have mod2.i with

      + +
      +
      +// mod2.i
      +%module (package="pkg1") mod2
      +%import "mod3.i"
      +// ...
      +
      +
      + +

      and mod3.i with

      + +
      +
      +// mod3.i
      +%module (package="pkg1.pkg2") mod3
      +// ...
      +
      +
      + +

      By default, SWIG would generate mod2.py proxy file with +import directive as in point 1. This can be changed with the +-relativeimport command line option. The -relativeimport instructs +SWIG to organize imports as in point 2 (for Python 2.x) or as in point 4 (for +Python 3, that is when the -py3 command line option is enabled). In short, if you have +mod2.i and mod3.i as above, then without +-relativeimport SWIG will write

      + +
      +
      +import pkg1.pkg2.mod3
      +
      +
      + +

      to mod2.py proxy file, and with -relativeimport it will +write

      + +
      +
      +import pkg2.mod3
      +
      +
      + +

      if -py3 is not used, or

      + +
      +
      +from . import pkg2
      +import pkg1.pkg2.mod3
      +
      +
      + +

      when -py3 is used.

      + +

      You should avoid using relative imports and use absolute ones whenever +possible. There are some cases, however, when relative imports may be +necessary. The first example is, when some (legacy) Python code refers entities +imported by proxy files generated by SWIG, and it assumes that the proxy file +uses relative imports. Second case is, when one puts import directives in +__init__.py to import symbols from submodules or subpackages and the +submodule depends on other submodules (discussed later).

      + +

      36.11.3 Enforcing absolute import semantics

      + + +

      As you may know, there is an incompatibility in import semantics (for the +import <> syntax) between Python 2 and 3. In Python 2.4 and +earlier it is not clear whether

      + +
      +
      +import foo
      +
      +
      +

      refers to a top-level module or to another module inside the current +package. In Python 3 it always refers to a top-level module +(see PEP 328). +To instruct Python 2.5 through 2.7 to use new semantics (that is import +foo is interpreted as absolute import), one has to put the following +line +

      + +
      +
      +from __future__ import absolute_import
      +
      +
      + +

      at the very beginning of his proxy *.py file. In SWIG, it may be +accomplished with %pythonbegin directive as follows:

      + +
      +
      +%pythonbegin %{
      +from __future__ import absolute_import
      +%}
      +
      +
      + +

      36.11.4 Importing from __init__.py

      + + +

      Imports in __init__.py are handy when you want to populate a +package's namespace with names imported from other modules. In SWIG based +projects this approach may also be used to split large pieces of code into +smaller modules, compile them in parallel and then re-assemble everything at +runtime by importing submodules' contents in __init__.py, for +example.

      + +

      Unfortunately import directives in __init__.py may cause problems, +especially if they refer to a package's submodules. This is caused by the way +Python initializes packages. If you spot problems with imports from +__init__.py try using -relativeimport option. Below we +explain in detail one issue, for which the -relativeimport workaround +may be helpful.

      + +

      Consider the following example (Python 3):

      + +
      +
      +pkg1/__init__.py        # (empty)
      +pkg1/pkg2/__init__.py   # (imports something from bar.py)
      +pkg1/pkg2/foo.py
      +pkg1/pkg2/bar.py        # (imports foo.py)
      +
      +
      + +

      If the file contents are:

      + +
        +
      • pkg1/pkg2/__init__.py:

        +
        +
        +# pkg1/pkg2/__init__.py
        +from .bar import Bar
        +
        +
        +
      • + +
      • pkg1/pkg2/foo.py:

        +
        +
        +# pkg1/pkg2/foo.py
        +class Foo: pass
        +
        +
        +
      • + +
      • pkg1/pkg2/bar.py:

        +
        +
        +# pkg1/pkg2/bar.py
        +import pkg1.pkg2.foo
        +class Bar(pkg1.pkg2.foo.Foo): pass
        +
        +
        +
      • +
      + +

      Now if one simply used import pkg1.pkg2, it will usually fail:

      + +
      +
      +>>> import pkg1.pkg2
      +Traceback (most recent call last):
      +  File "<stdin>", line 1, in <module>
      +  File "./pkg1/pkg2/__init__.py", line 2, in <module>
      +    from .bar import Bar
      +  File "./pkg1/pkg2/bar.py", line 3, in <module>
      +    class Bar(pkg1.pkg2.foo.Foo): pass
      +AttributeError: 'module' object has no attribute 'pkg2'
      +
      +
      + +

      Surprisingly, if we execute the import pkg1.pkg2 directive for the +second time, it succeeds. The reason seems to be following: when Python spots +the from .bar import Bar directive in pkg1/pkg2/__init__.py +it starts loading pkg1/pkg2/bar.py. This module imports +pkg1.pkg2.foo in turn and tries to use pkg1.pkg2.foo.Foo, but +the package pkg1 is not fully initialized yet (the initialization +procedure is actually in progress) and it seems like the effect of the already seen +import pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly the +same may happen to a proxy module generated by SWIG.

      + +

      One workaround for this case is to use a relative +import in pkg1/pkg2/bar.py. If we change bar.py to be:

      + +
      +
      +from .pkg3 import foo
      +class Bar(foo.Foo): pass
      +
      +
      + +

      or

      + +
      +
      +from . import pkg3
      +from .pkg3 import foo
      +class Bar(pkg3.foo.Foo): pass
      +
      +
      + +

      then the example works again. With SWIG, you need to enable the +-relativeimport option in order to have the above workaround in +effect (note, that the Python 2 case also needs the -relativeimport +workaround).

      + + +

      36.12 Python 3 Support

      @@ -5229,7 +5893,7 @@ The following are Python 3.0 new features that are currently supported by SWIG.

      -

      34.12.1 Function annotation

      +

      36.12.1 Function annotation

      @@ -5259,10 +5923,10 @@ all overloaded functions share the same function in SWIG generated proxy class.

      For detailed usage of function annotation, see -PEP 3107. +PEP 3107.

      -

      34.12.2 Buffer interface

      +

      36.12.2 Buffer interface

      @@ -5414,7 +6078,7 @@ modify the buffer.

      -

      34.12.3 Abstract base classes

      +

      36.12.3 Abstract base classes

      @@ -5452,7 +6116,243 @@ 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

      + + +

      +By default, any byte string (char* or std::string) returned +from C or C++ code is decoded to text as UTF-8. This decoding uses the +surrogateescape error handler under Python 3.1 or higher -- this +error handler decodes invalid byte sequences to high surrogate characters +in the range U+DC80 to U+DCFF. + +As an example, consider the following SWIG interface, which exposes a byte +string that cannot be completely decoded as UTF-8: +

      + +
      +%module example
      +
      +%include <std_string.i>
      +
      +%inline %{
      +
      +const char* non_utf8_c_str(void) {
      +        return "h\xe9llo w\xc3\xb6rld";
      +}
      +
      +%}
      +
      + +

      +When this method is called from Python 3, the return value is the following +text string: +

      + +
      +>>> s = example.non_utf8_c_str()
      +>>> s
      +'h\udce9llo wörld'
      +
      + +

      +Since the C string contains bytes that cannot be decoded as UTF-8, those raw +bytes are represented as high surrogate characters that can be used to obtain +the original byte sequence: +

      + +
      +>>> b = s.encode('utf-8', errors='surrogateescape')
      +>>> b
      +b'h\xe9llo w\xc3\xb6rld'
      +
      + +

      +One can then attempt a different encoding, if desired (or simply leave the +byte string as a raw sequence of bytes for use in binary protocols): +

      + +
      +>>> b.decode('latin-1')
      +'héllo wörld'
      +
      + +

      +Note, however, that text strings containing surrogate characters are rejected +with the default strict codec error handler. For example: +

      + +
      +>>> with open('test', 'w') as f:
      +...     print(s, file=f)
      +...
      +Traceback (most recent call last):
      +  File "<stdin>", line 2, in <module>
      +UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 1: surrogates not allowed
      +
      + +

      +This requires the user to check most strings returned by SWIG bindings, but +the alternative is for a non-UTF8 byte string to be completely inaccessible +in Python 3 code. +

      + +

      +For more details about the surrogateescape error handler, please see +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 ceea32146..9b5993bff 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -1,12 +1,13 @@ - + SWIG and R + -

      35 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++.

        -

        35.1 Bugs

        +

        37.1 Bugs

        @@ -45,7 +46,7 @@ Currently the following features are not implemented or broken:

      • C Array wrappings
      -

      35.2 Using R and SWIG

      +

      37.2 Using R and SWIG

      @@ -119,7 +120,24 @@ Without it, inheritance of wrapped objects may fail. These two files can be loaded in any order

      -

      35.3 Precompiling large R files

      +

      + If you are compiling code yourself (not using R itself), there are a few things to watch out for: +

      + +
        +
      • The output shared library name (to the left of the file extension) MUST match the module name, or alternatively, you can also set the -package NAME command line argument. See swig -r -help for more information +
      • If you do not set the output file name appropriately, you might see errors like +
        +
        +> fact(4)
        +Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") :
        +  "R_swig_fact" not available for .Call() for package "example"
        +
        +
        +
      • 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

      In cases where the R file is large, one make save a lot of loading @@ -137,7 +155,7 @@ will save a large amount of loading time. -

      35.4 General policy

      +

      37.4 General policy

      @@ -146,7 +164,7 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.

      -

      35.5 Language conventions

      +

      37.5 Language conventions

      @@ -155,7 +173,7 @@ and [ are overloaded to allow for R syntax (one based indices and slices)

      -

      35.6 C++ classes

      +

      37.6 C++ classes

      @@ -167,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.

      -

      35.7 Enumerations

      +

      37.7 Enumerations

      diff --git a/Doc/Manual/README b/Doc/Manual/README index f01013d54..66daaec90 100644 --- a/Doc/Manual/README +++ b/Doc/Manual/README @@ -1,9 +1,9 @@ This directory contains the HTML for the SWIG users manual. All of this HTML is hand-written. However, section numbering, indices, -and the table of contents is generated automatically by the 'maketoc.py' +and the table of contents are generated automatically by the 'maketoc.py' script. The Makefile has further information on how the various alternative -forms of the documentation is generated from the hand-written HTML. +forms of the documentation are generated from the hand-written HTML. There are 4 types of boxes that code or whatever can be inside: -

      ...
      diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 69005c731..cfb99e792 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -1,13 +1,14 @@ - + - SWIG and Ruby - +SWIG and Ruby + + -

      36 SWIG and Ruby

      +

      38 SWIG and Ruby

        @@ -42,6 +43,10 @@
      • C++ STL Functors
      • C++ STL Iterators
      • C++ Smart Pointers +
      • Cross-Language Polymorphism
        • Exception Unrolling @@ -71,9 +76,9 @@
        • Placement of typemaps
        • Ruby typemaps
            -
          •  "in" typemap +
          • "in" typemap
          • "typecheck" typemap -
          •  "out" typemap +
          • "out" typemap
          • "arginit" typemap
          • "default" typemap
          • "check" typemap @@ -144,137 +149,75 @@

            This chapter describes SWIG's support of Ruby.

            +

            38.1 Preliminaries

            - - -

            36.1 Preliminaries

            - - -

            SWIG 1.3 is known to work with Ruby versions 1.6 and later. +

            SWIG 3.0 is known to work with Ruby versions 1.8 and later. Given the choice, you should use the latest stable version of Ruby. You should also determine if your system supports shared libraries and dynamic loading. SWIG will work with or without dynamic loading, but the compilation process will vary.

            - - - -

            This chapter covers most SWIG features, but in less depth than is found in earlier chapters. At the very least, make sure you also read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby.

            - - - - -

            36.1.1 Running SWIG

            +

            38.1.1 Running SWIG

            To build a Ruby module, run SWIG using the -ruby option:

            - - - -
            -
            $ swig -ruby example.i
            +
            $ swig -ruby example.i
             
            - - - - -
            - - - -

            If building a C++ extension, add the -c++ option:

            - - - -
            -
            $ swig -c++ -ruby example.i
            +
            $ swig -c++ -ruby example.i
             
            - - - - -
            - - - -

            This creates a file example_wrap.c (example_wrap.cxx if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

            - - - - -

            36.1.2 Getting the right header files

            +

            38.1.2 Getting the right header files

            In order to compile the wrapper code, the compiler needs the ruby.h header file. This file is usually contained in a directory such as

            - - - -
            /usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h
            -/usr/local/lib/ruby/1.6/i686-linux/ruby.h
            +/usr/include/ruby-2.1.0/ruby.h
             
            - - - - -
            - - - -

            The exact location may vary on your machine, but the above location is typical. If you are not entirely sure where Ruby is installed, you can run Ruby to find out. For example:

            - - - -
            -
            $ ruby -e 'puts $:.join("\n")'
            -/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux
            -/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux .
            +
            $ ruby -e 'puts $:.join("\n")'
            +/usr/local/lib/site_ruby/2.1.0
            +/usr/local/lib/x86_64-linux-gnu/site_ruby
            +/usr/local/lib/site_ruby
            +/usr/lib/ruby/vendor_ruby/2.1.0
            +/usr/lib/x86_64-linux-gnu/ruby/vendor_ruby/2.1.0
            +/usr/lib/ruby/vendor_ruby
            +/usr/lib/ruby/2.1.0
            +/usr/lib/x86_64-linux-gnu/ruby/2.1.0
             
            - - - - -
            - - - - -

            36.1.3 Compiling a dynamic module

            +

            38.1.3 Compiling a dynamic module

            Ruby extension modules are typically compiled into shared @@ -283,100 +226,32 @@ exact commands for doing this vary from platform to platform, your best bet is to follow the steps described in the README.EXT file from the Ruby distribution:

            - - - -
              - - - - -
            1. - - - -

              Create a file called extconf.rb that looks like the following:

              - - - - - - - - -
              -
              require 'mkmf'
              create_makefile('example')
              +
              require 'mkmf'
              +create_makefile('example')
              - - - - -
            2. - - - - -
            3. - - - -

              Type the following to build the extension:

              - - - - - - - - -
              - - - - -
              $ ruby extconf.rb
              $ make
              $ make install +
              +$ ruby extconf.rb
              +$ make
              +$ make install
                   
              - - - - -
              - - - - -
            4. - - - - -
            - - - -

            Of course, there is the problem that mkmf does not work correctly on all platforms, e.g, HPUX. If you need to add your own make rules to the file that extconf.rb produces, you can add this:

            - - - -
            open("Makefile", "a") { |mf|
              puts <<EOM
            @@ -384,51 +259,38 @@ can add this: 

            EOM }
            - - - - -
            - - - -

            to the end of the extconf.rb file. If for some reason you don't want to use the standard approach, you'll need to determine the correct compiler and linker flags for your build -platform. For example, a typical sequence of commands for the Linux +platform. For example, assuming you have code you need to link to in a file +called example.c, a typical sequence of commands for the Linux operating system would look something like this:

            - - - -
            -
            $ swig -ruby example.i
            -$ gcc -c example.c
            -$ gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux 
            -$ gcc -shared example.o example_wrap.o -o example.so
            +
            $ swig -ruby example.i
            +$ gcc -O2 -fPIC -c example.c
            +$ gcc -O2 -fPIC -c example_wrap.c -I/usr/include/ruby-2.1.0
            +$ gcc -shared example.o example_wrap.o -o example.so
             
            - - - - -
            +

            +The -fPIC option tells GCC to generate position-independent code (PIC) +which is required for most architectures (it's not vital on x86, but +still a good idea as it allows code pages from the library to be shared between +processes). Other compilers may need a different option specified instead of +-fPIC. +

            - - - -

            For other platforms it may be necessary to compile with the -fPIC -option to generate position-independent code. If in doubt, consult the +

            +If in doubt, consult the manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

            -

            36.1.4 Using your module

            +

            38.1.4 Using your module

            Ruby module names must be capitalized, @@ -436,10 +298,6 @@ but the convention for Ruby feature names is to use lowercase names. So, for example, the Etc extension module is imported by requiring the etc feature:

            - - - -
            # The feature name begins with a lowercase letter...
             require 'etc'
            @@ -447,48 +305,22 @@ require 'etc'
             # ... but the module name begins with an uppercase letter
             puts "Your login name: #{Etc.getlogin}"
             
            - - - - -
            - - - -

            To stay consistent with this practice, you should always specify a lowercase module name with SWIG's %module directive. SWIG will automatically correct the resulting Ruby module name for your extension. So for example, a SWIG interface file that begins with:

            - - - -
            -
            %module example
            - - - - - +
            %module example
            - - - -

            will result in an extension module using the feature name "example" and Ruby module name "Example".

            - - - - -

            36.1.5 Static linking

            +

            38.1.5 Static linking

            An alternative approach to dynamic linking is to rebuild the @@ -498,41 +330,26 @@ loading support on certain machines. However, the situation has improved greatly over the last few years and you should not consider this approach unless there is really no other option.

            - - - -

            The usual procedure for adding a new module to Ruby involves finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.

            - - -

            36.1.6 Compilation of C++ extensions

            +

            38.1.6 Compilation of C++ extensions

            On most machines, C++ extension modules should be linked using the C++ compiler. For example:

            - - - -
            -
            $ swig -c++ -ruby example.i
            $ g++ -c example.cxx
            $ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux
            $ g++ -shared example.o example_wrap.o -o example.so +
            +$ swig -c++ -ruby example.i
            +$ g++ -fPIC -c example.cxx
            +$ g++ -fPIC -c example_wrap.cxx -I/usr/include/ruby-2.1.0
            +$ g++ -shared example.o example_wrap.o -o example.so
             
            - - - - -
            - - - -

            If you've written an extconf.rb script to automatically generate a Makefile for your C++ extension module, keep in mind that (as of this writing) Ruby still @@ -544,24 +361,13 @@ module's append_library() method to add one of the C++ runtime libraries to the list of libraries linked into your extension, e.g.

            - - - -
            -
            require 'mkmf'
            $libs = append_library($libs, "supc++")
            create_makefile('example')
            - - - - - +
            require 'mkmf'
            +$libs = append_library($libs, "supc++")
            +create_makefile('example')
            - - - - -

            36.2 Building Ruby Extensions under Windows 95/NT

            +

            38.2 Building Ruby Extensions under Windows 95/NT

            Building a SWIG extension to Ruby under Windows 95/NT is @@ -571,24 +377,14 @@ recent versions of Ruby, the procedure described above (i.e. using an extcon script) will work with Windows as well; you should be able to build your code into a DLL by typing:

            - - - -
            -
            C:\swigtest> ruby extconf.rb
            C:\swigtest> nmake
            C:\swigtest> nmake install +
            +C:\swigtest> ruby extconf.rb
            +C:\swigtest> nmake
            +C:\swigtest> nmake install
             
            - - - - -
            - - - -

            The remainder of this section covers the process of compiling SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within the Developer Studio IDE, instead of using the command line tools). In @@ -596,84 +392,35 @@ order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files.

            - - - - -

            36.2.1 Running SWIG from Developer Studio

            +

            38.2.1 Running SWIG from Developer Studio

            If you are developing your application within Microsoft developer studio, SWIG can be invoked as a custom build option. The process roughly follows these steps :

            - - - - -
              - - - - -
            • Open up a new workspace and use the AppWizard to select a DLL project.
            • - - - - -
            • Add both the SWIG interface file (the .i file), any supporting C files, and the name of the wrapper file that will be created by SWIG (i.e. example_wrap.c). Note : If using C++, choose a different suffix for the wrapper file such as example_wrap.cxx. Don't worry if the wrapper file doesn't exist yet--Developer Studio will keep a reference to it around.
            • - - - - -
            • Select the SWIG interface file and go to the settings menu. Under settings, select the "Custom Build" option.
            • - - - - -
            • Enter "SWIG" in the description field.
            • - - - - -
            • Enter "swig -ruby -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)" in the "Build command(s) field". You may have to include the path to swig.exe.
            • - - - - -
            • Enter "$(ProjDir)\$(InputName)_wrap.c" in the "Output files(s) field".
            • - - - - -
            • Next, select the settings for the entire project and go to the C/C++ tab and select the Preprocessor category. Add NT=1 to the Preprocessor definitions. This must be set else you will get compilation errors. Also add IMPORT to the preprocessor definitions, else you may get runtime errors. Also add the include directories for your Ruby installation under "Additional include directories".
            • - - - - -
            • Next, select the settings for the entire project and go to the Link tab and select the General category. Set the name of the output file to match the name of your Ruby module (i.e.. example.dll). @@ -681,23 +428,9 @@ Next add the Ruby library file to your link libraries under Object/Library modules. For example "mswin32-ruby16.lib. You also need to add the path to the library under the Input tab - Additional library path.
            • - - - - -
            • Build your project.
            • - - - - -
            - - - -

            Now, assuming all went well, SWIG will be automatically invoked when you build your project. Any changes made to the interface file will result in SWIG being automatically invoked to produce a new @@ -705,211 +438,95 @@ version of the wrapper file. To run your new Ruby extension, simply run Ruby and use the require command as normal. For example if you have this ruby file run.rb:

            - - - -
            -
            # file: run.rb
            require 'Example'

            # Call a c function
            print "Foo = ", Example.Foo, "\n"
            - - - - +
            # file: run.rb
            +require 'Example'
             
            +# Call a c function
            +print "Foo = ", Example.Foo, "\n"
            - - - -

            Ensure the dll just built is in your path or current directory, then run the Ruby script from the DOS/Command prompt:

            - - - -
            -
            C:\swigtest> ruby run.rb
            Foo = 3.0
            - - - - - +
            +C:\swigtest> ruby run.rb
            +Foo = 3.0
            +
            - - - - -

            36.3 The Ruby-to-C/C++ Mapping

            +

            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.

            - - - - -

            36.3.1 Modules

            +

            38.3.1 Modules

            The SWIG %module directive specifies the name of the Ruby module. If you specify:

            - - - -
            %module example
            - - - - -
            - - - -

            then everything is wrapped into a Ruby module named Example that is nested directly under the global module. You can specify a more deeply nested module by specifying the fully-qualified module name in quotes, e.g.

            - - - -
            %module "foo::bar::spam"
            - - - - -
            - - - -

            An alternate method of specifying a nested module name is to -use the -prefix +use the -prefix option on the SWIG command line. The prefix that you specify with this -option will be prepended to the module name specified with the %module +option will be prepended to the module name specified with the %module directive in your SWIG interface file. So for example, this declaration -at the top of your SWIG interface file:
            - - - - - +at the top of your SWIG interface file:

            - - - -
            %module "foo::bar::spam"
            - - - - -
            - - - - -

            will result in a nested module name of Foo::Bar::Spam, +

            will result in a nested module name of Foo::Bar::Spam, but you can achieve the same -effect by specifying:
            - - - - - +effect by specifying:

            - - - -
            %module spam
            - - - - -
            - - - - -

            and then running SWIG with the -prefix command -line option:
            - - - - - +

            and then running SWIG with the -prefix command +line option:

            - - - -
            -
            $ swig -ruby -prefix "foo::bar::" example.i
            - - - - - +
            +$ swig -ruby -prefix "foo::bar::" example.i
            +
            - - - -

            Starting with SWIG 1.3.20, you can also choose to wrap everything into the global module by specifying the -globalmodule option on the SWIG command line, i.e.

            - - - -
            -
            $ swig -ruby -globalmodule example.i
            - - - - - +
            +$ swig -ruby -globalmodule example.i
            +
            - - - -

            Note that this does not relieve you of the requirement of specifying the SWIG module name with the %module directive (or the -module command-line option) as described earlier.

            - - - -

            When choosing a module name, do not use the same name as a built-in Ruby command or standard module name, as the results may be unpredictable. Similarly, if you're using the -globalmodule @@ -917,74 +534,41 @@ option to wrap everything into the global module, take care that the names of your constants, classes and methods don't conflict with any of Ruby's built-in names.

            - - - - -

            36.3.2 Functions

            +

            38.3.2 Functions

            Global functions are wrapped as Ruby module methods. For example, given the SWIG interface file example.i:

            - - - -
            -
            %module example

            int fact(int n);
            - - - - +
            %module example
             
            +int fact(int n);
            - - - -

            and C source file example.c:

            - - - -
            -
            int fact(int n) {
            if (n == 0)
            return 1;
            return (n * fact(n-1));
            }
            - - - - - +
            int fact(int n) {
            +  if (n == 0)
            +  return 1;
            +  return (n * fact(n-1));
            +}
            - - - -

            SWIG will generate a method fact in the Example module that can be used like so:

            - - - -
            -
            $ irb
            irb(main):001:0> require 'example'
            true
            irb(main):002:0> Example.fact(4)
            24
            - - - - - +
            $ irb
            +irb(main):001:0> require 'example'
            +true
            +irb(main):002:0> Example.fact(4)
            +24
            - - - - -

            36.3.3 Variable Linking

            +

            38.3.3 Variable Linking

            C/C++ global variables are wrapped as a pair of singleton @@ -992,143 +576,89 @@ methods for the module: one to get the value of the global variable and one to set it. For example, the following SWIG interface file declares two global variables:

            - - - -
            -
            // SWIG interface file with global variables
            %module example
            ...
            %inline %{
            extern int variable1;
            extern double Variable2;
            %}
            ...
            - - - - - +
            // SWIG interface file with global variables
            +%module example
            +...
            +%inline %{
            +  extern int variable1;
            +  extern double Variable2;
            +%}
            +...
            - - - -

            Now look at the Ruby interface:

            - - - -
            -
            $ irb
            irb(main):001:0> require 'Example'
            true
            irb(main):002:0> Example.variable1 = 2
            2
            irb(main):003:0> Example.Variable2 = 4 * 10.3
            41.2
            irb(main):004:0> Example.Variable2
            41.2
            - - - - - +
            $ irb
            +irb(main):001:0> require 'Example'
            +true
            +irb(main):002:0> Example.variable1 = 2
            +2
            +irb(main):003:0> Example.Variable2 = 4 * 10.3
            +41.2
            +irb(main):004:0> Example.Variable2
            +41.2
            - - - -

            If you make an error in variable assignment, you will receive an error message. For example:

            - - - -
            -
            irb(main):005:0> Example.Variable2 = "hello"
            TypeError: no implicit conversion to float from string
            from (irb):5:in `Variable2='
            from (irb):5
            - - - - - +
            irb(main):005:0> Example.Variable2 = "hello"
            +TypeError: no implicit conversion to float from string
            +from (irb):5:in `Variable2='
            +from (irb):5
            - - - -

            If a variable is declared as const, it is wrapped as a read-only variable. Attempts to modify its value will result in an error.

            - - - -

            To make ordinary variables read-only, you can also use the %immutable directive. For example:

            - - - -
            -
            %immutable;
            %inline %{
            extern char *path;
            %}
            %mutable;
            - - - - - +
            %immutable;
            +%inline %{
            +  extern char *path;
            +%}
            +%mutable;
            - - - -

            The %immutable directive stays in effect until it is explicitly disabled using %mutable.

            - - - - -

            36.3.4 Constants

            +

            38.3.4 Constants

            C/C++ constants are wrapped as module constants initialized to the appropriate value. To create a constant, use #define or the %constant directive. For example:

            - - - -
            -
            #define PI 3.14159
            #define VERSION "1.0"

            %constant int FOO = 42;
            %constant const char *path = "/usr/local";

            const int BAR = 32;
            - - - +
            #define PI 3.14159
            +#define VERSION "1.0"
             
            +%constant int FOO = 42;
            +%constant const char *path = "/usr/local";
             
            +const int BAR = 32;
            - - - -

            Remember to use the :: operator in Ruby to get at these constant values, e.g.

            - - - -
            -
            $ irb
            irb(main):001:0> require 'Example'
            true
            irb(main):002:0> Example::PI
            3.14159
            - - - - - +
            $ irb
            +irb(main):001:0> require 'Example'
            +true
            +irb(main):002:0> Example::PI
            +3.14159
            - - - - -

            36.3.5 Pointers

            +

            38.3.5 Pointers

            "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -1136,125 +666,71 @@ aren't explicitly declared in your SWIG interface file) are wrapped as data objects. So, for example, consider a SWIG interface file containing only the declarations:

            - - - -
            -
            Foo *get_foo();
            void set_foo(Foo *foo);
            - - - - - +
            Foo *get_foo();
            +void set_foo(Foo *foo);
            - - - -

            For this case, the get_foo() method returns an instance of an internally generated Ruby class:

            - - - -
            -
            irb(main):001:0> foo = Example::get_foo()
            #<SWIG::TYPE_p_Foo:0x402b1654>
            - - - - - +
            irb(main):001:0> foo = Example::get_foo()
            +#<SWIG::TYPE_p_Foo:0x402b1654>
            - - - -

            A NULL pointer is always represented by the Ruby nil object.

            - - - - -

            36.3.6 Structures

            +

            38.3.6 Structures

            C/C++ structs are wrapped as Ruby classes, with accessor methods (i.e. "getters" and "setters") for all of the struct members. For example, this struct declaration:

            - - - -
            -
            struct Vector {
            double x, y;
            };
            - - - - - +
            struct Vector {
            +  double x, y;
            +};
            - - - -

            gets wrapped as a Vector class, with -Ruby instance methods x, x=, +Ruby instance methods x, x=, y and y=. These methods can be used to access structure data from Ruby as follows:

            - - - -
            -
            $ irb
            irb(main):001:0> require 'Example'
            true
            irb(main):002:0> f = Example::Vector.new
            #<Example::Vector:0x4020b268>
            irb(main):003:0> f.x = 10
            nil
            irb(main):004:0> f.x
            10.0
            - - - - - +
            $ irb
            +irb(main):001:0> require 'Example'
            +true
            +irb(main):002:0> f = Example::Vector.new
            +#<Example::Vector:0x4020b268>
            +irb(main):003:0> f.x = 10
            +nil
            +irb(main):004:0> f.x
            +10.0
            - - - -

            Similar access is provided for unions and the public data members of C++ classes.

            - - - -

            const members of a structure are read-only. Data members can also be forced to be read-only using the %immutable directive (in C++, private may also be used). For example:

            - - - -
            -
            struct Foo {
            ...
            %immutable;
            int x; /* Read-only members */
            char *name;
            %mutable;
            ...
            };
            - - - - - +
            struct Foo {
            +  ...
            +  %immutable;
            +  int x; /* Read-only members */
            +  char *name;
            +  %mutable;
            +  ...
            +};
            - - - -

            When char * members of a structure are wrapped, the contents are assumed to be dynamically allocated using malloc or new (depending on whether or not SWIG is run @@ -1263,99 +739,55 @@ is set, the old contents will be released and a new value created. If this is not the behavior you want, you will have to use a typemap (described shortly).

            - - - -

            Array members are normally wrapped as read-only. For example, this code:

            - - - -
            -
            struct Foo {
            int x[50];
            };
            - - - - - +
            struct Foo {
            +  int x[50];
            +};
            - - - -

            produces a single accessor function like this:

            - - - -
            -
            int *Foo_x_get(Foo *self) {
            return self->x;
            };
            - - - - - +
            int *Foo_x_get(Foo *self) {
            +  return self->x;
            +};
            - - - -

            If you want to set an array member, you will need to supply a "memberin" typemap described in the section on typemaps. As a special case, SWIG does generate code to set array members of type char (allowing you to store a Ruby string in the structure).

            - - - -

            When structure members are wrapped, they are handled as pointers. For example,

            - - - -
            -
            struct Foo {
            ...
            };

            struct Bar {
            Foo f;
            };
            - - - - +
            struct Foo {
            +  ...
            +};
             
            +struct Bar {
            +  Foo f;
            +};
            - - - -

            generates accessor functions such as this:

            - - - -
            -
            Foo *Bar_f_get(Bar *b) {
            return &b->f;
            }

            void Bar_f_set(Bar *b, Foo *val) {
            b->f = *val;
            }
            - - - - +
            Foo *Bar_f_get(Bar *b) {
            +  return &b->f;
            +}
             
            +void Bar_f_set(Bar *b, Foo *val) {
            +  b->f = *val;
            +}
            - - - - -

            36.3.7 C++ classes

            +

            38.3.7 C++ classes

            Like structs, C++ classes are wrapped by creating a new Ruby @@ -1365,152 +797,97 @@ wrapped as Ruby instance methods, and public static member functions are wrapped as Ruby singleton methods. So, given the C++ class declaration:

            - - - -
            -
            class List {
            public:
            List();
            ~List();
            int search(char *item);
            void insert(char *item);
            void remove(char *item);
            char *get(int n);
            int length;
            static void print(List *l);
            };
            - - - - - +
            class List {
            +public:
            +  List();
            +  ~List();
            +  int search(char *item);
            +  void insert(char *item);
            +  void remove(char *item);
            +  char *get(int n);
            +  int length;
            +  static void print(List *l);
            +};
            - - - -

            SWIG would create a List class with:

            - - - -
              - - - - -
            • instance methods search, insert, remove, and get;
            • - - - - -
            • instance methods length and length= (to get and set the value of the length data member); and,
            • - - - - -
            • a print singleton method for the class.
            • - - - - -
            - - - -

            In Ruby, these functions are used as follows:

            - - - -
            -
            require 'Example'

            l = Example::List.new

            l.insert("Ale")
            l.insert("Stout")
            l.insert("Lager")
            Example.print(l)
            l.length()
            ----- produces the following output
            Lager
            Stout
            Ale
            3
            - - - +
            require 'Example'
             
            +l = Example::List.new
             
            +l.insert("Ale")
            +l.insert("Stout")
            +l.insert("Lager")
            +Example.print(l)
            +l.length()
            +----- produces the following output 
            +Lager
            +Stout
            +Ale
            +3
            - - - - -

            36.3.8 C++ Inheritance

            +

            38.3.8 C++ Inheritance

            The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have classes like this:

            - - - -
            -
            class Parent {
            ...
            };

            class Child : public Parent {
            ...
            };
            - - - - +
            class Parent {
            +  ...
            +};
             
            +class Child : public Parent {
            +  ...
            +};
            - - - -

            those classes are wrapped into a hierarchy of Ruby classes that reflect the same inheritance structure. All of the usual Ruby utility methods work normally:

            - - - -
            -
            irb(main):001:0> c = Child.new
            #<Bar:0x4016efd4>
            irb(main):002:0> c.instance_of? Child
            true
            irb(main):003:0> b.instance_of? Parent
            false
            irb(main):004:0> b.is_a? Child
            true
            irb(main):005:0> b.is_a? Parent
            true
            irb(main):006:0> Child < Parent
            true
            irb(main):007:0> Child > Parent
            false
            - - - - - +
            irb(main):001:0> c = Child.new
            +#<Bar:0x4016efd4>
            +irb(main):002:0> c.instance_of? Child
            +true
            +irb(main):003:0> b.instance_of? Parent
            +false
            +irb(main):004:0> b.is_a? Child
            +true
            +irb(main):005:0> b.is_a? Parent
            +true
            +irb(main):006:0> Child < Parent
            +true
            +irb(main):007:0> Child > Parent
            +false
            - - - -

            Furthermore, if you have a function like this:

            - - - -
            -
            void spam(Parent *f);
            - - - - - +
            void spam(Parent *f);
            - - - -

            then the function spam() accepts Parent* or a pointer to any class derived from Parent.

            - - - -

            Until recently, the Ruby module for SWIG didn't support multiple inheritance, and this is still the default behavior. This doesn't mean that you can't wrap C++ classes which inherit from @@ -1519,23 +896,13 @@ base class listed in the class declaration is considered, and any additional base classes are ignored. As an example, consider a SWIG interface file with a declaration like this:

            - - - -
            -
            class Derived : public Base1, public Base2
            {
            ...
            };
            - - - - - +
            class Derived : public Base1, public Base2
            +{
            +  ...
            +};
            - - - -

            For this case, the resulting Ruby class (Derived) will only consider Base1 as its superclass. It won't inherit any of Base2's member functions or @@ -1544,66 +911,33 @@ data and it won't recognize Base2 as an relationship would fail). When SWIG processes this interface file, you'll see a warning message like:

            - - - -
            -
            example.i:5: Warning 802: Warning for Derived: Base Base2 ignored.
            Multiple inheritance is not supported in Ruby.
            - - - - - +
            example.i:5: Warning 802: Warning for Derived: Base Base2 ignored.
            +Multiple inheritance is not supported in Ruby.
            - - - -

            Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited support for multiple inheritance. Because the approach for dealing with multiple inheritance introduces some limitations, this is an optional feature that you can activate with the -minherit command-line option:

            - - - -
            -
            $ swig -c++ -ruby -minherit example.i
            - - - - - +
            +$ swig -c++ -ruby -minherit example.i
            +
            - - - -

            Using our previous example, if your SWIG interface file contains a declaration like this:

            - - - -
            -
            class Derived : public Base1, public Base2
            {
            ...
            };
            - - - - - +
            class Derived : public Base1, public Base2
            +{
            +  ...
            +};
            - - - -

            and you run SWIG with the -minherit command-line option, then you will end up with a Ruby class Derived that appears to "inherit" the member data and functions from both Base1 @@ -1614,346 +948,186 @@ module named Impl, and it's in these nested Impl modules that the actual instance methods for the classes are defined, i.e.

            - - - -
            -
            class Base1
            module Impl
            # Define Base1 methods here
            end
            include Impl
            end

            class Base2
            module Impl
            # Define Base2 methods here
            end
            include Impl
            end

            class Derived
            module Impl
            include Base1::Impl
            include Base2::Impl
            # Define Derived methods here
            end
            include Impl
            end
            - - - +
            class Base1
            +  module Impl
            +  # Define Base1 methods here
            +  end
            +  include Impl
            +end
             
            +class Base2
            +  module Impl
            +  # Define Base2 methods here
            +  end
            +  include Impl
            +end
             
            +class Derived
            +  module Impl
            +  include Base1::Impl
            +  include Base2::Impl
            +  # Define Derived methods here
            +  end
            +  include Impl
            +end
            - - - -

            Observe that after the nested Impl module for a class is defined, it is mixed-in to the class itself. Also observe that the Derived::Impl module first mixes-in its base classes' Impl modules, thus "inheriting" all of their behavior.

            - - - -

            The primary drawback is that, unlike the default mode of operation, neither Base1 nor Base2 is a true superclass of Derived anymore:

            - - - -
            -
            obj = Derived.new
            obj.is_a? Base1 # this will return false...
            obj.is_a? Base2 # ... and so will this
            - - - - - +
            obj = Derived.new
            +obj.is_a? Base1 # this will return false...
            +obj.is_a? Base2 # ... and so will this
            - - - -

            In most cases, this is not a serious problem since objects of type Derived will otherwise behave as though they inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").

            - - - - -

            36.3.9 C++ Overloaded Functions

            +

            38.3.9 C++ Overloaded Functions

            C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

            - - - -
            -
            void foo(int);
            void foo(char *c);
            - - - - - +
            void foo(int);
            +void foo(char *c);
            - - - -

            You can use them in Ruby in a straightforward manner:

            - - - -
            -
            irb(main):001:0> foo(3) # foo(int)
            irb(main):002:0> foo("Hello") # foo(char *c)
            - - - - - +
            irb(main):001:0> foo(3) # foo(int)
            +irb(main):002:0> foo("Hello") # foo(char *c)
            - - - -

            Similarly, if you have a class like this,

            - - - -
            -
            class Foo {
            public:
            Foo();
            Foo(const Foo &);
            ...
            };
            - - - - - +
            class Foo {
            +public:
            +  Foo();
            +  Foo(const Foo &);
            +  ...
            +};
            - - - -

            you can write Ruby code like this:

            - - - -
            -
            irb(main):001:0> f = Foo.new # Create a Foo
            irb(main):002:0> g = Foo.new(f) # Copy f
            - - - - - +
            irb(main):001:0> f = Foo.new # Create a Foo
            +irb(main):002:0> g = Foo.new(f) # Copy f
            - - - -

            Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:

            - - - -
            -
            void spam(int);
            void spam(short);
            - - - - - +
            void spam(int);
            +void spam(short);
            - - - -

            or

            - - - -
            -
            void foo(Bar *b);
            void foo(Bar &b);
            - - - - - +
            void foo(Bar *b);
            +void foo(Bar &b);
            - - - -

            If declarations such as these appear, you will get a warning message like this:

            - - - -
             example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
             example.i:11: Warning 509: as it is shadowed by spam(int).
            -
            -
            - - - - - +
            - - - -

            To fix this, you either need to ignore or rename one of the methods. For example:

            - - - -
            -
            %rename(spam_short) spam(short);
            ...
            void spam(int);
            void spam(short); // Accessed as spam_short
            - - - - - +
            %rename(spam_short) spam(short);
            +...
            +void spam(int); 
            +void spam(short); // Accessed as spam_short
            - - - -

            or

            - - - -
            -
            %ignore spam(short);
            ...
            void spam(int);
            void spam(short); // Ignored
            - - - - - +
            %ignore spam(short);
            +...
            +void spam(int); 
            +void spam(short); // Ignored
            - - - -

            SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.

            - - - -

            Please refer to the "SWIG and C++" chapter for more information about overloading.

            - - - - -

            36.3.10 C++ Operators

            +

            38.3.10 C++ Operators

            For the most part, overloaded operators are handled automatically by SWIG and do not require any special treatment on your part. So if your class declares an overloaded addition operator, e.g.

            - - - -
            -
            class Complex {
            ...
            Complex operator+(Complex &);
            ...
            };
            - - - - - +
            class Complex {
            +  ...
            +  Complex operator+(Complex &);
            +  ...
            +};
            - - - -

            the resulting Ruby class will also support the addition (+) method correctly.

            - - - -

            For cases where SWIG's built-in support is not sufficient, C++ operators can be wrapped using the %rename directive (available on SWIG 1.3.10 and later releases). All you need to do is give the operator the name of a valid Ruby identifier. For example:

            - - - -
            -
            %rename(add_complex) operator+(Complex &, Complex &);
            ...
            Complex operator+(Complex &, Complex &);
            - - - - - +
            %rename(add_complex) operator+(Complex &, Complex &);
            +...
            +Complex operator+(Complex &, Complex &);
            - - - -

            Now, in Ruby, you can do this:

            - - - -
            -
            a = Example::Complex.new(2, 3)
            b = Example::Complex.new(4, -1)
            c = Example.add_complex(a, b)
            - - - - - +
            a = Example::Complex.new(2, 3)
            +b = Example::Complex.new(4, -1)
            +c = Example.add_complex(a, b)
            - - - -

            More details about wrapping C++ operators into Ruby operators is discussed in the section on operator overloading.

            - - - - -

            36.3.11 C++ namespaces

            +

            38.3.11 C++ namespaces

            SWIG is aware of C++ namespaces, but namespace names do not @@ -1961,63 +1135,48 @@ appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

            - - - -
            -
            %module example

            namespace foo {
            int fact(int n);
            struct Vector {
            double x,y,z;
            };
            };
            - - - - +
            %module example
             
            +namespace foo {
            +  int fact(int n);
            +  struct Vector {
            +    double x,y,z;
            +  };
            +};
            - - - -

            it works in Ruby as follows:

            - - - -
            -
            irb(main):001:0> require 'example'
            true
            irb(main):002:0> Example.fact(3)
            6
            irb(main):003:0> v = Example::Vector.new
            #<Example::Vector:0x4016f4d4>
            irb(main):004:0> v.x = 3.4
            3.4
            irb(main):004:0> v.y
            0.0
            - - - - - +
            irb(main):001:0> require 'example'
            +true
            +irb(main):002:0> Example.fact(3)
            +6
            +irb(main):003:0> v = Example::Vector.new
            +#<Example::Vector:0x4016f4d4>
            +irb(main):004:0> v.x = 3.4
            +3.4
            +irb(main):004:0> v.y
            +0.0
            - - - -

            If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

            - - - -
            -
            %rename(Bar_spam) Bar::spam;

            namespace Foo {
            int spam();
            }

            namespace Bar {
            int spam();
            }
            - - - +
            %rename(Bar_spam) Bar::spam;
             
            +namespace Foo {
            +  int spam();
            +}
             
            +namespace Bar {
            +  int spam();
            +}
            - - - -

            If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace @@ -2025,11 +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.

            - - - - -

            36.3.12 C++ templates

            +

            38.3.12 C++ templates

            C++ templates don't present a huge problem for SWIG. However, @@ -2037,43 +1192,41 @@ in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

            - - - -
            -
            %module example

            %{
            #include "pair.h"
            %}

            template<class T1, class T2>
            struct pair {
            typedef T1 first_type;
            typedef T2 second_type;
            T1 first;
            T2 second;
            pair();
            pair(const T1&, const T2&);
            ~pair();
            };

            %template(Pairii) pair<int,int>;
            - - +
            %module example
             
            +%{
            +#include "pair.h"
            +%}
             
            +template<class T1, class T2>
            +struct pair {
            +  typedef T1 first_type;
            +  typedef T2 second_type;
            +  T1 first;
            +  T2 second;
            +  pair();
            +  pair(const T1&, const T2&);
            +  ~pair();
            +};
             
            +%template(Pairii) pair<int,int>;
            - - - -

            In Ruby:

            - - - -
            -
            irb(main):001:0> require 'example'
            true
            irb(main):002:0> p = Example::Pairii.new(3, 4)
            #<Example:Pairii:0x4016f4df>
            irb(main):003:0> p.first
            3
            irb(main):004:0> p.second
            4
            - - - - - +
            irb(main):001:0> require 'example'
            +true
            +irb(main):002:0> p = Example::Pairii.new(3, 4)
            +#<Example:Pairii:0x4016f4df>
            +irb(main):003:0> p.first
            +3
            +irb(main):004:0> p.second
            +4
            - - - - -

            36.3.13 C++ Standard Template Library (STL)

            +

            38.3.13 C++ Standard Template Library (STL)

            On a related note, the standard SWIG library contains a @@ -2086,658 +1239,245 @@ convenient for users of your extension module to pass Ruby objects of standard C++ templates. For example, suppose the C++ library you're wrapping has a function that expects a vector of floats:

            - - - -
            -
            %module example

            float sum(const std::vector<float>& values);
            - - - - +
            %module example
             
            +float sum(const std::vector<float>& values);
            - - - -

            Rather than go through the hassle of writing an "in" typemap to convert an array of Ruby numbers into a std::vector<float>, you can just use the std_vector.i module from the standard SWIG library:

            - - - -
            -
            %module example

            %include std_vector.i
            float sum(const std::vector<float>& values);
            - - - - +
            %module example
             
            +%include std_vector.i
            +float sum(const std::vector<float>& values);
            - - - -

            Ruby's STL wrappings provide additional methods to make them behave more similarly to Ruby's native classes.

            - - - -

            Thus, you can do, for example:

            - - - -
            -
            v = IntVector.new
            v << 2

            v << 3
            v << 4
            v.each { |x| puts x }

            => 2

            3
            4
            v.delete_if { |x| x == 3 }
            => [2,4]
            - - - - +
            v = IntVector.new
            +v << 2
            +v << 3
            +v << 4
            +v.each { |x| puts x }
             
            +=> 2
            +3
            +4
            +v.delete_if { |x| x == 3 }
            +=> [2,4]
            - - - -

            The SWIG Ruby module provides also the ability for all the STL containers to carry around Ruby native objects (Fixnum, Classes, etc) -making them act almost like Ruby's own Array, Hash, etc.   To +making them act almost like Ruby's own Array, Hash, etc. To do that, you need to define a container that contains a swig::GC_VALUE, like:

            +
            +%module nativevector
             
            +%{
            +std::vector< swig::GC_VALUE > NativeVector;
            +%}
             
            -
            -
            -
            %module -nativevector
            - - - - - -
            - - - - - -%{
            - - - - - -std::vector< swig::GC_VALUE > NativeVector;
            - - - - - -%}
            - - - - - -
            - - - - - -%template(NativeVector) std::vector< swig::GC_VALUE >;
            - - - - - +%template(NativeVector) std::vector< swig::GC_VALUE >; +
            - - - - -
            - - - - -

            This vector can then contain any Ruby object, making them almost identical to Ruby's own Array class.

            +
            +
            require 'nativevector'
            +include NativeVector
             
            +v = NativeVector.new
            +v << 1
            +v << [1,2]
            +v << 'hello'
             
            +class A; end
             
            +v << A.new
             
            -
            require 'nativevector'
            - - - - - -include NativeVector
            - - - - - -
            - - - - - -v = NativeVector.new
            - - - - - -v << 1
            - - - - - -v << -[1,2]
            - - - - - -v << -'hello'
            - - - - - -
            - - - - - -class A; end
            - - - - - -
            - - - - - -v << -A.new
            - - - - - -
            - - - - - -puts v
            - - - - - -=> -[1, [1,2], 'hello', #<A:0x245325>]
            - - - - - -
            - - - - +puts v +=> [1, [1,2], 'hello', #<A:0x245325>] +
            +

            Obviously, there is a lot more to template wrapping than shown in these examples. More details can be found in the SWIG and C++ chapter.

            - - - - -

            36.3.14 C++ STL Functors

            +

            38.3.14 C++ STL Functors

            Some containers in the STL allow you to modify their default behavior by using so called functors or function objects. - Functors are often just a very simple struct with operator() -redefined or an actual C/C++ function.  This allows you, for +Functors are often just a very simple struct with operator() +redefined or an actual C/C++ function. This allows you, for example, to always keep the sort order of a STL container to your liking.

            - - - -

            The Ruby STL mappings allows you to modify those containers that support functors using Ruby procs or methods, instead. - Currently, -this includes std::set, -set::map, -std::multiset -and std::multimap.

            +Currently, +this includes std::set, +set::map, +std::multiset +and std::multimap.

            +

            The functors in swig are called swig::UnaryFunction +and swig::BinaryFunction. - - - -

            The functors in swig are called swig::UnaryFunction -and swig::BinaryFunction.
            - - - - - -For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate -and swig::BinaryPredicate +For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate +and swig::BinaryPredicate are provided.

            - - - -

            As an example, if given this swig file:

            +
            +%module intset;
             
            +%include <std_set.i>
             
            -
            -
            -
            %module -intset;
            - - - - - -
            - - - - - -%include <std_set.i>
            - - - - - -
            - - - - - -%typemap(IntSet)  std::set< int, swig::BinaryPredicate ->;
            - - - - +%template(IntSet) std::set< int, swig::BinaryPredicate >; +

            You can then use the set from Ruby with or without a proc object as a predicate:

            +
            +require 'intset'
            +include Intset
             
            -
            -
            -
            -
            require -'intset'
            - - - - - -include Intset
            - - - - - -
            - - - - - -# Default sorting behavior defined in C++
            - - - - - -a = IntSet.new
            - - - - - -a << 1
            - - - - - -a << 2
            - - - - - -a << 3
            - - - - - -a
            - - - - - -=> - [1,2,3]
            - - - - - -
            - - - - +# Default sorting behavior defined in C++ +a = IntSet.new +a << 1 +a << 2 +a << 3 +a +=> [1,2,3] # Custom sorting behavior defined by a Ruby proc -
            b = IntSet.new( proc { -|a,b| a > b } )
            - - - - - -b << 1
            - - - - - -b << 2
            - - - - - -b << 3
            - - - - - -b
            - - - - - -=> - [3,2,1]
            - - - - - +b = IntSet.new( proc { |a,b| a > b } ) +b << 1 +b << 2 +b << 3 +b +=> [3,2,1] +
            +

            38.3.15 C++ STL Iterators

            - - -

            36.3.15 C++ STL Iterators

            - - -

            The STL is well known for the use of iterators.  There +

            The STL is well known for the use of iterators. There are a number of iterators possible with different properties, but in general there are two main categories: const iterators and non-const -iterators.  The const iterators can access and not modify the +iterators. The const iterators can access and not modify the values they point at, while the non-const iterators can both read and modify the values.

            - - - -

            The Ruby STL wrappings support both type of iterators by using -a proxy class in-between.  This proxy class is swig::Iterator or -swig::ConstIterator.  Derived from them are template +a proxy class in-between. This proxy class is swig::Iterator or +swig::ConstIterator. Derived from them are template classes that need to be initialized with the actual iterator for the container you are wrapping and often times with the beginning and -ending points of the iteration range. 

            - - - - +ending points of the iteration range.

            The SWIG STL library already provides typemaps to all the standard containers to do this wrapping automatically for you, but if you have your own STL-like iterator, you will need to write your own -typemap for them.  For out typemaps, the special functions make_const_iterator and make_nonconst_iterator are provided.

            +typemap for them. For out typemaps, the special functions make_const_iterator and make_nonconst_iterator are provided.

            These can be used either like:

            -
            make_const_iterator( iterator, rubyclass );
            +
            +make_const_iterator( iterator, rubyclass );
            +make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );
            +
            -make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );
            - - - - - -

            The iterators support a next() and previous() member function to -just change the iterator without returning anything.  previous() -should obviously only be used for bidirectional iterators.  You +

            The iterators support a next() and previous() member function to +just change the iterator without returning anything. previous() +should obviously only be used for bidirectional iterators. You can also advance the iterator multiple steps by using standard math -operations like +=.

            +operations like +=.

            The -value the iterator points at can be accessed with value() -- this is equivalent to dereferencing it with *i. -  For non-const iterators, a value=() function +value the iterator points at can be accessed with value() -- this is equivalent to dereferencing it with *i. + For non-const iterators, a value=() function is also provided which allows you to change the value pointed by the -iterator.  This is equivalent to the C++ construct of dereferencing and assignment, like *i = something

            - - - - +iterator. This is equivalent to the C++ construct of dereferencing and assignment, like *i = something.

            Thus, given say a vector class of doubles defined as:

            +
            +
            +%module doublevector
             
            +%include std_vector.i
             
            -
            -
            -
            %module doublevector
            - - - - - -
            - - - - - -%include std_vector.i

            - - - - - -
            - - - - - -%template(DoubleVector) std::vector<double>;
            - - - - +%template(DoubleVector) std::vector<double>; +
            +

            Its iterator can then be used from Ruby like:

            +
            +
            +require 'doublevector'
            +include Doublevector
             
            +v = DoubleVector.new
            +v << 1
            +v << 2
            +v << 3
             
            +#
            +# an elaborate and less efficient way of doing v.map! { |x| x+2 }
            +#
            +i = v.begin
            +e = v.end
            +while i != e
            +  val = i.value
            +  val += 2
            +  i.value = val
            +  i.next
            +end
            +i
            +>> [3, 4, 5 ]
            +
            +
            +

            If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

            -
            require -'doublevector'
            +

            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. +

            -include Doublevector
            -
            - - - - - -v = DoubleVector.new
            - - - - - -v << 1
            - - - - - -v << 2
            - - - - - -v << 3
            - -
            - -#
            - -# an elaborate and less efficient way of doing v.map! { |x| x+2 }
            - -#
            - - - - - -i = v.begin
            - - - - - -e = v.end
            - - - - - -while i != e
            - - - - - -  val = i.value
            - - - - - -  val += 2
            - - - - - -  i.value = val
            - - - - - -  i.next
            - - - - - -end
            - - - - -i
            - - - - ->> [3, 4, 5 ]
            - - - - - -
            - -

            If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

            - - - - - -

            36.3.16 C++ Smart Pointers

            +

            38.3.16.2 Generic Smart Pointers

            In certain C++ programs, it is common to use classes that @@ -2745,124 +1485,64 @@ have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:

            - - - -
            -
            template<class T> class SmartPtr {
            ...
            T *operator->();
            ...
            }
            - - - - - +
            template<class T> class SmartPtr {
            +  ...
            +  T *operator->();
            +  ...
            +}
            - - - -

            Then, if you have a class like this,

            - - - -
            -
            class Foo {
            public:
            int x;
            int bar();
            };
            - - - - - +
            class Foo {
            +public:
            +  int x;
            +  int bar();
            +};
            - - - -

            A smart pointer would be used in C++ as follows:

            - - - -
            -
            SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
            ...
            p->x = 3; // Foo::x
            int y = p->bar(); // Foo::bar
            - - - - - +
            SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
            +...
            +p->x = 3; // Foo::x
            +int y = p->bar(); // Foo::bar
            - - - -

            To wrap this in Ruby, simply tell SWIG about the SmartPtr class and the low-level Foo object. Make sure you instantiate SmartPtr using %template if necessary. For example:

            - - - -
            -
            %module example
            ...
            %template(SmartPtrFoo) SmartPtr<Foo>;
            ...
            - - - - - +
            %module example
            +...
            +%template(SmartPtrFoo) SmartPtr<Foo>;
            +...
            - - - -

            Now, in Ruby, everything should just "work":

            - - - -
            -
            irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow
            #<Example::SmartPtrFoo:0x4016f4df>
            irb(main):002:0> p.x = 3 # Foo::x
            3
            irb(main):003:0> p.bar() # Foo::bar
            - - - - - +
            irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow
            +#<Example::SmartPtrFoo:0x4016f4df>
            +irb(main):002:0> p.x = 3 # Foo::x
            +3
            +irb(main):003:0> p.bar() # Foo::bar
            - - - -

            If you ever need to access the underlying pointer returned by operator->() itself, simply use the __deref__() method. For example:

            - - - -
            -
            irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
            - - - - - +
            irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
            - - - - -

            36.3.17 Cross-Language Polymorphism

            +

            38.3.17 Cross-Language Polymorphism

            SWIG's Ruby module supports cross-language polymorphism @@ -2871,11 +1551,7 @@ module. Rather than duplicate the information presented in the 36.3.17.1 Exception Unrolling +

            38.3.17.1 Exception Unrolling

            Whenever a C++ director class routes one of its virtual @@ -2887,33 +1563,18 @@ change this behavior, you can use the %feature("director:except") directive to indicate what action should be taken when a Ruby exception is raised. The following code should suffice in most cases:

            - - - -
            -
            %feature("director:except") {
            throw Swig::DirectorMethodException($error);
            }
            - - - - - +
            %feature("director:except") {
            +  throw Swig::DirectorMethodException($error);
            +}
            - - - -

            When this feature is activated, the call to the Ruby instance method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.

            - - - - -

            36.4 Naming

            +

            38.4 Naming

            Ruby has several common naming conventions. Constants are @@ -2921,95 +1582,37 @@ generally in upper case, module and class names are in camel case and methods are in lower case with underscores. For example:

            - - - -
              - - - - -
            • MATH::PI is a constant name
            • - - - - -
            • MyClass is a class name
            • - - - - -
            • my_method is a method name
            • - - - - -
            - - - - -
            - - - -

            Prior to version 1.3.28, SWIG did not support these Ruby conventions. The only modifications it made to names was to capitalize the first letter of constants (which includes module and class names).

            - - - -

            SWIG 1.3.28 introduces the new -autorename command line parameter. When this parameter is specified, SWIG will automatically change constant, class and method names to conform with the standard Ruby naming conventions. For example:

            - - - -
            -
            $ swig -ruby -autorename example.i
            +
            $ swig -ruby -autorename example.i
             
            - - - - -
            - - - -

            To disable renaming use the -noautorename command line option.

            - - - -

            Since this change significantly changes the wrapper code generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.

            - - - - -

            36.4.1 Defining Aliases

            +

            38.4.1 Defining Aliases

            It's a fairly common practice in the Ruby built-ins and @@ -3020,65 +1623,51 @@ approach is to use SWIG's %extend directive to add a new method of the aliased name that calls the original function. For example:

            - - - -
            -
            class MyArray {
            public:
            // Construct an empty array
            MyArray();

            // Return the size of this array
            size_t length() const;
            };

            %extend MyArray {
            // MyArray#size is an alias for MyArray#length
            size_t size() const {
            return $self->length();
            }
            }
            - - - +
            class MyArray {
            +public:
            +  // Construct an empty array
            +  MyArray();
             
            +  // Return the size of this array
            +  size_t length() const;
            +};
             
            +%extend MyArray {
            +  // MyArray#size is an alias for MyArray#length
            +  size_t size() const {
            +    return $self->length();
            +  }
            +}
            + 
            - - - -

            A better solution is to use the %alias directive (unique to SWIG's Ruby module). The previous example could then be rewritten as:

            - - - -
            -
            // MyArray#size is an alias for MyArray#length
            %alias MyArray::length "size";

            class MyArray {
            public:
            // Construct an empty array
            MyArray();

            // Return the size of this array
            size_t length() const;
            };

            - - - - +
            // MyArray#size is an alias for MyArray#length
            +%alias MyArray::length "size";
             
            +class MyArray {
            +public:
            +  // Construct an empty array
            +  MyArray();
            + 
            +  // Return the size of this array
            +  size_t length() const;
            +};
            - - - -

            Multiple aliases can be associated with a method by providing a comma-separated list of aliases to the %alias directive, e.g.

            - - - -
            %alias MyArray::length "amount,quantity,size";
            - - - - -
            - - - -

            From an end-user's standpoint, there's no functional difference between these two approaches; i.e. they should get the same result from calling either MyArray#size or MyArray#length. @@ -3087,21 +1676,13 @@ doesn't need to generate all of the wrapper code that's usually associated with added methods like our MyArray::size() example.

            - - - -

            Note that the %alias directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

            - - - - -

            36.4.2 Predicate Methods

            +

            38.4.2 Predicate Methods

            Ruby methods that return a boolean value and end in a @@ -3114,83 +1695,43 @@ if the object is an instance of the specified class). For consistency with Ruby conventions, methods that return boolean values should be marked as predicate methods.

            - - - -

            One cumbersome solution to this problem is to rename the method (using SWIG's %rename directive) and provide a custom typemap that converts the function's actual return type to Ruby's true or false. For example:

            - - - -
            -
            %rename("is_it_safe?") is_it_safe();

            %typemap(out) int is_it_safe
            "$result = ($1 != 0) ? Qtrue : Qfalse;";

            int is_it_safe();

            - - - +
            %rename("is_it_safe?") is_it_safe();
             
            +%typemap(out) int is_it_safe "$result = ($1 != 0) ? Qtrue : Qfalse;";
             
            +int is_it_safe();
            - - - -

            A better solution is to use the %predicate directive (unique to SWIG's Ruby module) to designate a method as a predicate method. For the previous example, this would look like:

            - - - -
            -
            %predicate is_it_safe();

            int is_it_safe();

            - - - - +
            %predicate is_it_safe();
             
            +int is_it_safe();
            - - - -

            This method would be invoked from Ruby code like this:

            - - - -
            -
            irb(main):001:0> Example::is_it_safe?
            true

            - - - - - +
            irb(main):001:0> Example::is_it_safe?
            +true
            - - - -

            The %predicate directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

            - - - - -

            36.4.3 Bang Methods

            +

            38.4.3 Bang Methods

            Ruby methods that modify an object in-place and end in an @@ -3201,384 +1742,205 @@ which returns a copy of the array with the items sorted instead of modifying the original array. For consistency with Ruby conventions, methods that modify objects in place should be marked as bang methods.

            - - - -

            Bang methods can be marked using the %bang directive which is unique to the Ruby module and was introduced in SWIG 1.3.28. For example:

            - - - -
            -
            %bang sort!(arr);

            int sort(int arr[]);
            - - - - +
            %bang sort(int arr[]);
             
            +int sort(int arr[]); 
            - - - -

            This method would be invoked from Ruby code like this:

            - - - -
            irb(main):001:0> Example::sort!(arr)
            - - - - -
            - - - -

            The %bang directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

            - - - - -

            36.4.4 Getters and Setters

            +

            38.4.4 Getters and Setters

            Often times a C++ library will expose properties through getter and setter methods. For example:

            - - - -
            -
            class Foo {
            Foo() {}

            int getValue() { return value_; }

            void setValue(int value) { value_ = value; }

            private:
            int value_;
            };
            - - - - +
            class Foo {
            +  Foo() {}
            +  int getValue() { return value_; }
            +  void setValue(int value) { value_ = value; }
             
            +private:
            +  int value_;
            +};
            - - - -

            By default, SWIG will expose these methods to Ruby as get_value and set_value. However, it more natural for these methods to be exposed in Ruby as value and value=. That allows the methods to be used like this:

            - - - -
            -
            irb(main):001:0> foo = Foo.new()
            irb(main):002:0> foo.value = 5
            irb(main):003:0> puts foo.value
            - - - - - +
            irb(main):001:0> foo = Foo.new()
            +irb(main):002:0> foo.value = 5
            +irb(main):003:0> puts foo.value
            - - - -

            This can be done by using the %rename directive:

            - - - -
            -
            %rename("value") Foo::getValue();
            %rename("value=") Foo::setValue(int value);
            - - - - - +
            %rename("value") Foo::getValue();
            +%rename("value=") Foo::setValue(int value);
            - - - - -

             

            - - - - - -

            36.5 Input and output parameters

            +

            38.5 Input and output parameters

            A common problem in some C programs is handling parameters passed as simple pointers. For example:

            - - - -
            -
            void add(int x, int y, int *result) {
            *result = x + y;
            }
            or
            int sub(int *x, int *y) {
            return *x-*y;
            }
            - - - - - +
            void add(int x, int y, int *result) {
            +  *result = x + y;
            +}
            +

            +or +

            - - +
            +
            +int sub(int *x, int *y) {
            +  return *x-*y;
            +}
            +

            The easiest way to handle these situations is to use the typemaps.i file. For example:

            - - - -
            -
            %module Example
            %include "typemaps.i"

            void add(int, int, int *OUTPUT);
            int sub(int *INPUT, int *INPUT);
            - - - - +
            %module Example
            +%include "typemaps.i"
             
            +void add(int, int, int *OUTPUT);
            +int sub(int *INPUT, int *INPUT);
            - - - -

            In Ruby, this allows you to pass simple values. For example:

            - - - -
            -
            a = Example.add(3,4)
            puts a
            7
            b = Example.sub(7,4)
            puts b
            3
            - - - - - +
            a = Example.add(3,4)
            +puts a
            +7
            +b = Example.sub(7,4)
            +puts b
            +3
            - - - -

            Notice how the INPUT parameters allow integer values to be passed instead of pointers and how the OUTPUT parameter creates a return result.

            - - - -

            If you don't want to use the names INPUT or OUTPUT, use the %apply directive. For example:

            - - - -
            -
            %module Example
            %include "typemaps.i"

            %apply int *OUTPUT { int *result };
            %apply int *INPUT { int *x, int *y};

            void add(int x, int y, int *result);
            int sub(int *x, int *y);
            - - - +
            %module Example
            +%include "typemaps.i"
             
            +%apply int *OUTPUT { int *result };
            +%apply int *INPUT { int *x, int *y};
             
            +void add(int x, int y, int *result);
            +int sub(int *x, int *y);
            - - - -

            If a function mutates one of its parameters like this,

            - - - -
            -
            void negate(int *x) {
            *x = -(*x);
            }
            - - - - - +
            void negate(int *x) {
            + *x = -(*x);
            +}
            - - - -

            you can use INOUT like this:

            - - - -
            -
            %include "typemaps.i"
            ...
            void negate(int *INOUT);
            - - - - - +
            %include "typemaps.i"
            +...
            +void negate(int *INOUT);
            - - - -

            In Ruby, a mutated parameter shows up as a return value. For example:

            - - - -
            -
            a = Example.negate(3)
            print a
            -3

            - - - - - +
            a = Example.negate(3)
            +print a
            +-3
            - - - -

            The most common use of these special typemap rules is to handle functions that return more than one value. For example, sometimes a function returns a result as well as a special error code:

            - - - -
            -
            /* send message, return number of bytes sent, success code, and error_code */
            int send_message(char *text, int *success, int *error_code);
            - - - - - +
            /* send message, return number of bytes sent, success code, and error_code */
            +int send_message(char *text, int *success, int *error_code);
            - - - -

            To wrap such a function, simply use the OUTPUT rule above. For example:

            - - - -
            -
            %module example
            %include "typemaps.i"
            ...
            int send_message(char *, int *OUTPUT, int *OUTPUT);
            - - - - - +
            %module example
            +%include "typemaps.i"
            +...
            +int send_message(char *, int *OUTPUT, int *OUTPUT);
            - - - -

            When used in Ruby, the function will return an array of multiple values.

            - - - -
            -
            bytes, success, error_code = send_message("Hello World")
            if not success
            print "error #{error_code} : in send_message"
            else
            print "Sent", bytes
            end
            - - - - - +
            bytes, success, error_code = send_message("Hello World")
            +if not success
            +  print "error #{error_code} : in send_message"
            +else
            +  print "Sent", bytes
            +end
            - - - -

            Another way to access multiple return values is to use the %apply rule. In the following example, the parameters rows and columns are related to SWIG as OUTPUT values through the use of %apply

            - - - -
            -
            %module Example
            %include "typemaps.i"
            %apply int *OUTPUT { int *rows, int *columns };
            ...
            void get_dimensions(Matrix *m, int *rows, int*columns);
            - - - - - +
            %module Example
            +%include "typemaps.i"
            +%apply int *OUTPUT { int *rows, int *columns };
            +...
            +void get_dimensions(Matrix *m, int *rows, int*columns);
            - - - -

            In Ruby:

            - - - -
            -
            r, c = Example.get_dimensions(m)
            - - - - - +
            r, c = Example.get_dimensions(m)
            +

            38.6 Exception handling

            - - -

            36.6 Exception handling

            - - -

            36.6.1 Using the %exception directive

            +

            38.6.1 Using the %exception directive

            The SWIG %exception directive can be @@ -3587,1013 +1949,317 @@ C/C++ errors into Ruby exceptions. The chapter on -

            class DoubleArray {
            private:
            int n;
            double *ptr;
            public:
            // Create a new array of fixed size
            DoubleArray(int size) {
            ptr = new double[size];
            n = size;
            }

            // Destroy an array
            ~DoubleArray() {
            delete ptr;
            }

            // Return the length of the array
            int length() {
            return n;
            }

            // Get an array item and perform bounds checking.
            double getitem(int i) {
            if ((i >= 0) && (i < n))
            return ptr[i];
            else
            throw RangeError();
            }

            // Set an array item and perform bounds checking.
            void setitem(int i, double val) {
            if ((i >= 0) && (i < n))
            ptr[i] = val;
            else {
            throw RangeError();
            }
            }
            };
            - - - - - +
            class DoubleArray {
            +private:
            +  int n;
            +  double *ptr;
            +public:
            +  // Create a new array of fixed size
            +  DoubleArray(int size) {
            +    ptr = new double[size];
            +    n = size;
            +  }
            + 
            +  // Destroy an array
            +  ~DoubleArray() {
            +    delete ptr;
            +  } 
            + 
            +  // Return the length of the array
            +  int length() {
            +    return n;
            +  }
            + 
            +  // Get an array item and perform bounds checking.
            +  double getitem(int i) {
            +    if ((i >= 0) && (i < n))
            +      return ptr[i];
            +    else
            +      throw RangeError();
            +  }
            + 
            +  // Set an array item and perform bounds checking.
            +  void setitem(int i, double val) {
            +    if ((i >= 0) && (i < n))
            +      ptr[i] = val;
            +    else {
            +      throw RangeError();
            +    }
            +  }
            +};
      - - - -

      Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the Ruby extension by writing the following in an interface file:

      - - - -
      -
      %exception {
      try {
      $action
      }
      catch (const RangeError&) {
      static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      rb_raise(cpperror, "Range error.");
      }
      }

      class DoubleArray {
      ...
      };
      - - - - +
      %exception {
      +  try {
      +    $action
      +  }
      +  catch (const RangeError&) {
      +    static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      +    rb_raise(cpperror, "Range error.");
      +  }
      +}
       
      +class DoubleArray {
      +  ...
      +};
      - - - -

      The exception handling code is inserted directly into generated wrapper functions. When an exception handler is defined, errors can be caught and used to gracefully raise a Ruby exception instead of forcing the entire program to terminate with an uncaught error.

      - - - -

      As shown, the exception handling code will be added to every wrapper function. Because this is somewhat inefficient, you might consider refining the exception handler to only apply to specific methods like this:

      - - - -
      -
      %exception getitem {
      try {
      $action
      }
      catch (const RangeError&) {
      static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      rb_raise(cpperror, "Range error in getitem.");
      }
      }

      %exception setitem {
      try {
      $action
      }
      catch (const RangeError&) {
      static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      rb_raise(cpperror, "Range error in setitem.");
      }
      }
      - - - - - +
      %exception getitem {
      +  try {
      +    $action
      +  } catch (const RangeError&) {
      +    static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      +    rb_raise(cpperror, "Range error in getitem.");
      +  }
      +}
      + 
      +%exception setitem {
      +  try {
      +    $action
      +  } catch (const RangeError&) {
      +    static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      +    rb_raise(cpperror, "Range error in setitem.");
      +  }
      +}
      - - - -

      In this case, the exception handler is only attached to methods and functions named getitem and setitem.

      - - - -

      Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling. See the chapter on Customization Features for more examples.

      - - - - -

      36.6.2 Handling Ruby Blocks

      +

      38.6.2 Handling Ruby Blocks

      One of the highlights of Ruby and most of its standard library is the use of blocks, which allow the easy creation of continuations and -other niceties.  Blocks in ruby are also often used to +other niceties. Blocks in ruby are also often used to simplify the passing of many arguments to a class.

      - - - -

      In order to make your class constructor support blocks, you can take advantage of the %exception directive, which will get run -after the C++ class' constructor was called. 

      - - - - +after the C++ class' constructor was called.

      For example, this yields the class over after its construction: -
      - - - - -

      - - - -
      -
      class Window
      {
      public:
      Window(int x, int y, int w, int h);
      // .... other methods here ....
      };

      // Add support for yielding self in the Class' constructor.
      %exception Window::Window {
      $action
      if (rb_block_given_p()) {
      rb_yield(self);
      }
      }
      - - - - +
      class Window
      +{
      +public:
      +  Window(int x, int y, int w, int h);
      +  // .... other methods here ....
      +};
       
      +// Add support for yielding self in the Class' constructor.
      +%exception Window::Window {
      +  $action
      +  if (rb_block_given_p()) {
      +    rb_yield(self);
      +  }
      +}
      - - - -

      Then, in ruby, it can be used like:

      - - - - -
      Window.new(0,0,360,480) -{ |w|
      - - - - - -    w.color = Fltk::RED
      - - - - - -    w.border = false
      - - - - - -}
      - - - - - -
      - - - - +
      +Window.new(0,0,360,480) { |w|
      +  w.color = Fltk::RED
      +  w.border = false
      +}
      +
      +

      For other methods, you can usually use a dummy parameter with a special in typemap, like:

      - - - - -
      //
      - - - - - -// original function was:
      - - - - - -//
      - - - - - -// void func(int x);
      - - - - - -
      - - - - - -%typemap(in,numinputs=0) int RUBY_YIELD_SELF {
      - - - - - -     if ( !rb_block_given_p() )
      - - - - - -            -rb_raise("No block given");
      - - - - - -     return rb_yield(self);
      - - - - - -}
      - - - - - -
      - - - - - -%extend {
      - - - - - -        void func(int x, int -RUBY_YIELD_SELF );
      - - - - - -}
      - - - - +
      +//
      +// original function was:
      +//
      +// void func(int x);
      +
      +%typemap(in,numinputs=0) int RUBY_YIELD_SELF {
      +  if ( !rb_block_given_p() )
      +    rb_raise("No block given");
      +  return rb_yield(self);
      +}
      +
      +%extend {
      +  void func(int x, int RUBY_YIELD_SELF );
      +}
      +
      +

      For more information on typemaps, see Typemaps.

      - -

      36.6.3 Raising exceptions

      +

      38.6.3 Raising exceptions

      There are three ways to raise exceptions from C++ code to Ruby.

      - - - -

      The first way is to use SWIG_exception(int code, const char *msg). The following table shows the mappings from SWIG error codes to Ruby exceptions:

      - - - -
    • - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      - - - - +
      SWIG_MemoryError
      - - - - -
      - - - - +
      rb_eNoMemError
      - - - - -
      - - - - +
      SWIG_IOError
      - - - - -
      - - - - +
      rb_eIOError
      - - - - -
      - - - - +
      SWIG_RuntimeError
      - - - - -
      - - - - +
      rb_eRuntimeError
      - - - - -
      - - - - +
      SWIG_IndexError
      - - - - -
      - - - - +
      rb_eIndexError
      - - - - -
      - - - - +
      SWIG_TypeError
      - - - - -
      - - - - +
      rb_eTypeError
      - - - - -
      - - - - +
      SWIG_DivisionByZero
      - - - - -
      - - - - +
      rb_eZeroDivError
      - - - - -
      - - - - +
      SWIG_OverflowError
      - - - - -
      - - - - +
      rb_eRangeError
      - - - - -
      - - - - +
      SWIG_SyntaxError
      - - - - -
      - - - - +
      rb_eSyntaxError
      - - - - -
      - - - - +
      SWIG_ValueError
      - - - - -
      - - - - +
      rb_eArgError
      - - - - -
      - - - - +
      SWIG_SystemError
      - - - - -
      - - - - +
      rb_eFatal
      - - - - -
      - - - - +
      SWIG_AttributeError
      - - - - -
      - - - - +
      rb_eRuntimeError
      - - - - -
      - - - - +
      SWIG_NullReferenceError
      - - - - -
      - - - - +
      rb_eNullReferenceError*
      - - - - -
      - - - - +
      SWIG_ObjectPreviouslyDeletedError
      - - - - -
      - - - - +
      rb_eObjectPreviouslyDeleted*
      - - - - -
      - - - - +
      SWIG_UnknownError
      - - - - -
      - - - - +
      rb_eRuntimeError
      - - - - -
      - - - -
      * These error classes are created by SWIG and are not built-in Ruby exception classes
      - - - - -
      - - - - - - - - -

      The second way to raise errors is to use SWIG_Raise(obj, type, desc). Obj is a C++ instance of an exception class, type is a string specifying the type of exception (for example, "MyError") and desc is the SWIG description of the exception class. For example:

      - - - - -
      -%raise(SWIG_NewPointerObj(e, -SWIGTYPE_p_AssertionFailedException, -0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);
      - - - - +
      +%raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);
      +

      This is useful when you want to pass the current exception object @@ -4601,21 +2267,13 @@ directly to Ruby, particularly when the object is an instance of class marked as an %exceptionclass (see the next section for more information).

      - - - -

      Last, you can raise an exception by directly calling Ruby's C api. This is done by invoking the rb_raise() function. The first argument passed to rb_raise() is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.

      - - - - -

      36.6.4 Exception classes

      +

      38.6.4 Exception classes

      Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -4625,185 +2283,115 @@ directive are exposed in Ruby as child classes of rb_eRuntimeError. This allows C++ exceptions to be directly mapped to Ruby exceptions, providing for a more natural integration between C++ code and Ruby code.

      - - - -
      -
      	%exceptionclass CustomError;

      %inline %{
      class CustomError { };

      class Foo {
      public:
      void test() { throw CustomError; }
      };
      }
      - - - +
      %exceptionclass CustomError;
       
      +%inline %{
      +  class CustomError { };
       
      +  class Foo { 
      +  public:
      +    void test() { throw CustomError; }
      +  };
      +%}
      - - - -

      From Ruby you can now call this method like this:

      - - - -
      -
      foo = Foo.new
      begin
      foo.test()
      rescue CustomError => e
      puts "Caught custom error"
      end
      - - - - - +
      foo = Foo.new
      +begin
      +  foo.test()
      +rescue CustomError => e
      +  puts "Caught custom error"
      +end 
      - - - - -

      For another example look at swig/Examples/ruby/exception_class.
      - - - - - +

      For another example look at swig/Examples/ruby/exception_class.

      - - - - -

      36.7 Typemaps

      +

      38.7 Typemaps

      This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Ruby C API as well as the material in the "Typemaps" -chapter.  +chapter.

      - - - -

      Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.

      - - - - -

      36.7.1 What is a typemap?

      +

      38.7.1 What is a typemap?

      A typemap is nothing more than a code generation rule that is attached to a specific C datatype. The general form of this declaration is as follows ( parts enclosed in [...] are optional -):    

      - - - - - -
      %typemap( method [, modifiers...] ) typelist -code;
      - - - +):

      +
      +
      +%typemap( method [, modifiers...] ) typelist code;
      +
      +

      method is a simply a name that specifies what kind of typemap is being defined. It is usually a name like "in", "out", or "argout" (or its director variations). The purpose of these methods is described later.

      - - - -

      modifiers is an optional comma separated list of name="value" values. These are sometimes to attach extra information to a typemap and is often target-language dependent.

      - - - -

      typelist is a list of the C++ type patterns that the typemap will match. The general form of this list is as follows:

      - - - -
      -
      typelist : typepattern [, typepattern, typepattern, ... ] ;

      typepattern : type [ (parms) ]
      | type name [ (parms) ]
      | ( typelist ) [ (parms) ]
      - - - - +
      typelist : typepattern [, typepattern, typepattern, ... ] ;
       
      +typepattern : type [ (parms) ]
      +  | type name [ (parms) ]
      +  | ( typelist ) [ (parms) ]
      - - - -

      Each type pattern is either a simple type, a simple type and argument name, or a list of types in the case of multi-argument typemaps. In addition, each type pattern can be parameterized with a list of temporary variables (parms). The purpose of these variables will be explained shortly.

      - - - -

      code specifies the C code used in the typemap. It can take any one of the following forms:

      - - - -
      -
      code : { ... }
      | " ... "
      | %{ ... %}
      - - - - - +
      code : { ... }
      +  | " ... "
      +  | %{ ... %}
      - - - -

      For example, to convert integers from Ruby to C, you might define a typemap like this:

      - - - -
      -
      %module example

      %typemap(in) int {
      $1 = (int) NUM2INT($input);
      printf("Received an integer : %d\n",$1);
      }

      %inline %{
      extern int fact(int n);
      %}
      - - - +
      %module example
       
      +%typemap(in) int {
      +  $1 = (int) NUM2INT($input);
      +  printf("Received an integer : %d\n",$1);
      +}
       
      +%inline %{
      +  extern int fact(int n);
      +%}
      - - - -

      Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is @@ -4813,77 +2401,44 @@ prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int. The $input variable is the input Ruby object.

      - - - -

      When this example is compiled into a Ruby module, the following sample code:

      - - - -
      -
      require 'example'

      puts Example.fact(6)
      - - - - +
      require 'example'
       
      +puts Example.fact(6)
      - - - -

      prints the result:

      - - - -
      -
      Received an integer : 6
      720
      - - - - - +
      +Received an integer : 6
      +720
      +
      - - - -

      In this example, the typemap is applied to all occurrences of the int datatype. You can refine this by supplying an optional parameter name. For example:

      - - - -
      -
      %module example

      %typemap(in) int n {
      $1 = (int) NUM2INT($input);
      printf("n = %d\n",$1);
      }

      %inline %{
      extern int fact(int n);
      %}
      - - - +
      %module example
       
      +%typemap(in) int n {
      +  $1 = (int) NUM2INT($input);
      +  printf("n = %d\n",$1);
      +}
       
      +%inline %{
      +  extern int fact(int n);
      +%}
      - - - -

      In this case, the typemap code is only attached to arguments that exactly match "int n".

      - - - -

      The application of a typemap to specific datatypes and argument names involves more than simple text-matching--typemaps are fully integrated into the SWIG type-system. When you define a typemap @@ -4892,96 +2447,65 @@ and qualified variations such as const int. In addition, the typemap system follows typedef declarations. For example:

      - - - -
      -
      %typemap(in) int n {
      $1 = (int) NUM2INT($input);
      printf("n = %d\n",$1);
      }

      typedef int Integer;
      extern int fact(Integer n); // Above typemap is applied
      - - - - +
      %typemap(in) int n {
      +  $1 = (int) NUM2INT($input);
      +  printf("n = %d\n",$1);
      +}
       
      +typedef int Integer;
      +extern int fact(Integer n); // Above typemap is applied
      - - - -

      However, the matching of typedef only occurs in one direction. If you defined a typemap for Integer, it is not applied to arguments of type int.

      - - - -

      Typemaps can also be defined for groups of consecutive arguments. For example:

      - - - -
      -
      %typemap(in) (char *str, int len) {
      $1 = STR2CSTR($input);
      $2 = (int) RSTRING($input)->len;
      };

      int count(char c, char *str, int len);
      - - - - +
      %typemap(in) (char *str, int len) {
      +  $1 = StringValuePtr($input);
      +  $2 = (int) RSTRING($input)->len;
      +};
       
      +int count(char c, char *str, int len);
      - - - -

      When a multi-argument typemap is defined, the arguments are always handled as a single Ruby object. This allows the function count to be used as follows (notice how the length parameter is omitted):

      - - - -
      -
      puts Example.count('o','Hello World')
      2
      - - - - - +
      puts Example.count('o','Hello World')
      +2
      - - - - -

      36.7.2 Typemap scope

      +

      38.7.2 Typemap scope

      Once defined, a typemap remains in effect for all of the declarations that follow. A typemap may be redefined for different sections of an input file. For example:

      - - - -
      -
      // typemap1
      %typemap(in) int {
      ...
      }

      int fact(int); // typemap1
      int gcd(int x, int y); // typemap1

      // typemap2
      %typemap(in) int {
      ...
      }

      int isprime(int); // typemap2
      - - +
      // typemap1
      +%typemap(in) int {
      +  ...
      +}
       
      +int fact(int); // typemap1
      +int gcd(int x, int y); // typemap1
       
      +// typemap2
      +%typemap(in) int {
      +  ...
      +}
       
      +int isprime(int); // typemap2
      - - - -

      One exception to the typemap scoping rules pertains to the %extend declaration. %extend is used to attach new declarations to a class or structure definition. Because @@ -4989,250 +2513,152 @@ of this, all of the declarations in an %extend block are subject to the typemap rules that are in effect at the point where the class itself is defined. For example:

      - - - -
      -
      class Foo {
      ...
      };

      %typemap(in) int {
      ...
      }

      %extend Foo {
      int blah(int x); // typemap has no effect. Declaration is attached to Foo which
      // appears before the %typemap declaration.
      };
      - - - +
      class Foo {
      +  ...
      +};
       
      +%typemap(in) int {
      +  ...
      +}
       
      +%extend Foo {
      +  int blah(int x); // typemap has no effect. Declaration is attached to Foo which 
      +  // appears before the %typemap declaration.
      +};
      - - - - -

      36.7.3 Copying a typemap

      +

      38.7.3 Copying a typemap

      A typemap is copied by using assignment. For example:

      - - - -
      -
      %typemap(in) Integer = int;
      - - - - - +
      %typemap(in) Integer = int;
      - - - -

      or this:

      - - - -
      -
      %typemap(in) Integer, Number, int32_t = int;
      - - - - - +
      %typemap(in) Integer, Number, int32_t = int;
      - - - -

      Types are often managed by a collection of different typemaps. For example:

      - - - -
      -
      %typemap(in) int { ... }
      %typemap(out) int { ... }
      %typemap(varin) int { ... }
      %typemap(varout) int { ... }
      - - - - - +
      %typemap(in) int { ... }
      +%typemap(out) int { ... }
      +%typemap(varin) int { ... }
      +%typemap(varout) int { ... }
      - - - -

      To copy all of these typemaps to a new type, use %apply. For example:

      - - - -
      -
      %apply int { Integer }; // Copy all int typemaps to Integer
      %apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
      - - - - - +
      %apply int { Integer }; // Copy all int typemaps to Integer
      +%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
      - - - -

      The patterns for %apply follow the same rules as for %typemap. For example:

      - - - -
      -
      %apply int *output { Integer *output }; // Typemap with name
      %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
      - - - - - +
      %apply int *output { Integer *output }; // Typemap with name
      +%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
      - - - - -

      36.7.4 Deleting a typemap

      +

      38.7.4 Deleting a typemap

      A typemap can be deleted by simply defining no code. For example:

      - - - -
      -
      %typemap(in) int; // Clears typemap for int
      %typemap(in) int, long, short; // Clears typemap for int, long, short
      %typemap(in) int *output;
      - - - - - +
      %typemap(in) int; // Clears typemap for int
      +%typemap(in) int, long, short; // Clears typemap for int, long, short
      +%typemap(in) int *output; 
      - - - -

      The %clear directive clears all typemaps for a given type. For example:

      - - - -
      -
      %clear int; // Removes all types for int
      %clear int *output, long *output;
      - - - - - +
      %clear int; // Removes all types for int
      +%clear int *output, long *output;
      - - - -

      Note: Since SWIG's default behavior is defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.

      - - - - -

      36.7.5 Placement of typemaps

      +

      38.7.5 Placement of typemaps

      Typemap declarations can be declared in the global scope, within a C++ namespace, and within a C++ class. For example:

      - - - -
      -
      %typemap(in) int {
      ...
      }

      namespace std {
      class string;
      %typemap(in) string {
      ...
      }
      }

      class Bar {
      public:
      typedef const int & const_reference;
      %typemap(out) const_reference {
      ...
      }
      };
      - - - +
      %typemap(in) int {
      +  ...
      +}
       
      +namespace std {
      +  class string;
      +  %typemap(in) string {
      +    ...
      +  }
      +}
       
      +class Bar {
      +public:
      +  typedef const int & const_reference;
      +  %typemap(out) const_reference {
      +    ...
      +  }
      +};
      - - - -

      When a typemap appears inside a namespace or class, it stays in effect until the end of the SWIG input (just like before). However, the typemap takes the local scope into account. Therefore, this code

      - - - -
      -
      namespace std {
      class string;
      %typemap(in) string {
      ...
      }
      }
      - - - - - +
      namespace std {
      +  class string;
      +  %typemap(in) string {
      +    ...
      +  }
      +}
      - - - -

      is really defining a typemap for the type std::string. You could have code like this:

      - - - -
      -
      namespace std {
      class string;
      %typemap(in) string { /* std::string */
      ...
      }
      }

      namespace Foo {
      class string;
      %typemap(in) string { /* Foo::string */
      ...
      }
      }
      - - - - +
      namespace std {
      +  class string;
      +  %typemap(in) string { /* std::string */
      +  ...
      +  }
      +}
       
      +namespace Foo {
      +  class string;
      +  %typemap(in) string { /* Foo::string */
      +  ...
      +  }
      +}
      - - - -

      In this case, there are two completely distinct typemaps that apply to two completely different types (std::string and Foo::string).

      - - - -

      It should be noted that for scoping to work, SWIG has to know that string is a typename defined within a particular namespace. @@ -5240,537 +2666,153 @@ In this example, this is done using the class declaration class string .

      - - - - -

      36.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:

      - - - - -

      36.7.6.1  "in" typemap

      +

      38.7.6.1 "in" typemap

      Converts Ruby objects to input function arguments. For example:

      - - - -
      -
      %typemap(in) int {
      $1 = NUM2INT($input);
      }
      - - - - - +
      %typemap(in) int {
      +  $1 = NUM2INT($input);
      +}
      - - - -

      The following special variables are available:

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $input Input object + $input Input object holding value to be converted.
      $symname Name of + $symname Name of function/method being wrapped
      $1...n Argument being + $1...n Argument being sent to the function
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      - - - - -
      - - - -

      This is probably the most commonly redefined typemap because it can be used to implement customized conversions.

      - - - -

      In addition, the "in" typemap allows the number of converted arguments to be specified. For example:

      - - - -
      -
      // Ignored argument.
      %typemap(in, numinputs=0) int *out (int temp) {
      $1 = &temp;
      }
      - - - - - +
      // Ignored argument.
      +%typemap(in, numinputs=0) int *out (int temp) {
      +  $1 = &temp;
      +}
      - - - -

      At this time, only zero or one arguments may be converted.

      - - - - -

      36.7.6.2 "typecheck" typemap

      +

      38.7.6.2 "typecheck" typemap

      The "typecheck" typemap is used to support overloaded functions and methods. It merely checks an argument to see whether or not it matches a specific type. For example:

      - - - -
      -
      %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
      $1 = FIXNUM_P($input) ? 1 : 0;
      }
      - - - - - +
      %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
      +  $1 = FIXNUM_P($input) ? 1 : 0;
      +}
      - - - -

      For typechecking, the $1 variable is always a simple integer that is set to 1 or 0 depending on whether or not the input argument is the correct type.

      - - - -

      If you define new "in" typemaps and your program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."

      - - - - -

      36.7.6.3  "out" typemap

      +

      38.7.6.3 "out" typemap

      Converts return value of a C function to a Ruby object.

      - - - - -

      - - - - - -%typemap(out) int {
      - - - - - -   $result = INT2NUM( $1 );
      - - - - - -}
      - - - - - -
      - - - - +
      +
      %typemap(out) int {
      +  $result = INT2NUM( $1 );
      +}
      +

      The following special variables are available.

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $result Result object + $result Result object returned to target language.
      $symname Name of + $symname Name of function/method being wrapped
      $1...n Argument being + $1...n Argument being wrapped
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      - - - - -
      - - - - -
      - - - - - -

      36.7.6.4 "arginit" typemap

      +

      38.7.6.4 "arginit" typemap

      The "arginit" typemap is used to set the initial value of a @@ -5778,90 +2820,54 @@ function argument--before any conversion has occurred. This is not normally necessary, but might be useful in highly specialized applications. For example:

      - - - -
      -
      // Set argument to NULL before any conversion occurs
      %typemap(arginit) int *data {
      $1 = NULL;
      }
      - - - - - +
      // Set argument to NULL before any conversion occurs
      +%typemap(arginit) int *data {
      +  $1 = NULL;
      +}
      - - - - -

      36.7.6.5 "default" typemap

      +

      38.7.6.5 "default" typemap

      The "default" typemap is used to turn an argument into a default argument. For example:

      - - - -
      -
      %typemap(default) int flags {
      $1 = DEFAULT_FLAGS;
      }
      ...
      int foo(int x, int y, int flags);
      - - - - - +
      %typemap(default) int flags {
      +  $1 = DEFAULT_FLAGS;
      +}
      +...
      +int foo(int x, int y, int flags);
      - - - -

      The primary use of this typemap is to either change the wrapping of default arguments or specify a default argument in a language where they aren't supported (like C). Target languages that do not support optional arguments, such as Java and C#, effectively ignore the value specified by this typemap as all arguments must be given.

      - - - -

      Once a default typemap has been applied to an argument, all -arguments that follow must have default values. See the +arguments that follow must have default values. See the Default/optional arguments section for further information on default argument wrapping.

      - - - - -

      36.7.6.6 "check" typemap

      +

      38.7.6.6 "check" typemap

      The "check" typemap is used to supply value checking code during argument conversion. The typemap is applied after arguments have been converted. For example:

      - - - -
      -
      %typemap(check) int positive {
      if ($1 <= 0) {
      SWIG_exception(SWIG_ValueError,"Expected positive value.");
      }
      }
      - - - - - +
      %typemap(check) int positive {
      +  if ($1 <= 0) {
      +    SWIG_exception(SWIG_ValueError,"Expected positive value.");
      +  }
      +}
      - - - - -

      36.7.6.7 "argout" typemap

      +

      38.7.6.7 "argout" typemap

      The "argout" typemap is used to return values from arguments. @@ -5870,156 +2876,52 @@ need to return multiple values. The "argout" typemap is almost always combined with an "in" typemap---possibly to ignore the input value. For example:

      - - - -
      -
      /* Set the input argument to point to a temporary variable */
      %typemap(in, numinputs=0) int *out (int temp) {
      $1 = &temp;
      }

      %typemap(argout, fragment="output_helper") int *out {
      // Append output value $1 to $result (assuming a single integer in this case)
      $result = output_helper( $result, INT2NUM(*$1) );
      }
      - - - - +
      /* Set the input argument to point to a temporary variable */
      +%typemap(in, numinputs=0) int *out (int temp) {
      +  $1 = &temp;
      +}
       
      +%typemap(argout, fragment="output_helper") int *out {
      +  // Append output value $1 to $result (assuming a single integer in this case)
      +  $result = output_helper( $result, INT2NUM(*$1) );
      +}
      - - - -

      The following special variables are available.

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $result Result object + $result Result object returned to target language.
      $input The original + $input The original input object passed.
      $symname Name of + $symname Name of function/method being wrapped.
      - - - - -
      - - - -

      The code supplied to the "argout" typemap is always placed after the "out" typemap. If multiple return values are used, the extra return values are often appended to return value of the function.

      - - - -

      Output helper is a fragment that usually defines a macro to some function like SWIG_Ruby_AppendOutput.

      - - - -

      See the typemaps.i library for examples.

      - - - - -

      36.7.6.8 "freearg" typemap

      +

      38.7.6.8 "freearg" typemap

      The "freearg" typemap is used to cleanup argument data. It is @@ -6028,65 +2930,49 @@ be cleaned up when the wrapper function exits. The "freearg" typemap usually cleans up argument resources allocated by the "in" typemap. For example:

      - - - -
      -
      // Get a list of integers
      %typemap(in) int *items {
      int nitems = Length($input);
      $1 = (int *) malloc(sizeof(int)*nitems);
      }
      // Free the list
      %typemap(freearg) int *items {
      free($1);
      }
      - - - - - +
      // Get a list of integers
      +%typemap(in) int *items {
      +  int nitems = Length($input); 
      +  $1 = (int *) malloc(sizeof(int)*nitems);
      +}
      +// Free the list 
      +%typemap(freearg) int *items {
      +  free($1);
      +}
      - - - -

      The "freearg" typemap inserted at the end of the wrapper function, just before control is returned back to the target language. This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.

      - - - - -

      36.7.6.9 "newfree" typemap

      +

      38.7.6.9 "newfree" typemap

      The "newfree" typemap is used in conjunction with the %newobject directive and is used to deallocate memory used by the return result of a function. For example:

      - - - -
      -
      %typemap(newfree) string * {
      delete $1;
      }
      %typemap(out) string * {
      $result = PyString_FromString($1->c_str());
      }
      ...

      %newobject foo;
      ...
      string *foo();
      - - - - +
      %typemap(newfree) string * {
      +  delete $1;
      +}
      +%typemap(out) string * {
      +  $result = PyString_FromString($1->c_str());
      +}
      +...
       
      +%newobject foo;
      +...
      +string *foo();
      - - - -

      See Object ownership and %newobject for further details.

      - - - - -

      36.7.6.10 "memberin" typemap

      +

      38.7.6.10 "memberin" typemap

      The "memberin" typemap is used to copy data from an @@ -6094,54 +2980,31 @@ already converted input value into a structure member. It is typically used to handle array members and other special cases. For example:

      - - - -
      -
      %typemap(memberin) int [4] {
      memmove($1, $input, 4*sizeof(int));
      }
      - - - - - +
      %typemap(memberin) int [4] {
      +  memmove($1, $input, 4*sizeof(int));
      +}
      - - - -

      It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

      - - - - -

      36.7.6.11 "varin" typemap

      +

      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.

      - - - - -

      36.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.

      - - - - -

      36.7.6.13 "throws" typemap

      +

      38.7.6.13 "throws" typemap

      The "throws" typemap is only used when SWIG parses a C++ @@ -6153,736 +3016,238 @@ or exception in the target language. It is slightly different to the other typemaps as it is based around the exception type rather than the type of a parameter or variable. For example:

      - - - -
      -
      %typemap(throws) const char * %{
      rb_raise(rb_eRuntimeError, $1);
      SWIG_fail;
      %}
      void bar() throw (const char *);
      - - - - - +
      %typemap(throws) const char * %{
      +  rb_raise(rb_eRuntimeError, $1);
      +  SWIG_fail;
      +%}
      +void bar() throw (const char *);
      - - - -

      As can be seen from the generated code below, SWIG generates an exception handler with the catch block comprising the "throws" typemap content.

      - - - -
      -
      ...
      try {
      bar();
      }
      catch(char const *_e) {
      rb_raise(rb_eRuntimeError, _e);
      SWIG_fail;
      }
      ...
      - - - - - +
      ...
      +try {
      +  bar();
      +}
      +catch(char const *_e) {
      +  rb_raise(rb_eRuntimeError, _e);
      +  SWIG_fail;
      +}
      +...
      - - - -

      Note that if your methods do not have an exception specification yet they do throw exceptions, SWIG cannot know how to -deal with them. For a neat way to handle these, see the Exception +deal with them. For a neat way to handle these, see the Exception handling with %exception section.

      - - - - -

      36.7.6.14 directorin typemap

      +

      38.7.6.14 directorin typemap

      Converts C++ objects in director -member functions to ruby objects. It is roughly the opposite +member functions to ruby objects. It is roughly the opposite of the "in" typemap, making its typemap rule often similar to the "out" typemap.

      - - - - -

      - - - - - -%typemap(directorin) int {
      - - - - - -     $result = INT2NUM($1);
      - - - - - -}
      - - - - - -
      - - - - +
      +%typemap(directorin) int {
      +  $result = INT2NUM($1);
      +}
      +

      The following special variables are available.

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $result Result object + $result Result object returned to target language.
      $symname Name of + $symname Name of function/method being wrapped
      $1...n Argument being + $1...n Argument being wrapped
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      this C++ this, + this C++ this, referring to the class itself.
      - - - - -
      - - - - -

      36.7.6.15 directorout typemap

      +

      38.7.6.15 directorout typemap

      Converts Ruby objects in director -member functions to C++ objects.  It is roughly the opposite +member functions to C++ objects. It is roughly the opposite of the "out" typemap, making its rule often similar to the "in" typemap.

      - - - - -

      - - - - - -%typemap(directorout) int {

      - - - - - -   $result = NUM2INT($1);

      - - - - - -}
      - - - - - -
      - - - - +
      +%typemap(directorout) int {
      +  $result = NUM2INT($1);
      +}
      +
      +

      The following special variables are available:

      - - - -
      - - - - - - - - - - - - + + - - + + - - + + - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $inputRuby object being sent to the function$inputRuby object being sent to the function
      $symname Name of function/method being wrapped$symname Name of function/method being wrapped
      $1...n Argument being sent to the function$1...n Argument being sent to the function
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      this C++ this, + this C++ this, referring to the class itself.
      - - - - -
      - - - -

      Currently, the directorout nor the out typemap support the -option numoutputs, +option numoutputs, but the Ruby module provides that functionality through a %feature -directive.  Thus, a function can be made to return "nothing" +directive. Thus, a function can be made to return "nothing" if you do:

      - - - - -
      %feature("numoutputs","0") -MyClass::function;
      - - - - +
      +%feature("numoutputs","0") MyClass::function;
      +

      This feature can be useful if a function returns a status code, which you want to discard but still use the typemap to raise an -exception.
      - - - - +exception.

      - - - - -

      36.7.6.16 directorargout typemap

      +

      38.7.6.16 directorargout typemap

      Output argument processing in director member functions.

      - - - - -
      %typemap(directorargout, -fragment="output_helper") int {
      - - - - - -$result = output_helper( $result, NUM2INT($1) );

      - - - - - -}
      - - - - +
      +%typemap(directorargout,
      +fragment="output_helper") int {
      +  $result = output_helper( $result, NUM2INT($1) );
      +}
      +

      The following special variables are available:

      - - - -
      - - - - - - - - - - - - + + - - + + - - + + - - + + - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $resultResult that the director function returns$resultResult that the director function returns
      $inputRuby object being sent to the function$inputRuby object being sent to the function
      $symnamename of the function/method being wrapped$symnamename of the function/method being wrapped
      $1...nArgument being sent to the function$1...nArgument being sent to the function
      $1_nameName of the + $1_nameName of the argument (if provided)
      $1_typeThe actual C + $1_typeThe actual C datatype matched by the typemap
      $1_ltypeThe assignable + $1_ltypeThe assignable version of the C datatype matched by the typemap
      thisC++ this, + thisC++ this, referring to the instance of the class itself
      - - - - -
      - - - - -

      36.7.6.17 ret typemap

      +

      38.7.6.17 ret typemap

      Cleanup of function return values

      - - - - -

      36.7.6.18 globalin typemap

      +

      38.7.6.18 globalin typemap

      Setting of C global variables

      - - - - -

      36.7.7 Typemap variables

      +

      38.7.7 Typemap variables

      @@ -6891,83 +3256,35 @@ may appear. A full list of variables can be found in the "A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that is supposed to hold an argument value. For output values, this is the raw result that is supposed to be returned to Ruby. - - - -

      $input

      - - - -
      A VALUE holding a raw Ruby object with an argument or variable value.
      - - - -

      $result

      - - - -
      A VALUE that holds the result to be returned to Ruby.
      - - - -

      $1_name

      - - - -
      The parameter name that was matched.
      - - - -

      $1_type

      - - - -
      The actual C datatype matched by the typemap.
      - - - -

      $1_ltype

      - - - -
      An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may @@ -6975,48 +3292,27 @@ be an altered version of $1_type. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned.
      - - - -

      $symname

      - - - -
      The Ruby name of the wrapper function being created.
      - - - - -

      36.7.8 Useful Functions

      +

      38.7.8 Useful Functions

      When you write a typemap, you usually have to work directly with Ruby objects. The following functions may prove to be useful. (These functions plus many more can be found in Programming -Ruby book, by David Thomas and Andrew Hunt.) 

      +Ruby book, by David Thomas and Andrew Hunt.)

      In addition, we list equivalent functions that SWIG defines, which provide a language neutral conversion (these functions are defined for -each swig language supported).  If you are trying to create a swig +each swig language supported). If you are trying to create a swig file that will work under multiple languages, it is recommended you stick to the swig functions instead of the native Ruby functions. - That should help you avoid having to rewrite a lot of typemaps +That should help you avoid having to rewrite a lot of typemaps across multiple languages.

      - - - - - - - - - -

      36.7.8.1 C Datatypes to Ruby Objects

      +

      38.7.8.1 C Datatypes to Ruby Objects

      @@ -7024,487 +3320,264 @@ across multiple languages.

      - RUBY - SWIG + RUBY + SWIG - INT2NUM(long or int) - SWIG_From_int(int x) + INT2NUM(long or int) + SWIG_From_int(int x) int to Fixnum or Bignum - - INT2FIX(long or int) - + INT2FIX(long or int) + int to Fixnum (faster than INT2NUM) - - CHR2FIX(char) - SWIG_From_char(char x) + CHR2FIX(char) + SWIG_From_char(char x) char to Fixnum - - rb_str_new2(char*) - SWIG_FromCharPtrAndSize(char*, size_t) + rb_str_new2(char*) + SWIG_FromCharPtrAndSize(char*, size_t) char* to String - - rb_float_new(double) - SWIG_From_double(double),
      + rb_float_new(double) + SWIG_From_double(double),
      SWIG_From_float(float) float/double to Float - - - - - -
      - - - - -

      36.7.8.2 Ruby Objects to C Datatypes

      +

      38.7.8.2 Ruby Objects to C Datatypes

      Here, while the Ruby versions return the value directly, the SWIG -versions do not, but return a status value to indicate success (SWIG_OK). While more akward to use, this allows you to write typemaps that report more helpful error messages, like:

      -

      -%typemap(in) size_t (int ok)

      -  ok = SWIG_AsVal_size_t($input, &$1);
      -  if (!SWIG_IsOK(ok)) {
      -    SWIG_exception_fail(SWIG_ArgError(ok), -Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input -));
      -   }
      -
      -}
      -
        
      -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      int NUM2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      int FIX2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      unsigned int NUM2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      unsigned int FIX2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      long NUM2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      long FIX2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      unsigned long FIX2ULONG(Numeric)SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)
      char NUM2CHR(Numeric or String)SWIG_AsVal_char(VALUE, int*)
      char * STR2CSTR(String)SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)
      char * rb_str2cstr(String, int*length)
      double NUM2DBL(Numeric)(double) SWIG_AsVal_int(VALUE) or similar
      - - - - +versions do not, but return a status value to indicate success (SWIG_OK). While more akward to use, this allows you to write typemaps that report more helpful error messages, like:

      +
      +
      +%typemap(in) size_t (int ok)
      +  ok = SWIG_AsVal_size_t($input, &$1);
      +  if (!SWIG_IsOK(ok)) {
      +    SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input));
      +  }
      +}
      +
      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      int NUM2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      int FIX2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      unsigned int NUM2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      unsigned int FIX2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      long NUM2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      long FIX2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      unsigned long FIX2ULONG(Numeric)SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)
      char NUM2CHR(Numeric or String)SWIG_AsVal_char(VALUE, int*)
      char * StringValuePtr(String)SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)
      char * rb_str2cstr(String, int*length)
      double NUM2DBL(Numeric)(double) SWIG_AsVal_int(VALUE) or similar
      +
      - - - -

      36.7.8.3 Macros for VALUE

      +

      38.7.8.3 Macros for VALUE

      RSTRING_LEN(str)

      - - - -
      length of the Ruby string
      - - - -

      RSTRING_PTR(str)

      - - - -
      pointer to string storage
      - - - -

      RARRAY_LEN(arr)

      - - - -
      length of the Ruby array
      - - - -

      RARRAY(arr)->capa

      - - - -
      capacity of the Ruby array
      - - - -

      RARRAY_PTR(arr)

      - - - -
      pointer to array storage
      - - - - -

      36.7.8.4 Exceptions

      +

      38.7.8.4 Exceptions

      void rb_raise(VALUE exception, const char *fmt, ...)

      - - - -
      Raises an exception. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - -

      void rb_fatal(const char *fmt, ...)

      - - - -
      Raises a fatal exception, terminating the process. No rescue blocks are called, but ensure blocks will be called. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - -

      void rb_bug(const char *fmt, ...)

      - - - -
      Terminates the process immediately -- no handlers of any sort will be called. The given format string fmt and remaining arguments are interpreted as with printf(). You should call this function only if a fatal bug has been exposed.
      - - - -

      void rb_sys_fail(const char *msg)

      - - - -
      Raises a platform-specific exception corresponding to the last known system error, with the given string msg.
      - - - -

      VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args, VALUE(*rescue)(VALUE, VALUE), VALUE rargs)

      - - - -
      Executes body with the given args. If a StandardError exception is raised, then execute rescue with the given rargs.
      - - - -

      VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args, VALUE(*ensure)(VALUE), VALUE eargs)

      - - - -
      Executes body with the given args. Whether or not an exception is raised, execute ensure with the given rargs after body has completed.
      - - - -

      VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)

      - - - -
      Executes body with the given args and returns nonzero in result if any exception was raised.
      - - - -

      void rb_notimplement()

      - - - -
      Raises a NotImpError exception to indicate that the enclosed function is not implemented yet, or not available on this platform.
      - - - -

      void rb_exit(int status)

      - - - -
      Exits Ruby with the given status. Raises a SystemExit exception and calls registered exit functions and finalizers.
      - - - -

      void rb_warn(const char *fmt, ...)

      - - - -
      Unconditionally issues a warning message to standard error. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - -

      void rb_warning(const char *fmt, ...)

      - - - -
      Conditionally issues a warning message to standard error if Ruby was invoked with the -w flag. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - - -

      36.7.8.5 Iterators

      +

      38.7.8.5 Iterators

      void rb_iter_break()

      - - - -
      Breaks out of the enclosing iterator block.
      - - - -

      VALUE rb_each(VALUE obj)

      - - - -
      Invokes the each method of the given obj.
      - - - -

      VALUE rb_yield(VALUE arg)

      - - - -
      Transfers execution to the iterator block in the current context, passing arg as an argument. Multiple values may be passed in an array.
      - - - -

      int rb_block_given_p()

      - - - -
      Returns true if yield would execute a block in the current context; that is, if a code block was passed to the current method and is available to be called.
      - - - -

      VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE (*block)(VALUE, VALUE), VALUE arg2)

      - - - -
      Invokes method with argument args and block block. A yield from that method will invoke block with the argument given to yield, and a second argument arg2.
      - - - -

      VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE), VALUE value)

      - - - -
      Equivalent to Ruby's catch.
      - - - -

      void rb_throw(const char *tag, VALUE value)

      - - - -
      Equivalent to Ruby's throw.
      - - - - -

      36.7.9 Typemap Examples

      +

      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.

      - - - - -

      36.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 @@ -7512,54 +3585,64 @@ command line arguments, which are usually passed in an array of NULL terminated strings. The following SWIG interface file allows a Ruby Array instance to be used as a char ** object.

      - - - -
      -
      %module argv

      // This tells SWIG to treat char ** as a special case
      %typemap(in) char ** {
      /* Get the length of the array */
      int size = RARRAY($input)->len;
      int i;
      $1 = (char **) malloc((size+1)*sizeof(char *));
      /* Get the first element in memory */
      VALUE *ptr = RARRAY($input)->ptr;
      for (i=0; i < size; i++, ptr++)
      /* Convert Ruby Object String to char* */
      $1[i]= STR2CSTR(*ptr);
      $1[i]=NULL; /* End of list */
      }

      // This cleans up the char ** array created before
      // the function call

      %typemap(freearg) char ** {
      free((char *) $1);
      }

      // Now a test function
      %inline %{
      int print_args(char **argv) {
      int i = 0;
      while (argv[i]) {
      printf("argv[%d] = %s\n", i,argv[i]);
      i++;
      }
      return i;
      }
      %}

      - +
      %module argv
       
      +// This tells SWIG to treat char ** as a special case
      +%typemap(in) char ** {
      +  /* Get the length of the array */
      +  int size = RARRAY($input)->len; 
      +  int i;
      +  $1 = (char **) malloc((size+1)*sizeof(char *));
      +  /* Get the first element in memory */
      +  VALUE *ptr = RARRAY($input)->ptr; 
      +  for (i=0; i < size; i++, ptr++) {
      +    /* Convert Ruby Object String to char* */
      +    $1[i]= StringValuePtr(*ptr); 
      +  }
      +  $1[i]=NULL; /* End of list */
      +}
       
      +// This cleans up the char ** array created before 
      +// the function call
       
      +%typemap(freearg) char ** {
      +  free((char *) $1);
      +}
       
      +// Now a test function
      +%inline %{
      +int print_args(char **argv) {
      +  int i = 0;
      +  while (argv[i]) {
      +    printf("argv[%d] = %s\n", i,argv[i]);
      +    i++;
      +  }
      +  return i;
      +}
      +%}
      - - - -

      When this module is compiled, the wrapped C function now operates as follows :

      - - - -
      -
      require 'Argv'
      Argv.print_args(["Dave","Mike","Mary","Jane","John"])
      argv[0] = Dave
      argv[1] = Mike
      argv[2] = Mary
      argv[3] = Jane
      argv[4] = John
      - - - - - +
      require 'Argv'
      +Argv.print_args(["Dave","Mike","Mary","Jane","John"])
      +argv[0] = Dave
      +argv[1] = Mike
      +argv[2] = Mary
      +argv[3] = Jane
      +argv[4] = John
      - - - -

      In the example, two different typemaps are used. The "in" typemap is used to receive an input argument and convert it to a C array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function.

      - - - - -

      36.7.11 Collecting arguments in a hash

      +

      38.7.11 Collecting arguments in a hash

      Ruby's solution to the "keyword arguments" capability of some @@ -7571,66 +3654,33 @@ provide similar functionality for your Ruby interface. For example, suppose you'd like to wrap this C function that collects information about people's vital statistics:

      - - - -
      -
      void setVitalStats(const char *person, int nattributes, const char **names, int *values);
      - - - - - +
      void setVitalStats(const char *person, int nattributes, const char **names, int *values);
      - - - -

      and you'd like to be able to call it from Ruby by passing in an arbitrary number of key-value pairs as inputs, e.g.

      - - - -
      -
      setVitalStats("Fred",
      'weight' => 270,
      'age' => 42
      )
      - - - - - +
      setVitalStats("Fred", 
      +  'weight' => 270, 
      +  'age' => 42 
      +)
      - - - -

      To make this work, you need to write a typemap that expects a Ruby Hash as its input and somehow extracts the last three arguments (nattributes, names and values) needed by your C function. Let's start with the basics:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +}
      + 
      - - - -

      This %typemap directive tells SWIG that we want to match any function declaration that has the specified types and names of arguments somewhere in the argument list. The fact that we @@ -7643,38 +3693,20 @@ of parentheses (keys_arr, i, key and val) define local variables that our typemap will need.

      - - - -

      Since we expect the input argument to be a Hash, let's next add a check for that:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +}
      - - - -

      Check_Type() is just a macro (defined in the Ruby header files) that confirms that the input argument is of the correct type; if it isn't, an exception will be raised.

      - - - -

      The next task is to determine how many key-value pairs are present in the hash; we'll assign this number to the first typemap argument ($1). This is a little tricky since the @@ -7683,162 +3715,148 @@ hash, but we can get around that by calling the hash's size method directly and converting its result to a C int value:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      +}
      - - - -

      So now we know the number of attributes. Next we need to initialize the second and third typemap arguments (i.e. the two C arrays) to NULL and set the stage for extracting the keys and values from the hash:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      }

      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      +    $2 = NULL;
      +    $3 = NULL;
      +    if ($1 > 0) {
      +      $2 = (char **) malloc($1*sizeof(char *));
      +      $3 = (int *) malloc($1*sizeof(int));
      +    }
      +}
      - - - -

      There are a number of ways we could extract the keys and values from the input hash, but the simplest approach is to first call the hash's keys method (which returns a Ruby array of the keys) and then start looping over the elements in that array:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      for (i = 0; i < $1; i++) {
      }

      }
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      +    $2 = NULL;
      +    $3 = NULL;
      +    if ($1 > 0) {
      +      $2 = (char **) malloc($1*sizeof(char *));
      +      $3 = (int *) malloc($1*sizeof(int));
      +      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      +      for (i = 0; i < $1; i++) {
      +      }
      +    }
      +}
      - - - -

      Recall that keys_arr and i are local variables for this typemap. For each element in the keys_arr array, we want to get the key itself, as well as the value corresponding to that key in the hash:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      for (i = 0; i < $1; i++) {
      key = rb_ary_entry(keys_arr, i);
      val = rb_hash_aref($input, key);

      }
      }
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      +    $2 = NULL;
      +    $3 = NULL;
      +    if ($1 > 0) {
      +      $2 = (char **) malloc($1*sizeof(char *));
      +      $3 = (int *) malloc($1*sizeof(int));
      +      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      +      for (i = 0; i < $1; i++) {
      +        key = rb_ary_entry(keys_arr, i);
      +        val = rb_hash_aref($input, key);
      +      }
      +    }
      +}
      - - - -

      To be safe, we should again use the Check_Type() macro to confirm that the key is a String and the value is a Fixnum:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      for (i = 0; i < $1; i++) {
      key = rb_ary_entry(keys_arr, i);
      val = rb_hash_aref($input, key);
      Check_Type(key, T_STRING);
      Check_Type(val, T_FIXNUM);

      }
      }
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      +    $2 = NULL;
      +    $3 = NULL;
      +    if ($1 > 0) {
      +      $2 = (char **) malloc($1*sizeof(char *));
      +      $3 = (int *) malloc($1*sizeof(int));
      +      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      +      for (i = 0; i < $1; i++) {
      +        key = rb_ary_entry(keys_arr, i);
      +        val = rb_hash_aref($input, key);
      +        Check_Type(key, T_STRING);
      +        Check_Type(val, T_FIXNUM);
      +      }
      +    }
      +}
      - - - -

      Finally, we can convert these Ruby objects into their C equivalents and store them in our local C arrays:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      for (i = 0; i < $1; i++) {
      key = rb_ary_entry(keys_arr, i);
      val = rb_hash_aref($input, key);
      Check_Type(key, T_STRING);
      Check_Type(val, T_FIXNUM);
      $2[i] = STR2CSTR(key);
      $3[i] = NUM2INT(val);

      }
      }
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +  Check_Type($input, T_HASH);
      +  $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      +  $2 = NULL;
      +  $3 = NULL;
      +  if ($1 > 0) {
      +    $2 = (char **) malloc($1*sizeof(char *));
      +    $3 = (int *) malloc($1*sizeof(int));
      +    keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      +    for (i = 0; i < $1; i++) {
      +      key = rb_ary_entry(keys_arr, i);
      +      val = rb_hash_aref($input, key);
      +      Check_Type(key, T_STRING);
      +      Check_Type(val, T_FIXNUM);
      +      $2[i] = StringValuePtr(key);
      +      $3[i] = NUM2INT(val);
      +    }
      +  }
      +}
      - - - -

      We're not done yet. Since we used malloc() to dynamically allocate the memory used for the names and values arguments, we need to provide a corresponding "freearg" typemap to free that memory so that there is no memory leak. Fortunately, this typemap is a lot easier to write:

      - - - -
      -
      %typemap(freearg) (int nattributes, const char **names, const int *values) {
      free((void *) $2);
      free((void *) $3);
      }
      - - - - - +
      %typemap(freearg) (int nattributes, const char **names, const int *values) {
      +  free((void *) $2);
      +  free((void *) $3);
      +}
      - - - -

      All of the code for this example, as well as a sample Ruby program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

      - - - - -

      36.7.12 Pointer handling

      +

      38.7.12 Pointer handling

      Occasionally, it might be necessary to convert pointer values @@ -7846,17 +3864,9 @@ that have been stored using the SWIG typed-pointer representation. Since there are several ways in which pointers can be represented, the following two functions are used to safely perform this conversion:

      - - - -

      int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty, int flags)

      - - - -
      Converts a Ruby object obj to a C pointer whose address is ptr (i.e. ptr is a pointer to a pointer). The third argument, ty, @@ -7870,17 +3880,9 @@ errors will cause SWIG_ConvertPtr() to return -1 but not raise an exception. If ty is NULL, no type-checking is performed.
      - - - -

      VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)

      - - - -
      Creates a new Ruby pointer object. Here, ptr is the pointer to convert, ty is the SWIG type descriptor structure that describes the type, and own @@ -7888,10 +3890,6 @@ is a flag that indicates whether or not Ruby should take ownership of the pointer (i.e. whether Ruby should free this data when the corresponding Ruby instance is garbage-collected).
      - - - -

      Both of these functions require the use of a special SWIG type-descriptor structure. This structure contains information about the mangled name of the datatype, type-equivalence information, as well @@ -7899,96 +3897,52 @@ as information about converting pointer values under C++ inheritance. For a type of Foo *, the type descriptor structure is usually accessed as follows:

      - - - -
      -
      Foo *foo;
      SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);

      VALUE obj;
      obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
      - - - - +
      Foo *foo;
      +SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);
       
      +VALUE obj;
      +obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
      - - - -

      In a typemap, the type descriptor should always be accessed using the special typemap variable $1_descriptor. For example:

      - - - -
      -
      %typemap(in) Foo * {
      SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1);
      }
      - - - - - +
      %typemap(in) Foo * {
      +  SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1);
      +}
      - - - - -

      36.7.12.1 Ruby Datatype Wrapping

      +

      38.7.12.1 Ruby Datatype Wrapping

      VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void (*free)(void *), void *ptr)

      - - - -
      Given a pointer ptr to some C data, and the two garbage collection routines for this data (mark and free), return a VALUE for the Ruby object.
      - - - -

      VALUE Data_Make_Struct(VALUE class, c-type, void (*mark)(void *), void (*free)(void *), c-type *ptr)

      - - - -
      Allocates a new instance of a C data type c-type, assigns it to the pointer ptr, then wraps that pointer with Data_Wrap_Struct() as above.
      - - - -

      Data_Get_Struct(VALUE obj, c-type, c-type *ptr)

      - - - -
      Retrieves the original C pointer of type c-type from the data object obj and assigns that pointer to ptr.
      - - - - -

      36.7.13 Example: STL Vector to Ruby Array

      +

      38.7.13 Example: STL Vector to Ruby Array

      Another use for macros and type maps is to create a Ruby array @@ -7999,105 +3953,88 @@ The following is an example of how to construct this type of macro/typemap and should give insight into constructing similar typemaps for other STL structures:

      - - - -
      -
      %define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      %typemap(out) vectorclassname &, const vectorclassname & {
      VALUE arr = rb_ary_new2($1->size());
      vectorclassname::iterator i = $1->begin(), iend = $1->end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      $result = arr;
      }
      %typemap(out) vectorclassname, const vectorclassname {
      VALUE arr = rb_ary_new2($1.size());
      vectorclassname::iterator i = $1.begin(), iend = $1.end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      $result = arr;
      }
      %enddef
      - - - - - +
      %define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      +%typemap(out) vectorclassname &, const vectorclassname & {
      +  VALUE arr = rb_ary_new2($1->size());
      +  vectorclassname::iterator i = $1->begin(), iend = $1->end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      +  $result = arr;
      +}
      +%typemap(out) vectorclassname, const vectorclassname {
      +  VALUE arr = rb_ary_new2($1.size());
      +  vectorclassname::iterator i = $1.begin(), iend = $1.end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      +  $result = arr;
      +}
      +%enddef
      - - - -

      Note, that the "c ## classname.klass" is used in the preprocessor step to determine the actual object from the class name.

      - - - -

      To use the macro with a class Foo, the following is used:

      - - - -
      -
      PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)
      - - - - - +
      PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)
      - - - -

      It is also possible to create a STL vector of Ruby objects:

      - - - -
      -
      %define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
      %typemap(in) vectorclassname &, const vectorclassname & {
      Check_Type($input, T_ARRAY);
      vectorclassname *vec = new vectorclassname;
      int len = RARRAY($input)->len;
      for (int i=0; i!=len; i++) {
      VALUE inst = rb_ary_entry($input, i);
      //The following _should_ work but doesn't on HPUX
      // Check_Type(inst, T_DATA);
      classname *element = NULL;
      Data_Get_Struct(inst, classname, element);
      vec->push_back(element);
      }
      $1 = vec;
      }

      %typemap(freearg) vectorclassname &, const vectorclassname & {
      delete $1;
      }
      %enddef
      - - - - +
      %define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
      +%typemap(in) vectorclassname &, const vectorclassname & {
      +  Check_Type($input, T_ARRAY);
      +  vectorclassname *vec = new vectorclassname;
      +  int len = RARRAY($input)->len;
      +  for (int i=0; i!=len; i++) {
      +    VALUE inst = rb_ary_entry($input, i);
      +    //The following _should_ work but doesn't on HPUX
      +    // Check_Type(inst, T_DATA);
      +    classname *element = NULL;
      +    Data_Get_Struct(inst, classname, element);
      +    vec->push_back(element);
      +  }
      +  $1 = vec;
      +}
       
      +%typemap(freearg) vectorclassname &, const vectorclassname & {
      +  delete $1;
      +}
      +%enddef
      - - - -

      It is also possible to create a Ruby array from a vector of static data types:

      - - - -
      -
      %define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      %typemap(out) vectorclassname &, const vectorclassname & {
      VALUE arr = rb_ary_new2($1->size());
      vectorclassname::iterator i = $1->begin(), iend = $1->end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      $result = arr;
      }
      %typemap(out) vectorclassname, const vectorclassname {
      VALUE arr = rb_ary_new2($1.size());
      vectorclassname::iterator i = $1.begin(), iend = $1.end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      $result = arr;
      }
      %enddef
      - - - - - +
      %define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      +%typemap(out) vectorclassname &, const vectorclassname & {
      +  VALUE arr = rb_ary_new2($1->size()); 
      +  vectorclassname::iterator i = $1->begin(), iend = $1->end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      +  $result = arr;
      +}
      +%typemap(out) vectorclassname, const vectorclassname {
      +  VALUE arr = rb_ary_new2($1.size()); 
      +  vectorclassname::iterator i = $1.begin(), iend = $1.end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      +  $result = arr;
      +}
      +%enddef
      - - - - -
      - - - - - Note that this is mostly an example of typemaps. If you want to use the STL with ruby, you are advised to use the standard swig STL library, -which does much more than this.  Refer to the section called -the C++ Standard Template Library.
      +which does much more than this. Refer to the section called +the C++ Standard Template Library. - - - - -

      36.8 Docstring Features

      +

      38.8 Docstring Features

      @@ -8107,109 +4044,61 @@ will normally not get any documentation for it, even if they run 'rdoc' on the resulting .c or .cxx file.

      - - - -

      The features described in this section make it easy for you to add rdoc strings to your modules, functions and methods that can then be read by Ruby's rdoc tool to generate html web pages, ri documentation, Windows chm file and an .xml description.

      - - - -

      rdoc can then be run from a console or shell window on a swig -generated file. 

      - - - - +generated file.

      For example, to generate html web pages from a C++ file, you'd -do: 

      - - - - - -
      -$ -rdoc -E cxx=c -f html file_wrap.cxx
      - - - +do:

      +
      +
      +$ rdoc -E cxx=c -f html file_wrap.cxx
      +

      To generate ri documentation from a c wrap file, you could do:

      +
      +$ rdoc -r file_wrap.c
      +
      - - - -
      $ rdoc --r file_wrap.c -
      - - - - - -

      36.8.1 Module docstring

      +

      38.8.1 Module docstring

      -Ruby allows a docstring at the beginning of the file +Ruby allows a docstring at the beginning of the file before any other statements, and it is typically used to give a general description of the entire module. SWIG supports this by setting an option of the %module directive. For example:

      - - - -
      -
      %module(docstring="This is the example module's docstring") example
      - - - - - +
      %module(docstring="This is the example module's docstring") example
      - - - -

      When you have more than just a line or so then you can retain the easy readability of the %module directive by using a macro. For example:

      - - - -
      -
      %define DOCSTRING
      "The `XmlResource` class allows program resources defining menus,
      layout of controls on a panel, etc. to be loaded from an XML file."
      %enddef

      %module(docstring=DOCSTRING) xrc
      - - - - +
      %define DOCSTRING
      +"The `XmlResource` class allows program resources defining menus, 
      +layout of controls on a panel, etc. to be loaded from an XML file."
      +%enddef
       
      +%module(docstring=DOCSTRING) xrc
      - - - - -

      36.8.2 %feature("autodoc")

      +

      38.8.2 %feature("autodoc")

      Since SWIG does know everything about the function it wraps, @@ -8219,10 +4108,6 @@ and default values. Since Ruby ships with one of the best documentation systems of any language, it makes sense to take advantage of it.

      - - - -

      SWIG's Ruby module provides support for the "autodoc" feature, which when attached to a node in the parse tree will cause an rdoc @@ -8234,11 +4119,7 @@ several options for autodoc controlled by the value given to the feature, described below.

      - - - - -

      36.8.2.1 %feature("autodoc", "0")

      +

      38.8.2.1 %feature("autodoc", "0")

      @@ -8248,45 +4129,21 @@ example, given this function prototype:

      - - - -
      -
      %feature("autodoc", "0");
      bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
      - - - - - +
      %feature("autodoc", "0");
      +bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
      - - - -

      Then Ruby code like this will be generated:

      - - - -
      -
      function_name(x, y, foo=nil, bar=nil) -> bool
      ...
      - - - - - +
      function_name(x, y, foo=nil, bar=nil) -> bool
      +  ...
      - - - - -

      36.8.2.2 %feature("autodoc", "1")

      +

      38.8.2.2 %feature("autodoc", "1")

      @@ -8301,68 +4158,45 @@ parameter types with the "1" option will result in rdoc code like this:

      - - - -
      -
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
      ...
      - - - - - +
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
      +  ...
      - - - - -

      36.8.2.3 %feature("autodoc", "2")

      +

      38.8.2.3 %feature("autodoc", "2")

      When the "2" option is used then the parameter types will not be used in the rdoc string. However, they will be listed in full after the -function.  Given the example above, then turning on the +function. Given the example above, then turning on the parameter types with the "2" option will result in Ruby code like this:

      - - - - -

      36.8.2.4 %feature("autodoc", "3")

      +

      38.8.2.4 %feature("autodoc", "3")

      When the "3" option is used then the function will be documented using -a combination of "1" and "2" above.  Given the example above, +a combination of "1" and "2" above. Given the example above, then turning on the parameter types with the "2" option will result in Ruby code like this:

      - - - -
      -
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool

      Parameters:
      x - int
      y - int
      foo - Foo
      bar - Bar
      - - - - +
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
       
      +Parameters:
      +        x - int
      +        y - int
      +        foo - Foo
      +        bar - Bar
      - - - - -

      36.8.2.5 %feature("autodoc", "docstring")

      +

      38.8.2.5 %feature("autodoc", "docstring")

      @@ -8373,24 +4207,12 @@ feature then that string will be used in place of the automatically generated string. For example:

      - - - -
      -
      %feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
      void GetPosition(int* OUTPUT, int* OUTPUT);
      - - - - - +
      %feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
      +void GetPosition(int* OUTPUT, int* OUTPUT);
      - - - - -

      36.8.3 %feature("docstring")

      +

      38.8.3 %feature("docstring")

      @@ -8401,1031 +4223,191 @@ docstring associated with classes, function or methods are output. If an item already has an autodoc string then it is combined with the docstring and they are output together.

      +

      38.9 Advanced Topics

      - - -

      36.9 Advanced Topics

      - - -

      36.9.1 Operator overloading

      +

      38.9.1 Operator overloading

      SWIG allows operator overloading with, by using the %extend or %rename commands in SWIG and the following operator names (derived from Python):

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      General
      __repr__ inspect
      __str__ to_s
      __cmp__ <=>
      __hash__ hash
      __nonzero__ nonzero?
      Callable
      __call__ call
      Collection
      __len__ length
      __getitem__ []
      __setitem__ []=
      Numeric
      __add__ +
      __sub__ -
      __mul__ *
      __div__ /
      __mod__ %
      __divmod__ divmod
      __pow__ **
      __lshift__ <<
      __rshift__ >>
      __and__ &
      __xor__ ^
      __or__ |
      __neg__ -@
      __pos__ +@
      __abs__ abs
      __invert__ ~
      __int__ to_i
      __float__ to_f
      __coerce__ coerce
      Additions in 1.3.13
      __lt__ <
      __le__ <=
      __eq__ ==
      __gt__ >
      __ge__ >=
      - - - - -
      - - - -

      Note that although SWIG supports the __eq__ magic method name for defining an equivalence operator, there is no separate method for handling inequality since Ruby parses the expression a != b as !(a == b).

      - - - - -

      36.9.2 Creating Multi-Module Packages

      +

      38.9.2 Creating Multi-Module Packages

      The chapter on Working @@ -9433,112 +4415,88 @@ with Modules discusses the basics of creating multi-module extensions with SWIG, and in particular the considerations for sharing runtime type information among the different modules.

      - - - -

      As an example, consider one module's interface file (shape.i) that defines our base class:

      - - - -
      -
      %module shape

      %{
      #include "Shape.h"
      %}

      class Shape {
      protected:
      double xpos;
      double ypos;
      protected:
      Shape(double x, double y);
      public:
      double getX() const;
      double getY() const;
      };
      - - - +
      %module shape
       
      +%{
      +#include "Shape.h"
      +%}
       
      +class Shape {
      +protected:
      +  double xpos;
      +  double ypos;
      +protected:
      +  Shape(double x, double y);
      +public:
      +  double getX() const;
      +  double getY() const;
      +};
      - - - -

      We also have a separate interface file (circle.i) that defines a derived class:

      - - - -
      -
      %module circle

      %{
      #include "Shape.h"
      #include "Circle.h"
      %}

      // Import the base class definition from Shape module
      %import shape.i

      class Circle : public Shape {
      protected:
      double radius;
      public:
      Circle(double x, double y, double r);
      double getRadius() const;
      };
      - - +
      %module circle
       
      +%{
      +#include "Shape.h"
      +#include "Circle.h"
      +%}
       
      +// Import the base class definition from Shape module
      +%import shape.i
       
      +class Circle : public Shape {
      +protected:
      +  double radius;
      +public:
      +  Circle(double x, double y, double r);
      +  double getRadius() const;
      +};
      - - - -

      We'll start by building the Shape extension module:

      - - - -
      -
      $ swig -c++ -ruby shape.i
      +
      $ swig -c++ -ruby shape.i
       
      - - - - -
      - - - -

      SWIG generates a wrapper file named shape_wrap.cxx. To compile this into a dynamically loadable extension for Ruby, prepare an extconf.rb script using this template:

      - - - -
      -
      require 'mkmf'

      # Since the SWIG runtime support library for Ruby
      # depends on the Ruby library, make sure it's in the list
      # of libraries.
      $libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])

      # Create the makefile
      create_makefile('shape')
      - - - +
      require 'mkmf'
       
      +# Since the SWIG runtime support library for Ruby
      +# depends on the Ruby library, make sure it's in the list
      +# of libraries.
      +$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])
       
      +# Create the makefile
      +create_makefile('shape')
      - - - -

      Run this script to create a Makefile and then type make to build the shared library:

      - - - -
      -
      $ ruby extconf.rb
      creating Makefile
      $ make
      g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \
      -I. -c shape_wrap.cxx
      gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
      -lruby -lruby -lc
      - - - - - +
      $ ruby extconf.rb
      +creating Makefile
      +$ make
      +g++ -fPIC -g -O2 -I. -I/usr/include/ruby-2.1.0 \
      +-I. -c shape_wrap.cxx
      +gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
      +-lruby -lruby -lc
      - - - -

      Note that depending on your installation, the outputs may be slightly different; these outputs are those for a Linux-based development environment. The end result should be a shared library @@ -9546,67 +4504,36 @@ development environment. The end result should be a shared library code. Now repeat this process in a separate directory for the Circle module:

      - - - -
        - - - - -
      1. Run SWIG to generate the wrapper code (circle_wrap.cxx);
      2. - - - - -
      3. Write an extconf.rb script that your end-users can use to create a platform-specific Makefile for the extension;
      4. - - - - -
      5. Build the shared library for this extension by typing make.
      6. - - - - -
      - - - -

      Once you've built both of these extension modules, you can test them interactively in IRB to confirm that the Shape and Circle modules are properly loaded and initialized:

      - - - -
      -
      $ irb
      irb(main):001:0> require 'shape'
      true
      irb(main):002:0> require 'circle'
      true
      irb(main):003:0> c = Circle::Circle.new(5, 5, 20)
      #<Circle::Circle:0xa097208>
      irb(main):004:0> c.kind_of? Shape::Shape
      true
      irb(main):005:0> c.getX()
      5.0
      - - - - - +
      $ irb
      +irb(main):001:0> require 'shape'
      +true
      +irb(main):002:0> require 'circle'
      +true
      +irb(main):003:0> c = Circle::Circle.new(5, 5, 20)
      +#<Circle::Circle:0xa097208>
      +irb(main):004:0> c.kind_of? Shape::Shape
      +true
      +irb(main):005:0> c.getX()
      +5.0
      - - - - -

      36.9.3 Specifying Mixin Modules

      +

      38.9.3 Specifying Mixin Modules

      The Ruby language doesn't support multiple inheritance, but @@ -9614,97 +4541,66 @@ it does allow you to mix one or more modules into a class using Ruby's inclu method. For example, if you have a Ruby class that defines an each instance method, e.g.

      - - - -
      -
      class Set
      def initialize
      @members = []
      end

      def each
      @members.each { |m| yield m }
      end
      end
      - - - - - +
      class Set
      +  def initialize
      +  @members = []
      +  end
      + 
      +  def each
      +  @members.each { |m| yield m }
      +  end
      +end
      - - - -

      then you can mix-in Ruby's Enumerable module to easily add a lot of functionality to your class:

      - - - -
      -
      class Set
      include Enumerable
      def initialize
      @members = []
      end
      def each
      @members.each { |m| yield m }
      end
      end
      - - - - - +
      class Set
      +  include Enumerable
      +  def initialize
      +    @members = []
      +  end
      +  def each
      +    @members.each { |m| yield m }
      +  end
      +end
      - - - -

      To get the same benefit for your SWIG-wrapped classes, you can use the %mixin directive to specify the names of one or more modules that should be mixed-in to a class. For the above example, the SWIG interface specification might look like this:

      - - - -
      -
      %mixin Set "Enumerable";

      class Set {
      public:
      // Constructor
      Set();

      // Iterates through set members
      void each();
      };
      - - - - +
      %mixin Set "Enumerable";
       
      +class Set {
      +public:
      +  // Constructor
      +  Set();
      + 
      +  // Iterates through set members
      +  void each();
      +};
      - - - -

      Multiple modules can be mixed into a class by providing a comma-separated list of module names to the %mixin directive, e.g.

      - - - -
      %mixin Set "Fee,Fi,Fo,Fum";
      - - - - -
      - - - -

      Note that the %mixin directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      - - - - -

      36.10 Memory Management

      +

      38.10 Memory Management

      One of the most common issues in generating SWIG bindings for @@ -9712,46 +4608,22 @@ Ruby is proper memory management. The key to proper memory management is clearly defining whether a wrapper Ruby object owns the underlying C struct or C++ class. There are two possibilities:

      - - - -
        - - - -
      • The Ruby object is responsible for freeing the C struct or C++ object
      • - - - -
      • The Ruby object should not free the C struct or C++ object because it will be freed by the underlying C or C++ code
      • - - - -
      - - - -

      To complicate matters, object ownership may transfer from Ruby to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.

      - - - - -

      36.10.1 Mark and Sweep Garbage Collector

      +

      38.10.1 Mark and Sweep Garbage Collector

      Ruby uses a mark and sweep garbage collector. When the garbage @@ -9765,41 +4637,24 @@ 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 default these functions are set to NULL.

      - - - -

      If a C struct or C++ class references any other Ruby objects, then it must provide a "mark" function. The "mark" function should identify any referenced Ruby objects by calling the rb_gc_mark function for each one. Unsurprisingly, this function will be called by the Ruby garbage during the "mark" phase.

      - - - -

      During the sweep phase, Ruby destroys any unused objects. If any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.

      - - - - -

      36.10.2 Object Ownership

      +

      38.10.2 Object Ownership

      As described above, memory management depends on clearly @@ -9809,171 +4664,92 @@ then a "free" function must be registered for the object. If the Ruby object is not responsible for freeing the underlying memory, then a "free" function must not be registered for the object.

      - - - -

      For the most part, SWIG takes care of memory management issues. The rules it uses are:

      - - - -
        - - - -
      • When calling a C++ object's constructor from Ruby, SWIG will assign a "free" function thereby making the Ruby object responsible for freeing the C++ object
      • - - - -
      • When calling a C++ member function that returns a pointer, SWIG will not assign a "free" function thereby making the underlying library responsible for freeing the object.
      • - - - -
      - - - -

      To make this clearer, let's look at an example. Assume we have a Foo and a Bar class.

      - - - -
      -
      /* File "RubyOwernshipExample.h" */

      class Foo
      {
      public:
      Foo() {}
      ~Foo() {}
      };

      class Bar
      {
      Foo *foo_;
      public:
      Bar(): foo_(new Foo) {}
      ~Bar() { delete foo_; }
      Foo* get_foo() { return foo_; }
      Foo* get_new_foo() { return new Foo; }
      void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
      };

      - - - +
      /* File "RubyOwernshipExample.h" */
       
      +class Foo
      +{
      +public:
      +  Foo() {}
      +  ~Foo() {}
      +};
       
      +class Bar
      +{
      +  Foo *foo_;
      +public:
      +  Bar(): foo_(new Foo) {}
      +  ~Bar() { delete foo_; }
      +  Foo* get_foo() { return foo_; }
      +  Foo* get_new_foo() { return new Foo; }
      +  void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
      +};
      - - - -

      First, consider this Ruby code:

      - - - -
      foo = Foo.new
      - - - - -
      - - - -

      In this case, the Ruby code calls the underlying Foo C++ constructor, thus creating a new foo object. By default, SWIG will assign the new Ruby object a "free" function. When the Ruby object is garbage collected, the "free" function will be -called. It in turn will call Foo's destructor.

      - - - - +called. It in turn will call Foo's destructor.

      Next, consider this code:

      - - - -
      -
      bar = Bar.new
      foo = bar.get_foo()
      - - - - - +
      bar = Bar.new
      +foo = bar.get_foo()
      - - - -

      In this case, the Ruby code calls a C++ member function, get_foo. By default, SWIG will not assign the Ruby object a "free" function. Thus, when the Ruby object is garbage collected the underlying C++ foo object is not affected.

      - - - -

      Unfortunately, the real world is not as simple as the examples above. For example:

      - - - -
      -
      bar = Bar.new
      foo = bar.get_new_foo()
      - - - - - +
      bar = Bar.new
      +foo = bar.get_new_foo()
      - - - -

      In this case, the default SWIG behavior for calling member functions is incorrect. The Ruby object should assume ownership of the returned object. This can be done by using the %newobject directive. See Object ownership and %newobject for more information.

      - - - -

      The SWIG default mappings are also incorrect in this case:

      - - - -
      -
      foo = Foo.new
      bar = Bar.new
      bar.set_foo(foo)
      - - - - - +
      foo = Foo.new
      +bar = Bar.new
      +bar.set_foo(foo)
      - - - -

      Without modification, this code will cause a segmentation fault. When the Ruby foo object goes out of scope, it will free the underlying C++ foo @@ -9984,17 +4760,9 @@ Ruby object to the C++ object when the set_foo method is called. This can be done by using the special DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.

      - - - -

      Thus, a correct SWIG interface file correct mapping for these classes is:

      - - - -
      /* File RubyOwnershipExample.i */
       
      @@ -10007,92 +4775,108 @@ classes is:

      class Foo { public: - Foo(); - ~Foo(); + Foo(); + ~Foo(); }; class Bar { - Foo *foo_; + Foo *foo_; public: - Bar(); - ~Bar(); - Foo* get_foo(); + Bar(); + ~Bar(); + Foo* get_foo(); - %newobject get_new_foo; - Foo* get_new_foo(); + %newobject get_new_foo; + Foo* get_new_foo(); - %apply SWIGTYPE *DISOWN {Foo *foo}; - void set_foo(Foo *foo); - %clear Foo *foo; + %apply SWIGTYPE *DISOWN {Foo *foo}; + void set_foo(Foo *foo); + %clear Foo *foo; }; -
      - - - - -
      - - - - -
      - - - - -

      This code can be seen in swig/examples/ruby/tracking.

      - - - - -
      - - - - - -

      36.10.3 Object Tracking

      +

      38.10.3 Object Tracking

      The remaining parts of this section will use the class library shown below to illustrate different memory management techniques. The class library models a zoo and the animals it contains.

      - - - -
      -
      %module zoo

      %{
      #include <string>
      #include <vector>

      #include "zoo.h"
      %}

      class Animal
      {
      private:
      typedef std::vector<Animal*> AnimalsType;
      typedef AnimalsType::iterator IterType;
      protected:
      AnimalsType animals;
      protected:
      std::string name_;
      public:
      // Construct an animal with this name
      Animal(const char* name) : name_(name) {}

      // Return the animal's name
      const char* get_name() const { return name.c_str(); }
      };

      class Zoo
      {
      protected:
      std::vector<animal *=""> animals;

      public:
      // Construct an empty zoo
      Zoo() {}

      /* Create a new animal. */
      static Animal* Zoo::create_animal(const char* name)
      {
      return new Animal(name);
      }

      // Add a new animal to the zoo
      void add_animal(Animal* animal) {
      animals.push_back(animal);
      }

      Animal* remove_animal(size_t i) {
      Animal* result = this->animals[i];
      IterType iter = this->animals.begin();
      std::advance(iter, i);
      this->animals.erase(iter);

      return result;
      }

      // Return the number of animals in the zoo
      size_t get_num_animals() const {
      return animals.size();
      }

      // Return a pointer to the ith animal
      Animal* get_animal(size_t i) const {
      return animals[i];
      }
      };

      - +
      %module zoo
       
      +%{
      +#include <string>
      +#include <vector>
       
      +#include "zoo.h"
      +%}
       
      +class Animal
      +{
      +private:
      +  typedef std::vector<Animal*> AnimalsType;
      +  typedef AnimalsType::iterator IterType;
      +protected:
      +  AnimalsType animals;
      +protected:
      +  std::string name_;
      +public:
      +  // Construct an animal with this name
      +  Animal(const char* name) : name_(name) {}
      + 
      +  // Return the animal's name
      +  const char* get_name() const { return name.c_str(); }
      +};
       
      +class Zoo
      +{
      +protected:
      + std::vector<Animal *> animals;
      + 
      +public:
      +  // Construct an empty zoo
      +  Zoo() {}
      +  
      +  /* Create a new animal. */
      +  static Animal* Zoo::create_animal(const char* name) {
      +    return new Animal(name);
      +  }
      + 
      +  // Add a new animal to the zoo
      +  void add_animal(Animal* animal) {
      +    animals.push_back(animal); 
      +  }
      + 
      +  Animal* remove_animal(size_t i) {
      +    Animal* result = this->animals[i];
      +    IterType iter = this->animals.begin();
      +    std::advance(iter, i);
      +    this->animals.erase(iter);
      +   
      +    return result;
      +  }
      +  
      +  // Return the number of animals in the zoo
      +  size_t get_num_animals() const {
      +    return animals.size(); 
      +  }
      +  
      +  // Return a pointer to the ith animal
      +  Animal* get_animal(size_t i) const {
      +    return animals[i]; 
      +  }
      +};
      - - - - -

      Let's say you SWIG this code and then run IRB:
      - - - - +

      Let's say you SWIG this code and then run IRB:

      - - - -
      $ irb
       irb(main):001:0> require 'example'
      @@ -10121,33 +4905,14 @@ irb(main):008:0> tiger2.get_name()
       
       irb(main):009:0> tiger1.equal?(tiger2)
       => false
      -
       
      - - - - -
      - - - -

      Pay particular attention to the code tiger1.equal?(tiger2). Note that the two Ruby objects are not the same - but they reference -the same underlying C++ object. This can cause problems. For example:
      - - - - - +the same underlying C++ object. This can cause problems. For example:

      - - - -
      irb(main):010:0> tiger1 = nil
       => nil
      @@ -10157,19 +4922,9 @@ irb(main):011:0> GC.start
       
       irb(main):012:0> tiger2.get_name()
       (irb):12: [BUG] Segmentation fault
      -
       
      - - - - -
      - - - -

      After the garbage collector runs, as a result of our call to GC.start, callingtiger2.get_name() causes a segmentation fault. The problem is that when tiger1 @@ -10177,116 +4932,86 @@ is garbage collected, it frees the underlying C++ object. Thus, when tiger2< calls the get_name() method it invokes it on a destroyed object.

      - - - -

      This problem can be avoided if SWIG enforces a one-to-one mapping between Ruby objects and C++ classes. This can be done via the use of the %trackobjects functionality available in SWIG-1.3.26. and later.

      - - - -

      When the %trackobjects is turned on, SWIG automatically keeps track of mappings between C++ objects and Ruby objects. Note that enabling object tracking causes a slight performance degradation. Test results show this degradation to be about 3% to 5% when creating and destroying 100,000 animals in a row.

      - - - -

      Since %trackobjects is implemented as a %feature, it uses the same name matching rules as other kinds of features (see the chapter on "Customization Features") . Thus it can be applied on a class-by-class basis if needed. To fix the example above:

      - - - - -
      - - - - -
      -
      %module example

      %{
      #include "example.h"
      %}

      /* Tell SWIG that create_animal creates a new object */
      %newobject Zoo::create_animal;

      /* Tell SWIG to keep track of mappings between C/C++ structs/classes. */
      %trackobjects;

      %include "example.h"
      - +
      %module example
       
      +%{
      +#include "example.h"
      +%}
       
      +/* Tell SWIG that create_animal creates a new object */
      +%newobject Zoo::create_animal;
       
      +/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */
      +%trackobjects;
       
      +%include "example.h"
      - - - - -

      When this code runs we see:
      - - - - - -
      - - - - - +

      When this code runs we see:

      - - - -
      -
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be37d8>

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be0a18>

      irb(main):004:0> zoo.add_animal(tiger1)
      => nil

      irb(main):006:0> tiger2 = zoo.remove_animal(0)
      => #<Example::Animal:0x2be37d8>

      irb(main):007:0> tiger1.equal?(tiger2)
      => true

      irb(main):008:0> tiger1 = nil
      => nil

      irb(main):009:0> GC.start
      => nil

      irb(main):010:0> tiger.get_name()
      => "tiger1"
      irb(main):011:0>

      +
      $ irb
      +irb(main):001:0> require 'example'
      +=> true
       
      +irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      +=> #<Example::Animal:0x2be37d8>
       
      +irb(main):003:0> zoo = Example::Zoo.new()
      +=> #<Example::Zoo:0x2be0a18>
       
      +irb(main):004:0> zoo.add_animal(tiger1)
      +=> nil
       
      +irb(main):006:0> tiger2 = zoo.remove_animal(0)
      +=> #<Example::Animal:0x2be37d8>
       
      +irb(main):007:0> tiger1.equal?(tiger2)
      +=> true
      +
      +irb(main):008:0> tiger1 = nil
      +=> nil
      +
      +irb(main):009:0> GC.start
      +=> nil
      +
      +irb(main):010:0> tiger.get_name()
      +=> "tiger1"
      +irb(main):011:0>
      - - - -

      For those who are interested, object tracking is implemented by storing Ruby objects in a hash table and keying them on C++ -pointers. The underlying API is:
      - - - - +pointers. The underlying API is:

      - - - -
      -
      static void SWIG_RubyAddTracking(void* ptr, VALUE object);
      static VALUE SWIG_RubyInstanceFor(void* ptr) ;
      static void SWIG_RubyRemoveTracking(void* ptr);
      static void SWIG_RubyUnlinkObjects(void* ptr);
      - - - - - +
      static void SWIG_RubyAddTracking(void* ptr, VALUE object);
      +static VALUE SWIG_RubyInstanceFor(void* ptr) ;
      +static void SWIG_RubyRemoveTracking(void* ptr);
      +static void SWIG_RubyUnlinkObjects(void* ptr);
      - - - -

      When an object is created, SWIG will automatically call the SWIG_RubyAddTracking method. Similarly, when an object is deleted, SWIG will call the SWIG_RubyRemoveTracking. When an object is returned to Ruby from C++, SWIG will use the SWIG_RubyInstanceFor @@ -10294,58 +5019,49 @@ method to ensure a one-to-one mapping from Ruby to C++ objects. Last, the RubyUnlinkObjects method unlinks a Ruby object from its underlying C++ object.

      - - - -

      In general, you will only need to use the SWIG_RubyInstanceFor, which is required for implementing mark functions as shown below. However, if you implement your own free functions (see below) you may -also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects +also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.

      - - - - -

      36.10.4 Mark Functions

      +

      38.10.4 Mark Functions

      With a bit more testing, we see that our class library still -has problems. For example:
      - - - - +has problems. For example:

      - - - -
      -
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2bea6a8>

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be7960>

      irb(main):004:0> zoo.add_animal(tiger1)
      => nil

      irb(main):007:0> tiger1 = nil
      => nil

      irb(main):007:0> GC.start
      => nil

      irb(main):005:0> tiger2 = zoo.get_animal(0)
      (irb):12: [BUG] Segmentation fault
      +
      $ irb
      +irb(main):001:0> require 'example'
      +=> true
       
      +irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      +=> #<Example::Animal:0x2bea6a8>
       
      +irb(main):003:0> zoo = Example::Zoo.new()
      +=> #<Example::Zoo:0x2be7960>
       
      +irb(main):004:0> zoo.add_animal(tiger1)
      +=> nil
       
      +irb(main):007:0> tiger1 = nil
      +=> nil
       
      +irb(main):007:0> GC.start
      +=> nil
      +
      +irb(main):005:0> tiger2 = zoo.get_animal(0)
      +(irb):12: [BUG] Segmentation fault
      - - - -

      The problem is that Ruby does not know that the zoo object contains a reference to a Ruby object. Thus, when Ruby garbage -collects tiger1 +collects tiger1 it frees the underlying C++ object.

      - - - -

      This can be fixed by implementing a mark function as described above in the Mark and Sweep Garbage Collector section. You can specify a mark @@ -10355,10 +5071,6 @@ SWIG's' "features" mechanism it uses the same name matching rules as other kinds of features (see the chapter on "Customization Features" for more details).

      - - - -

      A mark function takes a single argument, which is a pointer to the C++ object being marked; it should, in turn, call rb_gc_mark() for any instances that are @@ -10368,75 +5080,87 @@ objects in the zoo object, look up their Ruby object equivalent, and then call rb_gc_mark(). One possible implementation is:

      - - - -
      -
      %module example

      %{
      #include "example.h"
      %}

      /* Keep track of mappings between C/C++ structs/classes
      and Ruby objects so we can implement a mark function. */
      %trackobjects;

      /* Specify the mark function */
      %markfunc Zoo "mark_Zoo";

      %include "example.h"

      %header %{

      static void mark_Zoo(void* ptr) {
      Zoo* zoo = (Zoo*) ptr;

      /* Loop over each object and tell the garbage collector
      that we are holding a reference to them. */
      int count = zoo->get_num_animals();

      for(int i = 0; i < count; ++i) {
      Animal* animal = zoo->get_animal(i);
      VALUE object = SWIG_RubyInstanceFor(animal);

      if (object != Qnil) {
      rb_gc_mark(object);
      }
      }
      }
      %}

      +
      %module example
       
      +%{
      +#include "example.h"
      +%}
       
      +/* Keep track of mappings between C/C++ structs/classes
      + and Ruby objects so we can implement a mark function. */
      +%trackobjects;
       
      +/* Specify the mark function */
      +%markfunc Zoo "mark_Zoo";
       
      +%include "example.h"
       
      +%header %{
      +
      +static void mark_Zoo(void* ptr) {
      +  Zoo* zoo = (Zoo*) ptr;
      + 
      +  /* Loop over each object and tell the garbage collector
      +  that we are holding a reference to them. */
      +  int count = zoo->get_num_animals();
      + 
      +  for(int i = 0; i < count; ++i) {
      +    Animal* animal = zoo->get_animal(i);
      +    VALUE object = SWIG_RubyInstanceFor(animal);
      + 
      +    if (object != Qnil) {
      +      rb_gc_mark(object);
      +    }
      +  }
      +}
      +%}
      - - - -

      Note the mark function is dependent on the SWIG_RUBY_InstanceFor method, and thus requires that %trackobjects is enabled. For more -information, please refer to the track_object.i test case in the SWIG +information, please refer to the ruby_track_objects.i test case in the SWIG test suite.

      - - - -

      When this code is compiled we now see:

      - - - -
      -
      $ irb
      irb(main):002:0> tiger1=Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be3bf8>

      irb(main):003:0> Example::Zoo.new()
      => #<Example::Zoo:0x2be1780>

      irb(main):004:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2bde9c0>

      irb(main):005:0> zoo.add_animal(tiger1)
      => nil

      irb(main):009:0> tiger1 = nil
      => nil

      irb(main):010:0> GC.start
      => nil
      irb(main):014:0> tiger2 = zoo.get_animal(0)
      => #<Example::Animal:0x2be3bf8>

      irb(main):015:0> tiger2.get_name()
      => "tiger1"
      irb(main):016:0>

      +
      $ irb
      +irb(main):002:0> tiger1=Example::Animal.new("tiger1")
      +=> #<Example::Animal:0x2be3bf8>
       
      +irb(main):003:0> Example::Zoo.new()
      +=> #<Example::Zoo:0x2be1780>
       
      +irb(main):004:0> zoo = Example::Zoo.new()
      +=> #<Example::Zoo:0x2bde9c0>
       
      +irb(main):005:0> zoo.add_animal(tiger1)
      +=> nil
       
      +irb(main):009:0> tiger1 = nil
      +=> nil
       
      +irb(main):010:0> GC.start
      +=> nil
      +irb(main):014:0> tiger2 = zoo.get_animal(0)
      +=> #<Example::Animal:0x2be3bf8>
      +
      +irb(main):015:0> tiger2.get_name()
      +=> "tiger1"
      +irb(main):016:0>
      - - - - -
      - - - - -

      This code can be seen in swig/examples/ruby/mark_function.

      - - - - -

      36.10.5 Free Functions

      +

      38.10.5 Free Functions

      By default, SWIG creates a "free" function that is called when a Ruby object is garbage collected. The free function simply calls the C++ object's destructor.

      - - - -

      However, sometimes an appropriate destructor does not exist or special processing needs to be performed before the destructor is called. Therefore, SWIG allows you to manually specify a "free" @@ -10446,10 +5170,6 @@ SWIG's' "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      - - - -

      IMPORTANT ! - If you define your own free function, then you must ensure that you call the underlying C++ object's destructor. In addition, if object tracking is activated for the object's class, you @@ -10458,10 +5178,6 @@ function (of course call this before you destroy the C++ object). Note that it is harmless to call this method if object tracking if off so it is advised to always call it.

      - - - -

      Note there is a subtle interaction between object ownership and free functions. A custom defined free function will only be called if the Ruby object owns the underlying C++ object. This also to Ruby @@ -10469,48 +5185,29 @@ objects which are created, but then transfer ownership to C++ objects via the use of the disown typemap described above.

      - - - -

      To show how to use the %freefunc directive, let's slightly change our example. Assume that the zoo -object is responsible for freeing animal that it contains. This means -that the Zoo::add_animal -function should be marked with a DISOWN typemap +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:

      - - - -
      $irb
       irb(main):002:0> require 'example'
      @@ -10533,19 +5230,9 @@ irb(main):008:0> GC.start
       
       irb(main):009:0> tiger1.get_name()
       (irb):12: [BUG] Segmentation fault
      -
       
      - - - - -
      - - - -

      The error happens because the C++ animal object is freed when the zoo object is freed. Although this error is unavoidable, we can at least prevent the @@ -10554,18 +5241,9 @@ implementing a custom free function that calls the SWIG_RubyUnlinkObjectsSWIG_RubyUnlinkObjects function notifies SWIG that a Ruby object's underlying C++ object is no longer valid. Once notified, SWIG will intercept any calls from the -existing Ruby object to the destroyed C++ object and raise an exception.
      - - - - - +existing Ruby object to the destroyed C++ object and raise an exception.

      - - - -
      %module example
       
      @@ -10573,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 */ @@ -10586,47 +5263,33 @@ existing Ruby object to the destroyed C++ object and raise an exception.
      %include "example.h" %header %{ - static void free_Zoo(void* ptr) { - Zoo* zoo = (Zoo*) ptr; + static void free_Zoo(void* ptr) { + Zoo* zoo = (Zoo*) ptr; - /* Loop over each animal */ - int count = zoo->get_num_animals(); + /* Loop over each animal */ + int count = zoo->get_num_animals(); - for(int i = 0; i < count; ++i) { - /* Get an animal */ - Animal* animal = zoo->get_animal(i); + for(int i = 0; i < count; ++i) { + /* Get an animal */ + Animal* animal = zoo->get_animal(i); - /* Unlink the Ruby object from the C++ object */ - SWIG_RubyUnlinkObjects(animal); + /* Unlink the Ruby object from the C++ object */ + SWIG_RubyUnlinkObjects(animal); - /* Now remove the tracking for this animal */ - SWIG_RubyRemoveTracking(animal); - } + /* Now remove the tracking for this animal */ + SWIG_RubyRemoveTracking(animal); + } - /* Now call SWIG_RubyRemoveTracking for the zoo */ - SWIG_RubyRemoveTracking(ptr); - - /* Now free the zoo which will free the animals it contains */ - delete zoo; - } + /* Now call SWIG_RubyRemoveTracking for the zoo */ + SWIG_RubyRemoveTracking(ptr); + /* Now free the zoo which will free the animals it contains */ + delete zoo; + } %}
      - - - - -
      - - - -

      Now when we use these objects in IRB we see:

      - - - -
      $irb
       irb(main):002:0> require 'example'
      @@ -10652,159 +5315,82 @@ RuntimeError: This Animal * already released
        from (irb):10:in `get_name'
        from (irb):10
       irb(main):011:0>
      - - - - -
      - - - -

      Notice that SWIG can now detect the underlying C++ object has been freed, and thus raises a runtime exception.

      - - - -

      This code can be seen in swig/examples/ruby/free_function.

      - - - - -

      36.10.6 Embedded Ruby and the C++ Stack

      +

      38.10.6 Embedded Ruby and the C++ Stack

      As has been said, the Ruby GC runs and marks objects before its -sweep phase.  When the garbage collector is called, it will +sweep phase. When the garbage collector is called, it will also try to mark any Ruby objects (VALUE) it finds in the machine registers and in the C++ stack.

      - - - -

      The stack is basically the history of the functions that have been called and also contains local variables, such as the ones you define whenever you do inside a function:

      - - - -
      VALUE obj;
      - - - -

      For ruby to determine where its stack space begins, during initialization a normal Ruby interpreter will call the ruby_init() function which in turn will call a function called Init_stack or -similar.  This function will store a pointer to the location +similar. This function will store a pointer to the location where the stack points at that point in time.

      - - - -

      ruby_init() is presumed to always be called within the main() function of your program and whenever the GC is called, ruby will assume that the memory between the current location in memory and the pointer that was stored previously represents the stack, which may -contain local (and temporary) VALUE ruby objects.   Ruby will +contain local (and temporary) VALUE ruby objects. Ruby will then be careful not to remove any of those objects in that location.

      - - - - -

      So far so good.  For a normal Ruby session, all the +

      So far so good. For a normal Ruby session, all the above is completely transparent and magic to the extensions developer. -  

      - - - - +

      However, with an embedded Ruby, it may not always be possible to -modify main() to make sure ruby_init() is called there.   As +modify main() to make sure ruby_init() is called there. As such, ruby_init() will likely end up being called from within some other -function.  This can lead Ruby to measure incorrectly where the -stack begins and can result in Ruby incorrectly collecting +function. This can lead Ruby to measure incorrectly where the +stack begins and can result in Ruby incorrectly collecting those -temporary VALUE objects that are created once another function +temporary VALUE objects that are created once another function is -called.  The end result: random crashes and segmentation +called. The end result: random crashes and segmentation faults.

      - - - -

      This problem will often be seen in director functions that are -used for callbacks, for example.  

      - - - - +used for callbacks, for example.

      To solve the problem, SWIG can now generate code with director -functions containing the optional macros SWIG_INIT_STACK and -SWIG_RELEASE_STACK.   These macros will try to force Ruby to -reinitiliaze the beginning of the stack the first time a +functions containing the optional macros SWIG_INIT_STACK and +SWIG_RELEASE_STACK. These macros will try to force Ruby to +reinitialize the beginning of the stack the first time a director -function is called.  This will lead Ruby to measure and not -collect any VALUE objects defined from that point on.  

      - - - - +function is called. This will lead Ruby to measure and not +collect any VALUE objects defined from that point on.

      To mark functions to either reset the ruby stack or not, you can use:

      - - - - -
      %initstack -  Class::memberfunction;  // only re-init the stack -in this director method
      - - - - - -%ignorestack Class::memberfunction;  // do not re-init the -stack in this director method
      - - - - - -%initstack   Class;       -        // init the stack on all -the methods of this class
      - - - - - -%initstack;   // all director functions will -re-init the stack
      - +
      +%initstack Class::memberfunction;   // only re-init the stack in this director method
      +%ignorestack Class::memberfunction; // do not re-init the stack in this director method
      +%initstack Class;                   // init the stack on all the methods of this class
      +%initstack;                         // all director functions will re-init the stack
      +
      diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index 58a3c8e55..bf1705d20 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,25 +120,31 @@ 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
         -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)
         -Dsymbol              Define a preprocessor symbol
         -Fstandard            Display error/warning messages in commonly used format
         -Fmicrosoft           Display error/warning messages in Microsoft format
        @@ -145,8 +152,9 @@ can be obtained by typing swig -help or swig
         -Idir                 Add a directory to the file include path
         -lfile                Include a SWIG library file.
         -module name          Set the name of the SWIG module
        --o outfile            Name of output file
        --outcurrentdir	      Set default output dir to current dir instead of input file's path
        +-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
        @@ -154,7 +162,7 @@ can be obtained by typing swig -help or swig
         
         
        -

        5.1.1 Input format

        +

        5.1.1 Input format

        @@ -201,7 +209,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

        @@ -211,7 +219,7 @@ additional files depending on the target language. By default, an input file with the name file.i is transformed into a file file_wrap.c or file_wrap.cxx (depending on whether or not the -c++ option has been used). The name of the -output file can be changed using the -o option. In certain +output C/C++ file can be changed using the -o option. In certain cases, file suffixes are used by the compiler to determine the source language (C, C++, etc.). Therefore, you have to use the -o option to change the suffix of the SWIG-generated wrapper @@ -224,7 +232,7 @@ $ swig -c++ -python -o example_wrap.cpp example.i

        The C/C++ output file created by SWIG often -contains everything that is needed to construct a extension module +contains everything that is needed to construct an extension module for the target scripting language. SWIG is not a stub compiler nor is it usually necessary to edit the output file (and if you look at the output, you probably won't want to). To build the final extension module, the @@ -233,7 +241,7 @@ program to create a shared library.

        -Many target languages will also generate proxy class files in the +For many target languages SWIG will also generate proxy class files in the target language. The default output directory for these language specific files is the same directory as the generated C/C++ file. This can be modified using the -outdir option. For example: @@ -258,10 +266,10 @@ this option the default output directory is the path to the input file. If -o and -outcurrentdir are used together, -outcurrentdir is effectively ignored as the output directory for the language files is the same directory as the -generated C/C++ file if not overidden with -outdir. +generated C/C++ file if not overridden with -outdir.

        -

        5.1.3 Comments

        +

        5.1.3 Comments

        @@ -271,7 +279,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

        @@ -295,7 +303,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

        @@ -326,7 +334,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

        @@ -424,7 +432,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

        @@ -484,10 +492,10 @@ Or in Python: Whenever possible, SWIG creates an interface that closely matches the underlying C/C++ code. However, due to subtle differences between languages, run-time environments, and semantics, it is not always possible to do so. The -next few sections describes various aspects of this mapping. +next few sections describe various aspects of this mapping.

        -

        5.2.1 Basic Type Handling

        +

        5.2.1 Basic Type Handling

        @@ -612,7 +620,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

        @@ -667,7 +675,7 @@ Earlier versions of SWIG incorrectly handled const and created constants instead.

        -

        5.2.3 Constants

        +

        5.2.3 Constants

        @@ -728,7 +736,7 @@ However, for the same conservative reasons even a constant with a simple cast wi

        -#define F_CONST (double) 5            // A floating pointer constant with cast
        +#define F_CONST (double) 5            // A floating point constant with cast
         
        @@ -750,13 +758,13 @@ enum values as assigned by the C compiler.

        The %constant directive is used to more precisely create constants corresponding to different C datatypes. Although it is not -usually not needed for simple values, it is more useful when working +usually needed for simple values, it is more useful when working with pointers and other more complex datatypes. Typically, %constant is only used when you want to add constants to the scripting language interface that are not defined in the original header file.

        -

        5.2.4 A brief word about const

        +

        5.2.4 A brief word about const

        @@ -858,7 +866,7 @@ const int spam = 42;

    • -

      5.2.5 A cautionary tale of char *

      +

      5.2.5 A cautionary tale of char *

      @@ -868,7 +876,7 @@ from a scripting language to a C char *, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, -strings are supposed be immutable. If you violate this, you will probably +strings are supposed to be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world.

      @@ -897,7 +905,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

      @@ -905,7 +913,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

      @@ -971,7 +979,7 @@ simplified and less prone to error.

    -

    5.3.2 Run time pointer type checking

    +

    5.3.2 Run time pointer type checking

    @@ -993,7 +1001,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

    @@ -1034,23 +1042,22 @@ 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)
     

    -In this case f1, f2, and buffer are all +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

    @@ -1110,7 +1117,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

    @@ -1199,7 +1206,7 @@ The corresponding wrapper function will accept arguments of type unsigned int * or size_t *.

    -

    5.4 Other Practicalities

    +

    5.4 Other Practicalities

    @@ -1209,7 +1216,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

    @@ -1240,7 +1247,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

    @@ -1295,7 +1302,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

    @@ -1312,10 +1319,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;
     }
     
    @@ -1327,7 +1334,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 *

    @@ -1456,7 +1463,7 @@ value is not released. -

    5.4.5 Arrays

    +

    5.4.5 Arrays

    @@ -1483,7 +1490,7 @@ void transpose(double (*a)[20]);

    Like C, SWIG does not perform array bounds checking. It is up to the -user to make sure the pointer points a suitably allocated region of memory. +user to make sure the pointer points to a suitably allocated region of memory.

    @@ -1592,7 +1599,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

    @@ -1602,11 +1609,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
     

    @@ -1666,10 +1673,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

    @@ -1711,7 +1718,7 @@ wrapping a header file like this:

    -%rename applies a renaming operation to all future +%rename applies a renaming operation to all future occurrences of a name. The renaming applies to functions, variables, class and structure names, member functions, and member data. For example, if you had two-dozen C++ classes, all with a member function @@ -1767,7 +1774,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

    @@ -1881,6 +1888,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 @@ -1888,11 +1902,22 @@ and a more descriptive one, but the two functions are otherwise equivalent: pattern part is a regular expression in Perl syntax (as supported by the Perl Compatible Regular Expressions (PCRE)) library and the subst string - can contain back-references introduced by '\' or, as backslashes need - to be escaped in C strings, rather by "\\". For example, to remove - any alphabetic prefix before an underscore you could use the following directive: - %rename("regex:/(\\w+)_(.*)/\\2/") - Prefix_PrintPrint + can contain back-references of the form \N where N is a digit + from 0 to 9, or one of the following escape sequences: \l, \L, + \u, \U or \E. The back-references are replaced with the + contents of the corresponding capture group while the escape sequences perform the + case conversion in the substitution string: \l and \L convert to + the lower case, while \u and \U convert to the upper case. The + difference between the elements of each pair is that \l and \u + change the case of the next character only, while \L and \U do + it for all the remaining characters or until \E is encountered. + + Finally please notice that backslashes need to be escaped in C strings, so in + practice "\\" must be used in all these escape sequences. For example, + to remove any alphabetic prefix before an underscore and capitalize the remaining + part you could use the following directive: + %rename("regex:/(\\w+)_(.*)/\\u\\2/") + prefix_printPrint command:cmd @@ -1958,7 +1983,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

    @@ -2056,7 +2081,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

    @@ -2098,7 +2123,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

    @@ -2115,8 +2140,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
     
     
    @@ -2135,7 +2160,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

    @@ -2254,7 +2279,7 @@ disabled using %nocallback. When you do this, the interface now works

    Notice that when the function is used as a callback, special names -such as add_cb is used instead. To call the function +such as add_cb are used instead. To call the function normally, just use the original function name such as add().

    @@ -2288,7 +2313,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

    @@ -2300,13 +2325,13 @@ handle C++ are described in the next section. If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need structure definitions to build an interface, providing definitions -make it possible to access structure members. The accessor functions +makes it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration :

     struct Vector {
    -	double x,y,z;
    +  double x,y,z;
     }
     
     
    @@ -2316,22 +2341,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;
     }
     
    @@ -2370,7 +2395,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

    @@ -2379,7 +2404,7 @@ programs :

     typedef struct {
    -	double x,y,z;
    +  double x,y,z;
     } Vector;
     
     
    @@ -2394,7 +2419,7 @@ that the use of typedef allows SWIG to drop the
     double Vector_x_get(Vector *obj) {
    -	return obj->x;
    +  return obj->x;
     }
     
    @@ -2404,7 +2429,7 @@ If two different names are used like this :

     typedef struct vector_struct {
    -	double x,y,z;
    +  double x,y,z;
     } Vector;
     
     
    @@ -2416,22 +2441,22 @@ 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

    Structures involving character strings require some care. SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated -ASCII strings. When such a member is modified, the previously contents +ASCII strings. When such a member is modified, the previous contents will be released, and the new contents allocated. For example :

     %module mymodule
     ...
     struct Foo {
    -	char *name;
    -	...
    +  char *name;
    +  ...
     }
     
     
    @@ -2441,14 +2466,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;
     }
     
    @@ -2463,7 +2489,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

    @@ -2485,7 +2511,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,7 +2534,7 @@ typedef struct Bar {

    When a structure member is wrapped, it is handled as a pointer, unless the %naturalvar directive is used where it is handled more like a C++ reference (see C++ Member data). -The accessors to the member variable as a pointer is effectively wrapped as follows: +The accessors to the member variable as a pointer are effectively wrapped as follows:

    @@ -2591,7 +2617,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

    @@ -2645,8 +2671,8 @@ struct Bar { // Default constructor generated.

    -Since ignoring the implicit or default destructors most of the times -produce memory leaks, SWIG will always try to generate them. If +Since ignoring the implicit or default destructors most of the time +produces memory leaks, SWIG will always try to generate them. If needed, however, you can selectively disable the generation of the default/implicit destructor by using %nodefaultdtor

    @@ -2676,11 +2702,11 @@ has now been enabled as the default behavior. Note: There are also the -nodefault option and %nodefault directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across -the target languages, and is highly recommended you don't use them. +the target languages, and it is highly recommended you don't use them.

    -

    5.5.6 Adding member functions to C structures

    +

    5.5.6 Adding member functions to C structures

    @@ -2699,8 +2725,8 @@ the following declaration :

     /* file : vector.h */
     ...
    -typedef struct {
    -	double x,y,z;
    +typedef struct Vector {
    +  double x,y,z;
     } Vector;
     
     
    @@ -2718,23 +2744,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); + } };
    @@ -2772,18 +2798,18 @@ of the Vector structure. For example:

    #include "vector.h" %} -typedef struct { - double x,y,z; - %extend { - Vector(double x, double y, double z) { ... } - ~Vector() { ... } - ... - } +typedef struct Vector { + double x,y,z; + %extend { + Vector(double x, double y, double z) { ... } + ~Vector() { ... } + ... + } } Vector;

    -Finally, %extend can be used to access externally written +Note that %extend can be used to access externally written functions provided they follow the naming convention used in this example :

    @@ -2792,19 +2818,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 @@ -2814,18 +2840,49 @@ double Vector_magnitude(Vector *v) { #include "vector.h" %} -typedef struct { - 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() - ... - } +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() + ... + } } Vector; +

    +The name used for %extend should be the name of the struct and not the name of any typedef to the struct. +For example: +

    + +
    +typedef struct Integer {
    +  int value;
    +} Int;
    +%extend Integer { ...  } /* Correct name */
    +%extend Int { ...  } /* Incorrect name */
    +
    +struct Float {
    +  float value;
    +};
    +typedef struct Float FloatValue;
    +%extend Float { ...  } /* Correct name */
    +%extend FloatValue { ...  } /* Incorrect name */
    +
    + +

    +There is one exception to this rule and that is when the struct is anonymously named such as: +

    + +
    +typedef struct {
    +  double value;
    +} Double;
    +%extend Double { ...  } /* Okay */
    +
    +

    A little known feature of the %extend directive is that it can also be used to add synthesized attributes or to modify the @@ -2862,7 +2919,7 @@ For example, consider this interface:

    -typedef struct {
    +typedef struct Person {
       char name[50];
       ...
     } Person;
    @@ -2876,7 +2933,7 @@ the interface as follows to ensure this occurs whenever a name is read or writte
     
     
    -typedef struct {
    +typedef struct Person {
       %extend {
         char name[50];
       }
    @@ -2922,7 +2979,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

    @@ -2930,13 +2987,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;
     
     
    @@ -2948,15 +3005,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;
     
     
    @@ -2968,16 +3025,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 ...
     
    @@ -3006,7 +3063,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

    @@ -3068,7 +3125,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

    @@ -3078,7 +3135,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

    @@ -3114,7 +3171,7 @@ the module upon loading. -

    5.6.2 Code insertion blocks

    +

    5.6.2 Code insertion blocks

    @@ -3184,7 +3241,7 @@ program. For example :

    %{ /* Create a new vector */ static Vector *new_Vector() { - return (Vector *) malloc(sizeof(Vector)); + return (Vector *) malloc(sizeof(Vector)); } %} @@ -3192,7 +3249,7 @@ static Vector *new_Vector() { Vector *new_Vector();
    -

    5.6.3 Inlined code blocks

    +

    5.6.3 Inlined code blocks

    @@ -3204,7 +3261,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)); } %} @@ -3219,7 +3276,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

    @@ -3230,19 +3287,19 @@ 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

    -This section describes the general approach for building interface +This section describes the general approach for building interfaces with SWIG. The specifics related to a particular scripting language are found in later chapters.

    -

    5.7.1 Preparing a C program for SWIG

    +

    5.7.1 Preparing a C program for SWIG

    @@ -3253,9 +3310,9 @@ of steps you can follow to make an interface for a C program :

    • Identify the functions that you want to wrap. It's probably not -necessary to access every single function in a C program--thus, a +necessary to access every single function of a C program--thus, a little forethought can dramatically simplify the resulting scripting -language interface. C header files are particularly good source for +language interface. C header files are a particularly good source for finding things to wrap.
    • Create a new interface file to describe the scripting language @@ -3274,7 +3331,7 @@ Most importantly, define a type before it is used! A C compiler will tell you if the full type information is not available if it is needed, whereas SWIG will usually not warn or error out as it is designed to work without full type information. However, if type information is not specified -correctly, the wrappers can be sub-optimal and even result in uncompileable C/C++ code. +correctly, the wrappers can be sub-optimal and even result in uncompilable C/C++ code.
    • If your program has a main() function, you may need to rename it (read on). @@ -3296,11 +3353,11 @@ 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

      -The preferred method of using SWIG is to generate separate interface +The preferred method of using SWIG is to generate a separate interface file. Suppose you have the following C header file :

      @@ -3349,7 +3406,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?

      @@ -3378,7 +3435,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

    @@ -3394,11 +3451,11 @@ include certain header files by using a %{,%} block like this: #include <GL/glu.h> %} -// Put rest of declarations here +// Put the rest of the declarations here ...

    -

    5.7.5 What to do with main()

    +

    5.7.5 What to do with main()

    @@ -3436,7 +3493,7 @@ program that is more interactive. In many cases, the old or Tcl script.

    -Note: If some cases, you might be inclined to create a +Note: In some cases, you might be inclined to create a scripting language wrapper for main(). If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index b4baca6ae..73b242fa3 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

      @@ -185,7 +186,6 @@ The following C++ features are not currently supported:

      • Overloaded versions of certain operators (new, delete, etc.) -
      • Nested classes, see Nested classes for workarounds.

      @@ -198,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

      @@ -217,7 +217,7 @@ to use the C++ compiler. For example:

       $ swig -c++ -tcl example.i
      -$ c++ -c example_wrap.cxx 
      +$ c++ -fPIC -c example_wrap.cxx 
       $ c++ example_wrap.o $(OBJS) -o example.so
       
      @@ -232,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

      @@ -244,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

      @@ -326,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

      @@ -480,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

      @@ -488,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

      @@ -521,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

      @@ -530,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

      @@ -687,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

      @@ -764,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

      @@ -866,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

      @@ -874,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);
       }
       
       
      @@ -892,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

      @@ -902,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

      @@ -912,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;
       }
       
       
      @@ -933,7 +933,7 @@ class List { public: ... %immutable; - int length; + int length; %mutable; ... }; @@ -960,8 +960,9 @@ Similarly, all data attributes declared as const are wrapped as read-on

      +By default, SWIG uses the const reference typemaps for members that are primitive types. There are some subtle issues when wrapping data members that are -themselves classes. For instance, if you had another class like this, +not primitive types, such as classes. For instance, if you had another class like this,

      @@ -974,7 +975,8 @@ public:

      -then the low-level accessor to the items member actually uses pointers. For example: +then the low-level accessor to the items member actually uses pointers. +For example:

      @@ -999,31 +1001,7 @@ This can be somewhat unnatural for some types. For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language, rather than a pointer to this class. The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps. -It is the %naturalvar directive and is used as follows: -

      - -
      -
      -// All List variables will use const List& typemaps
      -%naturalvar List;
      -
      -// Only Foo::myList will use const List& typemaps
      -%naturalvar Foo::myList;
      -struct Foo {
      -  List myList;
      -};
      -
      -// All variables will use const reference typemaps
      -%naturalvar;
      -
      -
      - -

      -The observant reader will notice that %naturalvar works like any other -feature flag directive, -except it can also be attached to class types. -The first of the example usages above show %naturalvar attaching to the List class. -Effectively this feature changes the way accessors are generated to the following: +It is the naturalvar feature and can be used to effectively change the way accessors are generated to the following:

      @@ -1038,15 +1016,45 @@ void Foo_items_set(Foo *self, const List &value) {

      -In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. +The %naturalvar directive is a macro for, and hence equivalent to, %feature("naturalvar"). It can be used as follows: +

      + +
      +
      +// All List variables will use const List& typemaps
      +%naturalvar List;
      +
      +// Only Foo::myList will use const List& typemaps
      +%naturalvar Foo::myList;
      +struct Foo {
      +  List myList;
      +};
      +
      +// All non-primitive types will use const reference typemaps
      +%naturalvar;
      +
      +
      + +

      +The observant reader will notice that %naturalvar works like any other +feature flag directive but with some extra flexibility. +The first of the example usages above shows %naturalvar attaching to the myList's variable type, that is the List class. +The second usage shows %naturalvar attaching to the variable name. +Hence the naturalvar feature can be used on either the variable's name or type. +Note that using the naturalvar feature on a variable's name overrides any naturalvar feature attached to the variable's type. +

      + +

      +It is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates to a NULL pointer and thereby preventing any potential NULL pointer dereferences. The %naturalvar feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.

      -Other alternatives for turning this feature on globally are to use the swig -naturalvar commandline option -or the module mode option, %module(naturalvar=1) +The naturalvar behavior can also be turned on as a global setting via the -naturalvar commandline option +or the module mode option, %module(naturalvar=1). +However, any use of %feature("naturalvar") will override the global setting.

      @@ -1086,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

      @@ -1177,26 +1185,28 @@ public:

      -This produces uncompileable wrapper code because default values in C++ are +This produces uncompilable wrapper code because default values in C++ are evaluated in the same scope as the member function whereas SWIG evaluates them in the scope of a wrapper function (meaning that the values have to be public).

      -This feature is automatically turned on when wrapping C code with default arguments -and whenever keyword arguments (kwargs) are specified for either C or C++ code. +The compactdefaultargs feature is automatically turned on when wrapping C code with default arguments. +Some target languages will also automatically turn on this feature +if the keyword arguments feature (kwargs) is specified for either C or C++ functions, and the target language supports kwargs, +the compactdefaultargs feature is also automatically turned on. Keyword arguments are a language feature of some scripting languages, for example Ruby and Python. SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used.

      -

      6.8 Protection

      +

      6.8 Protection

      SWIG wraps class members that are public following the C++ conventions, i.e., by explicit public declaration or by the use of - the using directive. In general, anything specified in a + the using directive. In general, anything specified in a private or protected section will be ignored, although the internal code generator sometimes looks at the contents of the private and protected sections so that it can properly generate code for default @@ -1210,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

      @@ -1221,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};
       };
       
       
      @@ -1240,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

      @@ -1301,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

      @@ -1311,7 +1321,7 @@ a declaration like this :

       class Foo {
       public:
      -	double bar(double &a);
      +  double bar(double &a);
       }
       
      @@ -1321,7 +1331,7 @@ has a low-level accessor
       double Foo_bar(Foo *obj, double *a) {
      -	obj->bar(*a);
      +  obj->bar(*a);
       }
       
      @@ -1401,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

      @@ -1505,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

      @@ -1522,7 +1532,7 @@ multiple inheritance. spirit, and target language capabilities, as possible. In most cases, this means that SWIG will parse the non-public inheritance declarations, but that will have no effect in the generated code, -besides the implicit policies derived for constructor and +besides the implicit policies derived for constructors and destructors.

      @@ -1540,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(); }
    @@ -1691,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

    @@ -1823,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

    @@ -1886,7 +1896,7 @@ it might be used like this -

    6.15.1 Dispatch function generation

    +

    6.15.1 Dispatch function generation

    @@ -2011,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

    @@ -2092,13 +2102,13 @@ Therefore, earlier methods will shadow methods that appear later.

    -When wrapping an overloaded function, there is a chance that you will get an error message like this: +When wrapping an overloaded function, there is a chance that you will get a warning message like this:

    -example.i:3: Warning 467: Overloaded foo(int) not supported (no type checking
    -rule for 'int').
    +example.i:3: Warning 467: Overloaded foo(int) not supported (incomplete type checking rule - 
    +no precedence level in typecheck typemap for 'int').
     
    @@ -2107,7 +2117,8 @@ This error means that the target language module supports overloading, but for some reason there is no type-checking rule that can be used to generate a working dispatch function. The resulting behavior is then undefined. You should report this as a bug to the -SWIG bug tracking database. +SWIG bug tracking database +if this is due to one of the typemaps supplied with SWIG.

    @@ -2128,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

    @@ -2471,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: +

    @@ -2557,7 +2569,7 @@ to wrapping methods with default arguments was introduced.
     
     
     
    -

    6.15.4 Comments on overloading

    +

    6.15.4 Comments on overloading

    @@ -2574,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

    @@ -2603,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); @@ -2758,7 +2770,7 @@ are ignored as well as conversion operators.

  • -

    6.17 Class extension

    +

    6.17 Class extension

    @@ -2776,22 +2788,22 @@ 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]; + } + } };

    -This code adds a __str__ method to our class for producing a +This code adds a __str__ method to our class for producing a string representation of the object. In Python, such a method would allow us to print the value of an object using the print command. @@ -2839,7 +2851,13 @@ struct Derived : Base {

    -The %extend directive follows all of the same conventions +The following special variables are expanded if used within a %extend block: +$name, $symname, $overname, $decl, $fulldecl, $parentclassname and $parentclasssymname. +The Special variables section provides more information each of these special variables. +

    + +

    +The %extend directive follows all of the same conventions as its use with C structures. Please refer to the Adding member functions to C structures section for further details.

    @@ -2851,7 +2869,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

    @@ -3121,8 +3139,8 @@ nothing is known about List<int>, you will get a warning message

    -example.h:42. Nothing known about class 'List<int >' (ignored). 
    -example.h:42. Maybe you forgot to instantiate 'List<int >' using %template. 
    +example.h:42: Warning 401. Nothing known about class 'List<int >'. Ignored. 
    +example.h:42: Warning 401. Maybe you forgot to instantiate 'List<int >' using %template. 
     
    @@ -3163,7 +3181,7 @@ Don't worry--if you get the order wrong, SWIG should generate a warning message. Occasionally, you may need to tell SWIG about base classes that are defined by templates, but which aren't supposed to be wrapped. Since SWIG is not able to automatically instantiate templates for this purpose, you must do it manually. To do this, simply -use %template with no name. For example: +use the empty template instantiation, that is, %template with no name. For example:

    @@ -3552,7 +3570,7 @@ It is also possible to separate these declarations from the template class. For template<class T> class List { ... public: - List() { }; + List() { } T get(int index); ... }; @@ -3599,18 +3617,52 @@ and the second will take two integer arguments.

    -Needless to say, SWIG's template support provides plenty of -opportunities to break the universe. That said, an important final -point is that SWIG does not perform extensive error checking of -templates! Specifically, SWIG does not perform type checking nor -does it check to see if the actual contents of the template -declaration make any sense. Since the C++ compiler will hopefully -check this when it compiles the resulting wrapper file, there is no -practical reason for SWIG to duplicate this functionality (besides, -none of the SWIG developers are masochistic enough to want to -implement this right now). +Needless to say, SWIG's template support provides plenty of opportunities to +break the universe. That said, an important final point is that SWIG does +not perform extensive error checking of templates! Specifically, SWIG does +not perform type checking nor does it check to see if the actual contents of the +template declaration make any sense. Since the C++ compiler checks this when it +compiles the resulting wrapper file, there is no practical reason for SWIG to +duplicate this functionality.

    + +

    +As SWIG's template support does not perform type checking %template +can be used as early as after a template declaration. You can, and rarely have +to, use %template before the template parameters have been declared. +For example: +

    + +
    +
    +template <class T> class OuterTemplateClass {};
    +
    +// The nested class OuterClass::InnerClass inherits from the template class
    +// OuterTemplateClass<OuterClass::InnerStruct> and thus the template needs
    +// to be expanded with %template before the OuterClass declaration.
    +%template(OuterTemplateClass_OuterClass__InnerStruct)
    +    OuterTemplateClass<OuterClass::InnerStruct>
    +
    +
    +// Don't forget to use %feature("flatnested") for OuterClass::InnerStruct and
    +// OuterClass::InnerClass if the target language doesn't support nested classes.
    +class OuterClass {
    +    public:
    +        // Forward declarations:
    +        struct InnerStruct;
    +        class InnerClass;
    +};
    +
    +struct OuterClass::InnerStruct {};
    +
    +// Expanding the template at this point with %template is too late as the
    +// OuterClass::InnerClass declaration is processed inside OuterClass.
    +
    +class OuterClass::InnerClass : public OuterTemplateClass<InnerStruct> {};
    +
    +
    +

    Compatibility Note: The first implementation of template support relied heavily on macro expansion in the preprocessor. Templates have been more tightly integrated into @@ -3651,7 +3703,7 @@ as the class name. For example: Similar changes apply to typemaps and other customization features.

    -

    6.19 Namespaces

    +

    6.19 Namespaces

    @@ -4100,7 +4152,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

    @@ -4181,7 +4233,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

    @@ -4259,7 +4311,7 @@ namespace Space {

    -

    6.21 Exception specifications

    +

    6.21 Exception specifications

    @@ -4310,7 +4362,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

    @@ -4360,7 +4412,7 @@ just a single catch handler for the base class, EBase will be generated

    -

    6.23 Pointers to Members

    +

    6.23 Pointers to Members

    @@ -4410,7 +4462,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->()

    @@ -4427,7 +4479,7 @@ around some other class. For example: template<class T> class SmartPtr { T *pointee; public: - ... + SmartPtr(T *p) : pointee(p) { ... } T *operator->() { return pointee; } @@ -4447,7 +4499,7 @@ typedef SmartPtr<Foo_Impl> Foo; // Create smart pointer Foo Foo make_Foo() { - return SmartPtr(new Foo_Impl()); + return SmartPtr<Foo_Impl>(new Foo_Impl()); } // Do something with smart pointer Foo @@ -4455,6 +4507,9 @@ void do_something(Foo f) { printf("x = %d\n", f->x); f->bar(); } + +// Call the wrapped smart pointer proxy class in the target language 'Foo' +%template(Foo) SmartPtr<Foo_Impl>; @@ -4619,11 +4674,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: +

    @@ -4640,11 +4696,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();
       }
     };
    @@ -4791,7 +4847,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

    @@ -4954,151 +5010,71 @@ public:

    -

    6.27 Nested classes

    +

    6.27 Nested classes

    -There is some support for nested structs and unions when wrapping C code, -see Nested structures for further details. -The added complexity of C++ compared to C means this approach does not work well for -C++ code (when using the -c++ command line option). -For C++, a nested class is treated much like an opaque pointer, so anything useful within the nested class, such as its -methods and variables, are not accessible from the target language. -True nested class support may be added to SWIG in the future, however, -until then some of the following workarounds can be applied to improve the situation. +If the target language supports the nested classes concept (like Java), the nested C++ classes +are wrapped as nested target language proxy classes. (In case of Java - "static" nested classes.) +Only public nested classes are wrapped. Otherwise there is little difference between nested and +normal classes.

    -

    -It might be possible to use partial class information as often you can accept that the nested class is not needed, -especially if it is not actually used in any methods you need from the target language. -Imagine you are wrapping the following Outer class which contains a nested class Inner. -The easiest thing to do is turn a blind eye to the warning that SWIG generates, or simply suppress it: +If the target language doesn't support nested classes directly, or the support is not implemented in the +language module (like for python currently), then the visible nested classes are moved to the same name +space as the containing class (nesting hierarchy is "flattened"). The same behaviour may be turned on for +C# and Java by the %feature ("flatnested"); If there is a class with the same name in the outer namespace +the inner class (or the global one) may be renamed or ignored:

    -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::Inner;
    -
    -class Outer {
    -public:
    -  class Inner {
    -    public:
    -      ...
    -  };
    -  Inner getInner();
    -  void useInner(const Inner& inner);
    -  ...
    -};
    -
    -
    - -

    -Note that if Inner can be used as an opaque type, the default wrapping approach suffices. -For example, if the nested class does not need to be created from the target language, but can be obtained via a method -call, such as the getInner() method above, the returned value can then be passed around, such as passed into the -useInner() method. -

    - -

    -With some more effort the above situation can be improved somewhat and a nested class can be constructed and used -from the target language much like any other non-nested class. Assuming we have the Outer class in a header file: -

    - -
    -
    -// File outer.h
    -class Outer {
    -public:
    -  class Inner {
    -    public:
    -      int var;
    -      Inner(int v = 0) : var(v) {}
    -  };
    -  Inner getInner();
    -  void useInner(const Inner& inner);
    -};
    -
    -
    - -

    -The following interface file works around the nested class limitations by redefining the nested class as a global class. -A typedef for the compiler and the nestedworkaround -feature flag is also required in -order for the generated wrappers to compile. This flag simply removes all the type information from SWIG, so SWIG treats -the nested class as if it had not been parsed at all. -

    - -
    -
    -// File : example.i
    -%module example
    -
    -// Redefine nested class in global scope in order for SWIG to generate
    -// a proxy class. Only SWIG parses this definition.
    -class Inner {
    +%rename (Bar_Foo) Bar::Foo;
    +class Foo {};
    +class Bar {
       public:
    -    int var;
    -    Inner(int v = 0) : var(v) {}
    +  class Foo {};
     };
    -
    -%nestedworkaround Outer::Inner;
    -
    -%{
    -#include "outer.h"
    -%}
    -%include "outer.h"
    -
    -// We've fooled SWIG into thinking that Inner is a global class, so now we need
    -// to trick the C++ compiler into understanding this apparent global type.
    -%{
    -typedef Outer::Inner Inner;
    -%}
     

    -The downside to this approach is a more complex interface file and having to maintain two definitions of Inner, -the real one and the one in the interface file that SWIG parses. -However, the upside is that all the methods/variables in the nested class are available from the target language -as a proxy class is generated instead of treating the nested class as an opaque type. -The proxy class can be constructed from the target language and passed into any methods accepting the nested class. -Also note that the original header file is parsed unmodified. +If a nested class, within an outer class, has to be used as a template parameter within the outer class, then the template will +have to be instantiated with %template before the beginning of the outer class. +An example can be found in the +Templates section.

    -Finally, conditional compilation can be used as a workaround to comment out nested class definitions in the actual headers, -assuming you are able to modify them. +Compatibility Note: +Prior to SWIG-3.0.0, there was limited nested class support. Nested classes were treated as opaque pointers. +However, there was a workaround for nested class support in these older versions requiring the user to replicate +the nested class in the global scope, adding in a typedef for the nested class in the global scope and +using the "nestedworkaround" feature on the nested class. This resulted in approximately the +same behaviour as the "flatnested" feature. With proper nested class support now available in SWIG-3.0.0, this +feature has been deprecated and no longer works requiring code changes. If you see the following warning:

    -
    +
    -// File outer.h
    -class Outer {
    -public:
    -#ifndef SWIG
    -  class Inner {
    -    public:
    -      ...
    -  };
    -#endif
    -  ...
    -};
    +example.i:8: Warning 126: The nestedworkaround feature is deprecated
     

    -This workaround used to be common when SWIG could not deal with nested classes particulary well. -This should just be a last resort for unusual corner cases now as SWIG can parse nested classes and even handle nested template classes fairly well. +consider using the "flatnested" feature discussed above which generates a non-nested proxy class, like the +"nestedworkaround" feature did. Alternatively, use the default nested class code generation, which may generate an +equivalent to a nested proxy class in the target language, depending on the target language support.

    -Compatibility Note: SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature +SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature and the generated code resulting from parsing nested classes did not always compile. Nested class warnings could also not be suppressed using %warnfilter.

    -

    6.28 A brief rant about const-correctness

    +

    6.28 A brief rant about const-correctness

    @@ -5156,7 +5132,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 new file mode 100644 index 000000000..aa4a3e99f --- /dev/null +++ b/Doc/Manual/Scilab.html @@ -0,0 +1,2148 @@ + + + +SWIG and Scilab + + + + + + + +

    39 SWIG and Scilab

    + + + + + + +

    +Scilab is a scientific software package for numerical computations providing a powerful open computing environment for engineering and scientific applications that is mostly compatible with MATLAB. More information can be found at www.scilab.org. +

    + +

    +This chapter explains how to use SWIG for Scilab. After this introduction, you should be able to generate with SWIG a Scilab external module from a C/C++ library. +

    + + +

    39.1 Preliminaries

    + + +

    +SWIG for Scilab supports Linux. Other operating sytems haven't been tested. +

    + +

    +Scilab is supported from version 5.3.3 onwards. +The forthcoming version 6, as of January 2015, is also supported. +

    + +

    +SWIG for Scilab supports C language. C++ is partially supported. See A basic tour of C/C++ wrapping for further details. +

    + + +

    39.2 Running SWIG

    + + +

    +Let's see how to use SWIG for Scilab on a small example. +
    +In this example we bind from C a function and a global variable into Scilab. The SWIG interface (stored in a file named example.i), is the following: +

    + +
    +%module example
    +
    +%inline %{
    +double Foo = 3.0;
    +
    +int fact(int n) {
    +    if (n < 0) {
    +        return 0;
    +    }
    +    else if (n == 0) {
    +        return 1;
    +    }
    +    else {
    +        return n * fact(n-1);
    +    }
    +}
    +%}
    +
    + +

    +Note: a code in an %inline section is both parsed and wrapped by SWIG, and inserted as is in the wrapper source file. +

    + + +

    39.2.1 Generating the module

    + + +

    +The module is generated using the swig executable and its -scilab option. +

    + +
    +$ swig -scilab example.i
    +
    + +

    +This command generates two files: +

    +
      +
    • example_wrap.c: a C source file containing the wrapping code and also here the wrapped code (the fact() and Foo definitions)
    • +
    • loader.sce: a Scilab script used to load the module into Scilab +
    + +

    +Note: if the following error is returned: +

    + +
    +:1: Error: Unable to find 'swig.swg'
    +:3: Error: Unable to find 'scilab.swg'
    +
    + +

    +it may be because the SWIG library is not found. Check the SWIG_LIB environment variable or your SWIG installation. +

    + +

    +Note: SWIG for Scilab can work in two modes related to the way the module is built, see the Building modes section for details. +This example uses the builder mode. +

    + + +

    +The swig executable has several other command line options you can use. See Scilab command line options for further details. +

    + + +

    39.2.2 Building the module

    + + +

    +To be loaded in Scilab, the wrapper has to be built into a dynamic module (or shared library). +

    + +

    +The commands to compile and link the wrapper (with gcc) into the shared library libexample.so are: +

    + +
    +$ gcc -fPIC -c -I/usr/local/include/scilab example_wrap.c
    +$ gcc -shared example_wrap.o -o libexample.so
    +
    + +

    +Note: we supposed in this example that the path to the Scilab include directory is /usr/local/include/scilab (which is the case in a Debian environment), this should be changed for another environment. +

    + +

    39.2.3 Loading the module

    + + +

    +Loading a module is done by running the loader script in Scilab: +

    + +
    +--> exec loader.sce
    +
    + +

    +Scilab should output the following messages: +

    + +
    +Shared archive loaded.
    +Link done.
    +
    + +

    +which means that Scilab has successfully loaded the shared library. The module functions and other symbols are now available in Scilab. +

    + +

    39.2.4 Using the module

    + + +

    +In Scilab, the function fact() is simply called as following: +

    + +
    +--> fact(5)
    +ans  =
    +
    +    120.
    +
    + +

    For the Foo global variable, the accessors need to be used: + +

    +--> Foo_get
    +ans  =
    +
    +    3.
    +
    +--> Foo_set(4);
    +
    +--> Foo_get
    +ans  =
    +
    +    4.
    +
    + +

    +Note: for conciseness, we assume in the subsequent Scilab code examples that the modules have been beforehand built and loaded in Scilab. +

    + +

    39.2.5 Scilab command line options

    + + +

    +The following table lists the Scilab specific command line options in addition to the generic SWIG options: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    -builderGenerate the Scilab builder script
    -buildercflags <cflags>Add <cflags> to the builder compiler flags
    -builderldflags <ldflags>Add <ldlags> to the builder linker flags
    -buildersources <files>Add the (comma separated) files <files> to the builder sources
    -builderverbositylevel <level>Set the build verbosity level to <level> (default 0: off, 2: high)
    -builderflagscript <file>Use the Scilab script <file> to configure the compiler and linker flags
    -gatewayxml <gateway_id>Generate the gateway XML with the given <gateway_id>
    + +

    +These options can be displayed with: +

    + +
    +$ swig -scilab -help
    +
    + + +

    39.3 A basic tour of C/C++ wrapping

    + + +

    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). +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

    + + +

    +In Scilab 5.x, identifier names are composed of 24 characters maximum (this limitation should disappear from Scilab 6.0 onwards). +
    Thus long function or variable names may be truncated and this can cause ambiguities. +

    +

    This happens especially when wrapping structs/classes, for which the wrapped function name is composed of the struct/class name and field names. +In these cases, the %rename directive can be used to choose a different Scilab name. +

    + +

    39.3.3 Functions

    + + +

    +Functions are wrapped as new Scilab built-in functions. For example: +

    + +
    +%module example
    +
    +%inline %{
    +int fact(int n) {
    +  if (n > 1)
    +    return n * fact(n - 1);
    +  else
    +    return 1;
    +}
    +%}
    +
    + +

    +creates a built-in function fact(n) in Scilab: +

    + +
    +--> fact(4)
    +ans  =
    +
    +    24.
    +
    + +

    39.3.3.1 Argument passing

    + + +

    +In the above example, the function parameter is a primitive type and is marshalled by value. +So this function is wrapped without any additional customization. +Argument values are converted between C types and Scilab types through type mappings. +There are several default type mappings for primitive and complex types, described later in the Scilab typemaps section. +

    + +

    +When a parameter is not passed by value, such as a pointer or reference, SWIG does not know if it is an input, output (or both) parameter. +The INPUT, OUTPUT, INOUT typemaps defined in the typemaps.i library can be used to specify this. +

    + +

    +Let's see this on two simple functions: sub() which has an output parameter, and inc(), which as input/output parameter: +

    + +
    +%module example
    +
    +%include <typemaps.i>
    +
    +extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
    +extern void inc(int *INOUT, int *INPUT);
    +
    +%{
    +void sub(int *x, int *y, int *result) {
    +  *result = *x - *y;
    +}
    +void inc(int *x, int *delta) {
    +  *x = *x + *delta;
    +}
    +%}
    +
    + +

    +In Scilab, parameters are passed by value. The output (and inout) parameters are returned as the result of the functions: +

    + +
    +--> sub(5, 3)
    + ans  =
    +
    +    2.
    +
    +--> inc(4, 3)
    + ans  =
    +
    +    7.
    +
    + +

    39.3.3.2 Multiple output arguments

    + + +

    +A C function can have several output parameters. They can all be returned as results of the wrapped function as Scilab supports multiple return values from a function +when using the typemaps.i library. +If the C function itself returns a result, this is returned first before the parameter outputs. +

    + +

    +The example below shows this for a C function returning 2 values and a result: +

    + +
    +%module example
    +
    +%include <typemaps.i>
    +
    +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;
    +}
    +%}
    +
    + +
    + +
    +--> [ret, q, r] = divide(20, 6)
    + r  =
    +
    +    2.
    + q  =
    +
    +    3.
    + ret  =
    +
    +    1.
    +
    + + +

    39.3.4 Global variables

    + + +

    +Global variables are manipulated through generated accessor functions. +For example, for a given Foo global variable, SWIG actually generates two functions: Foo_get() to get the value of Foo, and Foo_set() to set the value. +These functions are used as following: +

    + +
    +--> exec loader.sce;
    +--> c = Foo_get();
    +
    +--> Foo_set(4);
    +
    +--> c
    +c =
    +
    +    3.
    +
    +--> Foo_get()
    +ans  =
    +
    +    4.
    +
    + +

    +It works for variables of primitive type, but also for non-primitive types: arrays, and structs/classes which are described later. +For now, an example with two global primitive arrays x and y is shown: +

    + +
    +%module example
    +
    +%inline %{
    +int x[10];
    +double y[7];
    +
    +void initArrays()
    +{
    +  int i;
    +  for (i = 0; i < 10; i++)
    +    x[i] = 1;
    +  for (i = 0; i < 7; i++)
    +    y[i] = 1.0f;
    +}
    +%}
    +
    + +

    +It works the same:

    + +
    +--> exec loader.sce
    +
    +--> initArrays();
    +--> x_get()
    + ans  =
    +
    +    1.    1.    1.    1.    1.    1.    1.    1.    1.    1.
    +
    +--> y_set([0:6] / 10);
    +--> y_get()
    + ans  =
    +
    +    0.    0.1    0.2    0.3    0.4    0.5    0.6
    +
    + + +

    39.3.5 Constants and enumerations

    + + +

    39.3.5.1 Constants

    + + +

    +There is not any constant in Scilab. By default, C/C++ constants are wrapped as getter functions. For example, for the following constants: +

    + +
    +%module example
    +#define    ICONST      42
    +#define    FCONST      2.1828
    +#define    CCONST      'x'
    +#define    CCONST2     '\n'
    +#define    SCONST      "Hello World"
    +#define    SCONST2     "\"Hello World\""
    +
    + +

    +the following getter functions are generated: +

    + +
    +--> exec loader.sce;
    +--> ICONST_get();
    + ans  =
    +
    +    42.
    +
    +--> FCONST_get();
    + ans  =
    +
    +    2.1828
    +
    +--> CCONST_get();
    + ans  =
    +
    +    x
    +
    +--> CCONST2_get();
    + ans  =
    +
    +--> SCONST_get();
    + ans  =
    +
    +    Hello World
    +
    +--> SCONST2_get();
    + ans  =
    +
    +    "Hello World"
    +
    +--> EXPR_get();
    + ans  =
    +
    +    48.5484
    +
    +--> iconst_get();
    + ans  =
    +
    +    37.
    +
    +--> fconst_get();
    + ans  =
    +
    +    3.14
    +
    + +

    +There is another mode in which constants are wrapped as Scilab variables. +The variables are easier to use than functions, but the drawback is that variables are not constant and so can be modified. +

    + +

    +This mode can be enabled/disabled at any time in the interface file with %scilabconst(), which +works like all the other %feature directives. +Use the argument value "1" to enable and "0" to disable this mode. +For example in this mode the previous constants: +

    + +
    +%module example
    +
    +%scilabconst(1);
    +#define    ICONST      42
    +#define    FCONST      2.1828
    +#define    CCONST      'x'
    +#define    CCONST2     '\n'
    +#define    SCONST      "Hello World"
    +#define    SCONST2     "\"Hello World\""
    +
    + +

    +are mapped to Scilab variables, with the same name: +

    + +
    +--> exec loader.sce;
    +--> ICONST
    + ans  =
    +
    +    42
    +
    +--> FCONST
    + ans  =
    +
    +    2.1828
    +
    +--> CCONST
    + ans  =
    +
    +    x
    +
    +--> CCONST2
    + ans  =
    +
    +--> SCONST
    + ans  =
    +
    +    Hello World
    +
    +--> SCONST2
    + ans  =
    +
    +    "Hello World"
    +
    +--> EXPR
    + ans  =
    +
    +    48.5484
    +
    +--> iconst
    + ans  =
    +
    +    37
    +
    +--> fconst
    + ans  =
    +
    +    3.14
    +
    + +

    39.3.5.2 Enumerations

    + + +

    +The wrapping of enums is the same as for constants. +By default, enums are wrapped as getter functions. +For example, with the following enumeration: +

    + +
    %module example
    +typedef enum { RED, BLUE, GREEN } color;
    +
    + +

    +a getter function will be generated for each value of the enumeration: +

    + +
    +--> exec loader.sce;
    +--> RED_get()
    + ans  =
    +
    +    0.
    +
    +--> BLUE_get()
    + ans  =
    +
    +    1.
    +
    +--> GREEN_get()
    + ans  =
    +
    +    2.
    +
    + +

    +The %scilabconst() feature is also available for enumerations: +

    + +
    %module example
    +%scilabconst(1) color;
    +typedef enum { RED, BLUE, GREEN } color;
    +
    + +
    + +
    +--> exec loader.sce;
    +--> RED
    + ans  =
    +
    +    0.
    +
    +--> BLUE
    + ans  =
    +
    +    1.
    +
    +--> GREEN
    + ans  =
    +
    +    2.
    +
    +
    + +

    39.3.6 Pointers

    + + +

    +Pointers are supported by SWIG. A pointer can be returned from a wrapped C/C++ function, stored in a Scilab variable, and used in input argument of another C/C++ function. +

    +

    +Also, thanks to the SWIG runtime which stores informations about types, pointer types are tracked between exchanges Scilab and the native code. Indeed pointer types are stored alongside the pointer adress. +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. +

    + +

    +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: +

    + +
    +%module example
    +
    +%{
    +#include <stdio.h>
    +%}
    +
    +FILE *fopen(const char *filename, const char *mode);
    +int fputs(const char *, FILE *);
    +int fclose(FILE *);
    +
    + +

    +These functions can be used the same way as in C from Scilab: +

    + +
    +--> example_Init();
    +
    +--> f = fopen("junk", "w");
    +--> typeof(f)
    + ans  =
    +
    +  _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

    + + +

    +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. +

    + +

    +SWIG comes with two pointer utility functions: +

    +
      +
    • SWIG_this(): returns the address value of a pointer
    • +
    • SWIG_ptr(): creates a pointer from an address value
    • +
    + +

    +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");
    +--> fputs("Hello", f);
    +--> addr = SWIG_this(f)
    + ans  =
    +
    +    8219088.
    +
    +--> p = SWIG_ptr(addr);
    +--> typeof(p)
    +ans  =
    +
    +  pointer
    +
    +--> fputs(" World", p);
    +--> fclose(f);
    +
    + + +

    39.3.6.2 Null pointers:

    + +

    +Using the previous SWIG_this() and SWIG_ptr(), it is possible to create and check null pointers: +

    + +
    +--> p = SWIG_ptr(0);
    +--> SWIG_this(p) == 0
    + ans  =
    +
    +    T
    +
    + + +

    39.3.7 Structures

    + + +

    +Structs exist in Scilab, but C structs are not (at least in this version of SWIG) mapped to Scilab structs. +A C structure is wrapped through low-level accessor functions, i.e. functions that give access to the member variables of this structure. +In Scilab, a structure is manipulated through a pointer which is passed as an argument to the accessor functions. +

    + +

    +Let's see it on an example of a struct with two members: +

    + +
    +%module example
    +
    +%inline %{
    +
    +typedef struct {
    +    int x;
    +    int arr[4];
    +} Foo;
    +
    +%}
    +
    + +

    +Several functions are generated: +

    +
      +
    • a constructor function new_Foo() which returns a pointer to a newly created struct Foo.
    • +
    • two member getter functions Foo_x_get(), Foo_arr_get(), to get the values of x and y for the struct pointer (provided as the first parameter to these functions)
    • +
    • two member setter functions Foo_x_set(), Foo_arr_set(), to set the values of x and y for the struct pointer (provided as the first parameter to these functions).
    • +
    • a destructor function delete_Foo() to release the struct pointer.
    • +
    + + +Usage example: +

    + +
    +--> f = new_Foo();
    +--> Foo_x_set(f, 100);
    +--> Foo_x_get(f)
    +ans  =
    +
    +    100.
    +
    +--> Foo_arr_set(f, [0:3]);
    +--> Foo_arr_get(f)
    +ans  =
    +
    +    0.    1.    2.    3.
    +
    +--> delete_Foo(f);
    +
    + + +

    +Members of a structure that are also structures are also accepted and wrapped as a pointer: +

    + +
    +%module example
    +
    +%inline %{
    +
    +typedef struct {
    +  int x;
    +} Bar;
    +
    +typedef struct {
    +  Bar b;
    +} Foo;
    +
    +%}
    +
    + +
    + +
    +--> b = new_Bar();
    +--> Bar_x_set(b, 20.);
    +
    +--> f = new_Foo();
    +--> Foo_b_set(f, b);
    +
    +--> b2 = Foo_b_get(f);
    +--> Bar_x_get(b2);
    +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: +

    + +

    +--> example_Init();
    +--> b = new_Bar();
    +--> typeof(b)
    + ans  =
    +
    +    _p_Bar
    +--> delete_Bar(b);
    +
    + +

    39.3.8 C++ classes

    + + +

    +Classes do not exist in Scilab. The classes are wrapped the same way as structs. +Low-level accessor functions are generated for class members. +Also, constructor and destructor functions are generated to create and destroy an instance of the class. +

    + +

    +For example, the following class: +

    + +
    +%module example
    +
    +%inline %{
    +
    +class Point {
    +public:
    +  int x, y;
    +  Point(int _x, int _y) : x(_x), y(_y) {}
    +  double distance(const Point& rhs) {
    +    return sqrt(pow(x-rhs.x, 2) + pow(y-rhs.y, 2));
    +  }
    +  void set(int _x, int _y) {
    +    x=_x;
    +    y=_y;
    +  }
    +};
    +
    +%}
    +
    + +

    +can be used in Scilab like this: +

    + +
    +--> p1 = Point_new(3, 5);
    +--> p2 = Point_new(1, 2);
    +--> p1.distance(p2)
    +ans  =
    +
    +    3.6056
    +
    +--> delete_Point(p1);
    +--> delete_Point(p2);
    +
    + +

    +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

    + + +

    +Inheritance is supported. SWIG knows the inheritance relationship between classes. +

    + +

    +A function is only generated for the class in which it is actually declared. +But if one of its parameters is a class, any instance of a derived class is accepted as the argument. +

    + +

    +This mechanism also applies for accessor functions: they are generated only in the class in which they are defined. +But any instance of a derived class can be used as the argument to these accessor functions. +

    + +

    +For example, let's take a base class Shape and two derived classes Circle and Square: +

    + +
    +%module example
    +
    +%inline %{
    +
    +class Shape {
    +public:
    +  double x, y;
    +  void set_location(double _x, double _y) { x = _x; y = _y; }
    +  virtual double get_perimeter() { return 0; };
    +};
    +
    +class Circle : public Shape {
    +public:
    +  int radius;
    +  Circle(int _radius): radius(_radius) {};
    +  virtual double get_perimeter() { return 6.28 * radius; }
    +};
    +
    +class Square : public Shape {
    +public:
    +  int size;
    +  Square(int _size): size(_size) {};
    +  virtual double get_perimeter() { return 4 * size; }
    +};
    +
    +%}
    +
    + +

    +To set the location of the Circle, we have to use the function set_location() of the parent Shape. +But we can use either use the get_perimeter() function of the parent class or the derived class: +

    + +
    +--> c = new_Circle(3);
    +
    +--> Shape_set_location(c, 2, 3);
    +--> Shape_x_get(c)
    + ans  =
    +
    +    2.
    +
    +--> Circle_get_perimeter(c)
    + ans  =
    +
    +    18.84
    +
    +--> Shape_get_perimeter(c)
    + ans  =
    +
    +    18.84
    +
    + +

    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

    + + +

    +In C++ objects can be passed by value, pointer, reference, or by an array: +

    +
    +%module example
    +
    +%{
    +#include <sciprint.h>
    +%}
    +
    +%inline %{
    +
    +class Foo {
    +public:
    +  Foo(int _x) : x(_x) {}
    +  int x;
    +};
    +
    +void spam1(Foo *f)  { sciprint("%d\n", f->x); }   // Pass by pointer
    +void spam2(Foo &f)  { sciprint("%d\n", f.x); }    // Pass by reference
    +void spam3(Foo f)   { sciprint("%d\n", f.x); }    // Pass by value
    +void spam4(Foo f[]) { sciprint("%d\n", f[0].x); } // Array of objects
    +
    +%}
    +
    +

    + +In SWIG, there is no real distinction between these. +So in Scilab, it is perfectly legal to do this: +

    +
    +--> f = new_Foo()
    +--> spam1(f)
    +3
    +--> spam2(f)
    +3
    +--> spam3(f)
    +3
    +--> spam4(f)
    +3
    +
    + +

    +Similar behaviour occurs for return values. For example, if you had functions like this: +

    +
    +Foo *spam5();
    +Foo &spam6();
    +Foo  spam7();
    +
    +

    +All these functions will return a pointer to an instance of Foo. +As the function spam7 returns a value, new instance of Foo has to be allocated, and a pointer on this instance is returned. +

    + +

    39.3.12 C++ templates

    + + +

    +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. +For example: +

    + +
    +%module example
    +
    +template<class T1, class T2, class T3>
    +struct triplet {
    +  T1 first;
    +  T2 second;
    +  T3 third;
    +  triplet(const T1& a, const T2& b, const T3& c) {
    +    third = a; second = b; third = c;
    +  }
    +};
    +
    +%template(IntTriplet) triplet<int,int,int>;
    +
    + +

    +Then in Scilab: +

    + +
    +
    +--> t = new_IntTriplet(3, 4, 1);
    +
    +--> IntTriplet_first_get(t)
    + ans  =
    +
    +    3.
    +
    +--> IntTriplet_second_get(t)
    + ans  =
    +
    +    4.
    +
    +--> IntTriplet_third_get(t)
    + ans  =
    +
    +    1.
    +
    +--> delete_IntTriplet(t);
    +
    +
    + +

    +More details on template support can be found in the templates documentation. +

    + +

    39.3.13 C++ operators

    + + +

    +C++ operators are partially supported. +Operator overloading exists in Scilab, but a C++ operator is not (in this version) wrapped by SWIG as a Scilab operator, but as a function. +It is not automatic, you have to rename each operator (with the instruction %rename) with the suitable wrapper name. +

    + +

    +Let's see it with an example of class with two operators + and double(): +

    + +
    +%module example
    +
    +%rename(plus) operator +;
    +%rename(toDouble) operator double();
    +
    +%inline %{
    +
    +class Complex {
    +public:
    +  Complex(double re, double im) : real(re), imag(im) {};
    +
    +  Complex operator+(const Complex& other) {
    +    double result_real = real + other.real;
    +    double result_imaginary = imag + other.imag;
    +    return Complex(result_real, result_imaginary);
    +  }
    +  operator double() { return real; }
    +private:
    +  double real;
    +  double imag;
    +};
    +
    +%}
    +
    + +
    + +
    +--> c1 = new_Complex(3, 7);
    +
    +--> c2 = Complex_plus(c, new_Complex(1,1));
    +
    +--> Complex_toDouble(c2)
    + ans  =
    +
    +    4.
    +
    + + +

    39.3.14 C++ namespaces

    + + +

    +SWIG is aware of C++ namespaces, but does not use it for wrappers. +The module is not broken into submodules, nor do namespace appear in functions names. +All the namespaces are all flattened in the module. +For example with one namespace Foo: +

    + +
    +
    +%module example
    +
    +%inline %{
    +
    +namespace foo {
    +  int fact(int n) {
    +    if (n > 1)
    +      return n * fact(n-1);
    +    else
    +      return 1;
    +  }
    +
    +  struct Vector {
    +    double x,y,z;
    +  };
    +};
    +
    +%}
    +
    +
    +
    + +

    +In Scilab, there is no need to the specify the Foo namespace: +

    + +
    +
    +--> fact(3)
    + ans  =
    +
    +   6.
    +
    +--> v = new_Vector();
    +--> Vector_x_set(v, 3.4);
    +--> Vector_y_get(v)
    + ans  =
    +
    +   0.
    +
    +
    + +

    +If your program has more than one namespace, name conflicts can be resolved using %rename. +For example: +

    + +
    +
    +%rename(Bar_spam) Bar::spam;
    +
    +namespace Foo {
    +  int spam();
    +}
    +
    +namespace Bar {
    +  int spam();
    +}
    +
    +
    + +

    +Note: the nspace feature is not supported. +

    + + +

    39.3.15 C++ exceptions

    + + +

    +Scilab does not natively support exceptions, but has errors. +When an exception is thrown, SWIG catches it, and sets a Scilab error. An error message is displayed in Scilab. +For example: +

    + +
    +%module example
    +
    +%inline %{
    +void throw_exception() throw(char const *) {
    +  throw "Bye world !";
    +}
    +%}
    +
    + +
    + +
    +-->throw_exception()
    +  !--error 999
    +SWIG/Scilab: Exception (char const *) occured: Bye world !
    +
    + +

    +Scilab has a try-catch mechanism (and a similar instruction execstr()) to handle exceptions. +It can be used with the lasterror() function as following: +

    + +
    +--> execstr('throw_exception()', 'errcatch');
    + ans  =
    +
    +    999.
    +
    +--> lasterror()
    + ans  =
    +
    +    SWIG/Scilab: Exception (char const *) occured: Bye world !
    +
    + +

    +If the function has a throw exception specification, SWIG can automatically map the exception type and set an appropriate Scilab error message. +It works for a few primitive types, and also for STL exceptions (the library std_except.i has to be included to get the STL exception support): +

    + +
    +%module example
    +
    +%include <std_except.i>
    +
    +%inline %{
    +void throw_int() throw(int) {
    +  throw 12;
    +}
    +
    +void throw_stl_invalid_arg(int i) throw(std::invalid_argument) {
    +  if (i < 0)
    +    throw std::invalid_argument("argument is negative.");
    +}
    +%}
    +
    + +
    + +
    +--> throw_int();
    +            !--error 999
    +SWIG/Scilab: Exception (int) occured: 12
    +
    +-->throw_stl_invalid_arg(-1);
    +                          !--error 999
    +SWIG/Scilab: ValueError: argument is negative.
    +
    + +

    +More complex or custom exception types require specific exception typemaps to be implemented in order to specifically handle a thrown type. +See the SWIG C++ documentation for more details. +

    + +

    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.1 Default primitive type mappings

    + + +

    +The following table provides the equivalent Scilab type for C/C++ primitive types. +

    + +
    + + + + + + + + + + + + + + + + + + + + +
    C/C++ typeScilab type
    boolboolean
    charstring
    signed chardouble or int8
    unsigned chardouble or uint8
    shortdouble or int16
    unsigned shortdouble or uint16
    intdouble or int32
    unsigned intdouble or uint32
    longdouble or int32
    unsigned longdouble or uint32
    signed long longnot supported in Scilab 5.x
    unsigned long longnot supported in Scilab 5.x
    floatdouble
    doubledouble
    char * or char[]string
    +
    + +

    +Notes: +

    +
      +
    • In Scilab the double type is far more used than any integer type. +This is why integer values (int32, uint32, ...) are automatically converted to Scilab double values when marshalled from C into Scilab. +Additionally on input to a C function, Scilab double values are converted into the related integer type. +
    • +
    • +When an integer is expected, if the input is a double, the value must be an integer, i.e. it must not have any decimal part, otherwise a SWIG value error occurs. +
    • +
    • +In SWIG for Scilab 5.x, the long long type is not supported, since Scilab 5.x does not have a 64-bit integer type. +The default behaviour is for SWIG to generate code that will give a runtime error if long long type arguments are used from Scilab. +
    • +
    + + + + +

    39.4.2 Arrays

    + + +

    +Typemaps are available by default for arrays. Primitive type arrays are automatically converted to/from Scilab matrices. +Typemaps are also provided to handle members of a struct or class that are arrays. +

    + +

    +In input, the matrix is usually one-dimensional (it can be either a row or column vector). But it can also be a two-dimensional matrix. +Warning: in Scilab, the values are column-major ordered, unlike in C, which is row-major ordered. +

    + +

    +The type mappings used for arrays is the same for primitive types, described earlier. +This means that, if needed, a Scilab double vector is converted in input into the related C integer array +and this C integer array is automatically converted on output into a Scilab double vector. +Note that unlike scalars, no control is done for arrays when a double is converted into an integer. +

    + +

    +The following example illustrates all this:

    + +
    +%module example
    +
    +%#include <stdio.h>
    +
    +%inline %{
    +
    +void printArray(int values[], int len) {
    +  int i = 0;
    +  for (i = 0; i < len; i++) {
    +    printf("%s %d %s", i==0?"[":"", values[i], i==len-1?"]\n":"");
    +  }
    +}
    +%}
    +
    + +
    + +
    +--> printArray([0 1 2 3], 4)
    +[ 0  1  2  3 ]
    +
    +--> printArray([0.2; -1.8; 2; 3.7], 4)
    +[ 0  -1  2  3 ]
    +
    +--> printArray([0 1; 2 3], 4)
    +[ 0  2  1  3 ]
    +
    +--> printArray([0; 1; 2; 3], 4)
    +[ 0  1  2  3 ]
    +
    + +

    39.4.3 Pointer-to-pointers

    + + +

    +There are no specific typemaps for pointer-to-pointers, they are are mapped as pointers in Scilab. +

    + +

    +Pointer-to-pointers are sometimes used to implement matrices in C. The following is a an example of this: +

    + + +
    +%module example
    +%inline %{
    +
    +// Returns the matrix [1 2; 3 4];
    +double **create_matrix() {
    +  double **M;
    +  int i;
    +  M = (double **) malloc(2 * sizeof(double *));
    +  for (i = 0; i < 2; i++) {
    +    M[i] = (double *) malloc(2 * sizeof(double));
    +    M[i][0] = 2 * i + 1;
    +    M[i][1] = 2 * i + 2;
    +  }
    +  return M;
    +}
    +
    +// Gets the item M(i,j) value
    +double get_matrix(double **M, int i, int j) {
    +  return M[i][j];
    +}
    +
    +// Sets the item M(i,j) value to be val
    +void set_matrix(double **M, int i, int j, double val) {
    +  M[i][j] = val;
    +}
    +
    +// Prints a matrix (2,2) to console
    +void print_matrix(double **M, int nbRows, int nbCols) {
    +  int i, j;
    +  for (i = 0; i < 2; i++) {
    +    for (j = 0; j < 2; j++) {
    +      printf("%3g ", M[i][j]);
    +    }
    +    printf("\n");
    +  }
    +}
    +
    +%}
    +
    + +

    + These functions are used like this in Scilab: +

    + +
    +--> m = create_matrix();
    +
    +--> print_matrix(m);
    +   1.   2.
    +   3.   4.
    +
    +--> set_matrix(m, 1, 1, 5.);
    +
    +--> get_matrix(m, 1, 1)
    + ans  =
    +
    +    5.
    +
    + + +

    39.4.4 Matrices

    + + +

    +The matrix.i library provides a set of typemaps which can be useful when working with one-dimensional and two-dimensional matrices. +

    + +

    +In order to use this library, just include it in the interface file: +

    + +
    +  %include <matrix.i>
    +
    + + +

    +Several typemaps are available for the common Scilab matrix types: +

    +
      +
    • double
    • +
    • int
    • +
    • char *
    • +
    • bool
    • +
    + +

    +For example: for a matrix of int, we have the typemaps, for input: +

    +
      +
    • (int *IN, int IN_ROWCOUNT, int IN_COLCOUNT)
    • +
    • (int IN_ROWCOUNT, int IN_COLCOUNT, int *IN)
    • +
    • (int *IN, int IN_SIZE)
    • +
    • (int IN_SIZE, int *IN)
    • +
    + +

    +and output: +

    +
      +
    • (int **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT)
    • +
    • (int *OUT_ROWCOUNT, int *OUT_COLCOUNT, int **OUT)
    • +
    • (int **OUT, int *OUT_SIZE)
    • +
    • (int *OUT_SIZE, int **OUT)
    • +
    + +

    +They marshall a Scilab matrix type into the appropriate 2 or 3 C parameters. +The following is an example using the typemaps in this library: +

    + +
    +%module example
    +
    +%include <matrix.i>
    +
    +%apply (int *IN, int IN_ROWCOUNT, int IN_COLCOUNT) { (int *matrix, int matrixNbRow, int matrixNbCol) };
    +%apply (int **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT) { (int **outMatrix, int *outMatrixNbRow, int *outMatrixNbCol) };
    +
    +%inline %{
    +
    +void absolute(int *matrix, int matrixNbRow, int matrixNbCol,
    +  int **outMatrix, int *outMatrixNbRow, int *outMatrixNbCol) {
    +  int i, j;
    +  *outMatrixNbRow = matrixNbRow;
    +  *outMatrixNbCol = matrixNbCol;
    +  *outMatrix = malloc(matrixNbRow * matrixNbCol * sizeof(int));
    +  for (i=0; i < matrixNbRow * matrixNbCol; i++) {
    +    (*outMatrix)[i] = matrix[i] > 0 ? matrix[i]:-matrix[i];
    +  }
    +}
    +
    +%}
    +
    + +
    + +
    +--> absolute([-0 1 -2; 3 4 -5])
    + ans  =
    +
    +    0.    1.    2.
    +    3.    4.    5.
    +
    + +

    +The remarks made earlier for arrays also apply here: +

    +
      +
    • The values of matrices in Scilab are column-major orderered,
    • +
    • There is no control while converting double values to integers, double values are truncated without any checking or warning.
    • +
    + +

    39.4.5 STL

    + + +

    +The STL library wraps some containers defined in the STL (Standard Template Library), so that they can be manipulated in Scilab. +This library also provides the appropriate typemaps to use the containers in functions and variables. +

    + +

    +The list of wrapped sequence containers are: +

    +
      +
    • std::vector
    • +
    • std::list
    • +
    • std::deque
    • +
    + +

    +And associative containers are: +

    +
      +
    • std::set
    • +
    • std::multiset
    • +
    + +

    +Typemaps are available for the following container types: +

    + +
      +
    • double
    • +
    • float
    • +
    • int
    • +
    • string
    • +
    • bool
    • +
    • pointer
    • +
    + +

    +Containers of other item types are not supported. Using them does not break compilation, but provokes a runtime error. +Containers of enum are not supported yet. +

    + +

    +In order to use the STL, the library must first be included in the SWIG interface file: +

    + +
    +%include <stl.i>
    +
    + +

    Then for each container used, the appropriate template must be instantiated, in the std namespace: +

    +namespace std {
    +    %template(IntVector)    vector<int>;
    +    %template(DoubleVector) vector<double>;
    +}
    +
    + +

    +Additionally, the module initialization function has to be executed first in Scilab, so that all the types are known to Scilab. +See the Module initialization section for more details. +

    + + +

    +Because in Scilab matrices exist for basic types only, a sequence container of pointers is mapped to a Scilab list. +For other item types (double, int, string...) the sequence container is mapped to a Scilab matrix. +

    + +

    +The first example below shows how to create a vector (of int) in Scilab, add some values to the vector and pass it as an argument of a function. +It also shows, thanks to the typemaps, that we can also pass a Scilab matrix of values directly into the function: +

    + +
    +%module example
    +
    +%include <stl.i>
    +
    +namespace std {
    +  %template(IntVector) vector<int>;
    +}
    +
    +%{
    +#include <numeric>
    +%}
    +
    +%inline %{
    +
    +double average(std::vector<int> v) {
    +  return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
    +}
    +
    +%}
    +
    + +
    + +
    +--> example_Init();
    +
    +--> v = new_IntVector();
    +
    +--> for i = 1:4
    +-->     IntVector_push_back(v, i);
    +--> end;
    +
    +--> average(v)
    + ans  =
    +
    +    2.5
    +
    +--> average([0 1 2 3])
    + ans  =
    +
    +    2.5
    +
    +--> delete_IntVector();
    +
    + + +

    +In the second example, a set of struct (Person) is wrapped. +A function performs a search in this set, and returns a subset. As one can see, the result in Scilab is a list of pointers: +

    + +
    +%module example
    +
    +%include <stl.i>
    +
    +%{
    +#include <string>
    +%}
    +
    +%inline %{
    +
    +struct Person {
    +  Person(std::string _name, int _age) : name(_name), age(_age) {};
    +  std::string name;
    +  int age;
    +};
    +typedef Person * PersonPtr;
    +
    +%}
    +
    +namespace std {
    +  %template(PersonPtrSet) set<PersonPtr>;
    +}
    +
    +%inline %{
    +
    +std::set<PersonPtr> findPersonsByAge(std::set<PersonPtr> persons, int minAge, int maxAge) {
    +  std::set<PersonPtr> foundPersons;
    +  for (std::set<PersonPtr>::iterator it = persons.begin(); it != persons.end(); it++) {
    +    if (((*it)->age >= minAge) && ((*it)->age <= maxAge)) {
    +      foundPersons.insert(*it);
    +    }
    +  }
    +  return foundPersons;
    +}
    +
    +%}
    +
    + +
    + +
    +--> example_Init();
    +
    +--> joe = new_Person("Joe", 25);
    +--> susan = new_Person("Susan", 32);
    +--> bill = new_Person("Bill", 50);
    +
    +--> p = new_PersonPtrSet();
    +--> PersonPtrSet_insert(p, susan);
    +--> PersonPtrSet_insert(p, joe);
    +--> PersonPtrSet_insert(p, bill);
    +
    +--> l = findPersonsByAge(p, 20, 40);
    +
    +--> size(l)
    + ans  =
    +
    +    2.
    +
    +--> Person_name_get(l(1))
    +ans  =
    +
    +    Susan
    +
    +--> Person_name_get(l(2))
    + ans  =
    +
    +    Joe
    +
    +--> delete_PersonPtrSet(p);
    +
    + +

    39.5 Module initialization

    + + +

    +The wrapped module contains an initialization function to: +

    +
      +
    • initialize the SWIG runtime, needed for pointer type tracking or when working with the STL
    • +
    • initialize the module constants and enumerations declared with %scilabconst()
    • +
    + +

    +This initialization function should be executed at the start of a script, before the wrapped library has to be used. +

    + +

    +The function has the name of the module suffixed by _Init. +For example, to initialize the module example: +

    + +
    +--> example_Init();
    +
    + +

    39.6 Building modes

    + + +

    +The mechanism to load an external module in Scilab is called Dynamic Link and works with dynamic modules (or shared libraries, .so files). +

    + +

    +To produce a dynamic module, when generating the wrapper, there are two possibilities, or build modes: +

    +
      +
    • the nobuilder mode, this is the default mode in SWIG. The user is responsible of the build. +
    • the builder mode. In this mode, Scilab is responsible of building. +
    + +

    39.6.1 No-builder mode

    + + +

    +In this mode, used by default, SWIG generates the wrapper sources, which have to be manually compiled and linked. +A loader script loader.sce is also produced, this one is executed further in Scilab to load the module. +

    + +

    +This mode is the best option to use when you have to integrate the module build into a larger build process. +

    + + +

    39.6.2 Builder mode

    + + +

    +In this mode, in addition to the wrapper sources, SWIG produces a builder Scilab script (builder.sce), which is executed in Scilab to build the module. +In a few words, the Scilab ilib_build() command is used, which produces the shared library file, and the loader script loader.sce (and also a cleaner script cleaner.sce). +

    + +

    +An advantage of this mode is that it hides all the complexity of the build and other platform issues. +Also it allows the module to conform to a Scilab external module convention which is that an external module should be simply built by calling a builder script. +

    + +

    +The builder mode is activated with the -builder SWIG option. +In this mode, the following SWIG options may be used to setup the build: +

    + +
      +
    • -buildersources: to add sources to the build (several files must be separated by a comma)
    • +
    • -buildercflags: to add flags to the builder compiler flags, for example to set library dependencies include paths
    • +
    • -builderldflags: to add flags to the linker flags, for example to set library dependency names and paths
    • +
    + +

    +Let's give an example how to build a module example, composed of two sources, and using a library dependency: +

    +
      +
    • the sources are baa1.c and baa2.c (and are stored in in the current directory)
    • +
    • the library is libfoo in /opt/foo (headers stored in /opt/foo/include, and shared library in /opt/foo/lib)
    • +
    + +

    +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

    + + +

    +In this part we give some details about the generated Scilab scripts. +

    + +

    39.7.1 Builder script

    + + +

    +builder.sce is the name of the builder script generated by SWIG in builder mode. It contains code like this: +

    +
    +ilib_name = "examplelib";
    +files = ["example_wrap.c"];
    +libs = [];
    +table = ["fact","_wrap_fact";"Foo_set","_wrap_Foo_set";"Foo_get","_wrap_Foo_get";];
    +ilib_build(ilib_name,table,files,libs);
    +
    + +

    +ilib_build(lib_name,table,files,libs) is used to create shared libraries, and to generate a loader file used to dynamically load the shared library into Scilab. +

    + +
      +
    • ilib_name: a character string, the generic name of the library without path and extension.
    • +
    • files: string matrix containing objects files needed for shared library creation.
    • +
    • libs: string matrix containing extra libraries needed for shared library creation.
    • +
    • table: two column string matrix containing a table of pairs of 'scilab function name', 'C function name'.
    • +
    + +

    39.7.2 Loader script

    + + +

    +The loader script is used to load in Scilab all the module functions. When loaded, these functions can be used as other Scilab functions. +

    + +

    +The loader script loader.sce contains code similar to: +

    + +
    +// ------------------------------------------------------
    +// generated by builder.sce: Please do not edit this file
    +// ------------------------------------------------------
    +
    +libexamplelib_path = get_file_path('loader.sce');
    +list_functions = [             'fact';
    +            'Foo_set';
    +            'Foo_get';
    +];
    +addinter(libexamplelib_path+'/libexamplelib.so','libexamplelib',list_functions);
    +// remove temp. variables on stack
    +clear libexamplelib_path;
    +clear list_functions;
    +clear get_file_path;
    +// ------------------------------------------------------
    +
    + +

    +addinter(files,spname,fcts) performs dynamic linking of a compiled C interface function. +

    +
      +
    • files: a character string or a vector of character strings defining the object files (containing the C interface functions) to link with.
    • +
    • spname: a character string. Name of interface routine entry point.
    • +
    • fcts: vector of character strings. The name of new Scilab function.
    • +
    + + +

    39.8 Other resources

    + + +
      +
    • Example use cases can be found in the Examples/scilab directory.
    • +
    • The test suite in the Examples/test-suite/scilab can be another source of useful use cases.
    • +
    • The Scilab API is used in the generated code and is a useful reference when examining the output.
    • +
    • This guide describes the Scilab external modules structure and files, in particular the files that are generated by SWIG for Scilab.
    • +
    + diff --git a/Doc/Manual/Scripting.html b/Doc/Manual/Scripting.html index e6a2eee24..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

      @@ -293,14 +295,14 @@ A proxy class is a special kind of object that gets created in a scripting language to access a C/C++ class (or struct) in a way that looks like the original structure (that is, it proxies the real C++ class). For example, if you -have the following C definition :

      +have the following C++ definition :

       class Vector {
       public:
      -	Vector();
      -	~Vector();
      -	double x,y,z;
      +  Vector();
      +  ~Vector();
      +  double x,y,z;
       };
       
      @@ -334,18 +336,18 @@ Finally, in Tcl :
       Vector v
      -v configure -x 3 -y 4 -z 13
      +v configure -x 3 -y 4 -z -13
       
       

      -When proxy classes are used, two objects are at really work--one in +When proxy classes are used, two objects are really at work--one in the scripting language, and an underlying C/C++ object. Operations affect both objects equally and for all practical purposes, it appears as if you are simply manipulating a C/C++ object.

      -

      4.3 Building scripting language extensions

      +

      4.3 Building scripting language extensions

      @@ -353,32 +355,27 @@ The final step in using a scripting language with your C/C++ application is adding your extensions to the scripting language itself. There are two primary approaches for doing this. The preferred technique is to build a dynamically loadable -extension in the form a shared library. Alternatively, you can +extension in the form of a shared library. Alternatively, you can recompile the scripting language interpreter with your extensions added to it.

      -

      4.3.1 Shared libraries and dynamic loading

      +

      4.3.1 Shared libraries and dynamic loading

      To create a shared library or DLL, you often need to look at the manual pages for your compiler and linker. However, the procedure -for a few common machines is shown below:

      +for a few common platforms is shown below:

       # Build a shared library for Solaris
      -gcc -c example.c example_wrap.c -I/usr/local/include
      +gcc -fpic -c example.c example_wrap.c -I/usr/local/include
       ld -G example.o example_wrap.o -o example.so
       
       # Build a shared library for Linux
       gcc -fpic -c example.c example_wrap.c -I/usr/local/include
       gcc -shared example.o example_wrap.o -o example.so
      -
      -# Build a shared library for Irix
      -gcc -c example.c example_wrap.c -I/usr/local/include
      -ld -shared example.o example_wrap.o -o example.so
      -
       

      @@ -405,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

    @@ -452,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 1151de1d5..bfa58f1ae 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -1,16 +1,19 @@ - + -SWIG-2.0 Documentation +SWIG-3.0 Documentation + -

    SWIG-2.0 Documentation

    +

    SWIG-3.0 Documentation

    -Last update : SWIG-2.0.6 (30 April 2012) +

    +Last update : SWIG-3.0.9 (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 f55a7f139..31fae0321 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -1,12 +1,13 @@ - + SWIG and Tcl + -

      37 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.

        -

        37.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.

        -

        37.1.1 Getting the right header files

        +

        40.1.1 Getting the right header files

        @@ -127,19 +128,20 @@ this is the case, you should probably make a symbolic link so that tcl.h -

        37.1.2 Compiling a dynamic module

        +

        40.1.2 Compiling a dynamic module

        The preferred approach to building an extension module is to compile it into -a shared object file or DLL. To do this, you will need to compile your program +a shared object file or DLL. Assuming you have code you need to link to in a file +called example.c, you will need to compile your program using commands like this (shown for Linux):

         $ swig -tcl example.i
        -$ gcc -c example.c
        -$ gcc -c example_wrap.c -I/usr/local/include
        +$ gcc -fPIC -c example.c
        +$ gcc -fPIC -c example_wrap.c -I/usr/local/include
         $ gcc -shared example.o example_wrap.o -o example.so
         
        @@ -159,10 +161,10 @@ of the module. If the name of your SWIG module is "example", the name of the corresponding object file should be "example.so". The name of the module is specified using the %module directive or the - -module command line option. + -module command line option.

        -

        37.1.3 Static linking

        +

        40.1.3 Static linking

        @@ -206,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

      @@ -228,7 +230,7 @@ minimal in most situations (and quite frankly not worth the extra hassle in the opinion of this author).

      -

      37.1.4 Using your module

      +

      40.1.4 Using your module

      @@ -356,7 +358,7 @@ to the default system configuration (this requires root access and you will need the man pages).

      -

      37.1.5 Compilation of C++ extensions

      +

      40.1.5 Compilation of C++ extensions

      @@ -373,8 +375,8 @@ compiler. For example:

       % swig -c++ -tcl example.i
      -% g++ -c example.cxx
      -% g++ -c example_wrap.cxx -I/usr/local/include
      +% g++ -fPIC -c example.cxx
      +% g++ -fPIC -c example_wrap.cxx -I/usr/local/include
       % g++ -shared example.o example_wrap.o -o example.so
       
      @@ -386,8 +388,8 @@ Solaris, you often need to add an extra library -lCrun like this:
       % swig -c++ -tcl example.i
      -% CC -c example.cxx
      -% CC -c example_wrap.cxx -I/usr/local/include
      +% CC -KPIC -c example.cxx
      +% CC -KPIC -c example_wrap.cxx -I/usr/local/include
       % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
       
      @@ -439,7 +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.

      -

      37.1.6 Compiling for 64-bit platforms

      +

      40.1.6 Compiling for 64-bit platforms

      @@ -466,7 +468,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      37.1.7 Setting a package prefix

      +

      40.1.7 Setting a package prefix

      @@ -485,7 +487,7 @@ option will append the prefix to the name when creating a command and call it "Foo_bar".

      -

      37.1.8 Using namespaces

      +

      40.1.8 Using namespaces

      @@ -503,11 +505,11 @@ name, but you can override it using the -prefix option.

      -When the -namespace option is used, objects in the module +When the -namespace option is used, objects in the module are always accessed with the namespace name such as Foo::bar.

      -

      37.2 Building Tcl/Tk Extensions under Windows 95/NT

      +

      40.2 Building Tcl/Tk Extensions under Windows 95/NT

      @@ -518,7 +520,7 @@ covers the process of using SWIG with Microsoft Visual C++. although the procedure may be similar with other compilers.

      -

      37.2.1 Running SWIG from Developer Studio

      +

      40.2.1 Running SWIG from Developer Studio

      @@ -576,7 +578,7 @@ MSDOS > tclsh80 %

    -

    37.2.2 Using NMAKE

    +

    40.2.2 Using NMAKE

    @@ -624,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 @@ -639,7 +641,7 @@ to get you started. With a little practice, you'll be making lots of Tcl extensions.

    -

    37.3 A tour of basic C/C++ wrapping

    +

    40.3 A tour of basic C/C++ wrapping

    @@ -650,7 +652,7 @@ classes. This section briefly covers the essential aspects of this wrapping.

    -

    37.3.1 Modules

    +

    40.3.1 Modules

    @@ -684,7 +686,7 @@ To fix this, supply an extra argument to load like this: -

    37.3.2 Functions

    +

    40.3.2 Functions

    @@ -709,7 +711,7 @@ like you think it does: % -

    37.3.3 Global variables

    +

    40.3.3 Global variables

    @@ -789,7 +791,7 @@ extern char *path; // Read-only (due to %immutable) -

    37.3.4 Constants and enums

    +

    40.3.4 Constants and enums

    @@ -873,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.

    -

    37.3.5 Pointers

    +

    40.3.5 Pointers

    @@ -969,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.

    -

    37.3.6 Structures

    +

    40.3.6 Structures

    @@ -979,7 +981,7 @@ This provides a very natural interface. For example,

     struct Vector {
    -	double x,y,z;
    +  double x,y,z;
     };
     
     
    @@ -1251,7 +1253,7 @@ Note: Tcl only destroys the underlying object if it has ownership. See the memory management section that appears shortly.

    -

    37.3.7 C++ classes

    +

    40.3.7 C++ classes

    @@ -1282,7 +1284,7 @@ you can use it in Tcl like this: % x insert Lager % x get 1 Stout -% puts [l cget -length] +% puts [x cget -length] 3 % @@ -1318,7 +1320,7 @@ In Tcl, the static member is accessed as follows: -

    37.3.8 C++ inheritance

    +

    40.3.8 C++ inheritance

    @@ -1367,7 +1369,7 @@ For instance: It is safe to use multiple inheritance with SWIG.

    -

    37.3.9 Pointers, references, values, and arrays

    +

    40.3.9 Pointers, references, values, and arrays

    @@ -1421,7 +1423,7 @@ to hold the result and a pointer is returned (Tcl will release this memory when the return value is garbage collected).

    -

    37.3.10 C++ overloaded functions

    +

    40.3.10 C++ overloaded functions

    @@ -1544,7 +1546,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

    -

    37.3.11 C++ operators

    +

    40.3.11 C++ operators

    @@ -1646,7 +1648,7 @@ There are ways to make this operator appear as part of the class using the % Keep reading.

    -

    37.3.12 C++ namespaces

    +

    40.3.12 C++ namespaces

    @@ -1710,7 +1712,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

    -

    37.3.13 C++ templates

    +

    40.3.13 C++ templates

    @@ -1762,7 +1764,7 @@ More details can be found in the SWIG and C++ -

    37.3.14 C++ Smart Pointers

    +

    40.3.14 C++ Smart Pointers

    @@ -1846,7 +1848,7 @@ simply use the __deref__() method. For example: -

    37.4 Further details on the Tcl class interface

    +

    40.4 Further details on the Tcl class interface

    @@ -1859,7 +1861,7 @@ of low-level details were omitted. This section provides a brief overview of how the proxy classes work.

    -

    37.4.1 Proxy classes

    +

    40.4.1 Proxy classes

    @@ -1924,7 +1926,7 @@ function. This allows objects to be encapsulated objects that look a lot like as shown in the last section.

    -

    37.4.2 Memory management

    +

    40.4.2 Memory management

    @@ -2112,7 +2114,7 @@ typemaps--an advanced topic discussed later.

    -

    37.5 Input and output parameters

    +

    40.5 Input and output parameters

    @@ -2300,7 +2302,7 @@ set c [lindex $dim 1] -

    37.6 Exception handling

    +

    40.6 Exception handling

    @@ -2364,7 +2366,7 @@ Tcl extension by specifying the following in an interface file : $action // Gets substituted by actual function call } catch (RangeError) { - Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); + Tcl_SetResult(interp, (char *)"Array index out-of-bounds", TCL_STATIC); return TCL_ERROR; } } @@ -2383,7 +2385,7 @@ exception handler to only apply to specific methods like this: $action } catch (RangeError) { - Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); + Tcl_SetResult(interp, (char *)"Array index out-of-bounds", TCL_STATIC); return TCL_ERROR; } } @@ -2393,7 +2395,7 @@ exception handler to only apply to specific methods like this: $action } catch (RangeError) { - Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); + Tcl_SetResult(interp, (char *)"Array index out-of-bounds", TCL_STATIC); return TCL_ERROR; } } @@ -2418,7 +2420,7 @@ For example: $action } catch (RangeError) { - Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); + Tcl_SetResult(interp, (char *)"Array index out-of-bounds", TCL_STATIC); return TCL_ERROR; } } @@ -2434,7 +2436,7 @@ Since SWIG's exception handling is user-definable, you are not limited to C++ ex See the chapter on "Customization Features" for more examples.

    -

    37.7 Typemaps

    +

    40.7 Typemaps

    @@ -2451,7 +2453,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Tcl interface.

    -

    37.7.1 What is a typemap?

    +

    40.7.1 What is a typemap?

    @@ -2464,8 +2466,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); @@ -2502,8 +2505,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); @@ -2525,8 +2529,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;
    @@ -2568,7 +2573,7 @@ parameter is omitted):
     
    -

    37.7.2 Tcl typemaps

    +

    40.7.2 Tcl typemaps

    @@ -2706,7 +2711,7 @@ Initialize an argument to a value before any conversions occur. Examples of these methods will appear shortly.

    -

    37.7.3 Typemap variables

    +

    40.7.3 Typemap variables

    @@ -2777,7 +2782,7 @@ properly assigned. The Tcl name of the wrapper function being created. -

    37.7.4 Converting a Tcl list to a char **

    +

    40.7.4 Converting a Tcl list to a char **

    @@ -2839,7 +2844,7 @@ argv[2] = Larry 3 -

    37.7.5 Returning values in arguments

    +

    40.7.5 Returning values in arguments

    @@ -2881,7 +2886,7 @@ result, a Tcl function using these typemaps will work like this : % -

    37.7.6 Useful functions

    +

    40.7.6 Useful functions

    @@ -2920,7 +2925,6 @@ int Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);

     Tcl_Obj  *Tcl_NewStringObj(char *str, int len);
    -void      Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len);
     char     *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len);
     void      Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
     
    @@ -2958,7 +2962,7 @@ int Tcl_IsShared(Tcl_Obj *obj);
    -

    37.7.7 Standard typemaps

    +

    40.7.7 Standard typemaps

    @@ -2975,10 +2979,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;
     }
     
    @@ -3036,13 +3040,14 @@ work)
    -%typemap(out) char * {
    -   Tcl_SetStringObj($result,$1);
    +%typemap(out,noblock=1,fragment="SWIG_FromCharPtr") char *, const char * {
    +  Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)$1));
     }
    +
     
    -

    37.7.8 Pointer handling

    +

    40.7.8 Pointer handling

    @@ -3118,7 +3123,7 @@ For example: -

    37.8 Turning a SWIG module into a Tcl Package.

    +

    40.8 Turning a SWIG module into a Tcl Package.

    @@ -3152,8 +3157,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
     

    @@ -3190,7 +3195,7 @@ As a final note, most SWIG examples do not yet use the to use the load command instead.

    -

    37.9 Building new kinds of Tcl interfaces (in Tcl)

    +

    40.9 Building new kinds of Tcl interfaces (in Tcl)

    @@ -3263,14 +3268,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
    @@ -3289,7 +3294,7 @@ danger of blowing something up (although it is easily accomplished
     with an out of bounds array access).
     

    -

    37.9.1 Proxy classes

    +

    40.9.1 Proxy classes

    @@ -3410,7 +3415,7 @@ short, but clever Tcl script can be combined with SWIG to do many interesting things.

    -

    37.10 Tcl/Tk Stubs

    +

    40.10 Tcl/Tk Stubs

    diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index b3b0bc7a9..c365a879b 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -1,12 +1,13 @@ - + Typemaps + -

    10 Typemaps

    +

    11 Typemaps

    +
  • Special variables and typemap attributes +
  • Special variables combined with special variable macros
  • Common typemap methods
      @@ -85,7 +88,7 @@
    • Usage
  • 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 +98,7 @@ -

    10.1 Introduction

    +

    11.1 Introduction

    @@ -112,7 +115,7 @@ to re-read the earlier chapters if you have found your way to this chapter with only a vague idea of what SWIG already does by default.

    -

    10.1.1 Type conversion

    +

    11.1.1 Type conversion

    @@ -205,7 +208,7 @@ to read the extension documentation for your favorite language to know how it works (an exercise left to the reader).

    -

    10.1.2 Typemaps

    +

    11.1.2 Typemaps

    @@ -306,7 +309,7 @@ parts of the generated wrapper functions. Because arbitrary code can be insert possible to completely change the way in which values are converted.

    -

    10.1.3 Pattern matching

    +

    11.1.3 Pattern matching

    @@ -408,7 +411,7 @@ In this case, a single input object is expanded into a pair of C arguments. Thi provides a hint to the unusual variable naming scheme involving $1, $2, and so forth.

    -

    10.1.4 Reusing typemaps

    +

    11.1.4 Reusing typemaps

    @@ -464,7 +467,7 @@ typedef int size_t; then SWIG already knows that the int typemaps apply. You don't have to do anything.

    -

    10.1.5 What can be done with typemaps?

    +

    11.1.5 What can be done with typemaps?

    @@ -576,7 +579,7 @@ typemaps that expand upon this list. For example, the Java module defines a var aspects of the Java bindings. Consult language specific documentation for further details.

    -

    10.1.6 What can't be done with typemaps?

    +

    11.1.6 What can't be done with typemaps?

    @@ -639,7 +642,7 @@ void wrap_foo(char *s, int x) {

  • -

    10.1.7 Similarities to Aspect Oriented Programming

    +

    11.1.7 Similarities to Aspect Oriented Programming

    @@ -653,11 +656,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.

    -

    10.1.8 The rest of this chapter

    +

    11.1.8 The rest of this chapter

    @@ -677,14 +680,14 @@ of "The C Programming Language" by Kernighan and Ritchie or "The C++ Programming Language" by Stroustrup before going any further.

    -

    10.2 Typemap specifications

    +

    11.2 Typemap specifications

    This section describes the behavior of the %typemap directive itself.

    -

    10.2.1 Defining a typemap

    +

    11.2.1 Defining a typemap

    @@ -773,7 +776,7 @@ Here are some examples of valid typemap specifications: } /* Typemap with modifiers */ -%typemap(in,doc="integer") int "$1 = gh_scm2int($input);"; +%typemap(in,doc="integer") int "$1 = scm_to_int($input);"; /* Typemap applied to patterns of multiple arguments */ %typemap(in) (char *str, int len), @@ -797,7 +800,7 @@ Admittedly, it's not the most readable syntax at first glance. However, the pur individual pieces will become clear.

    -

    10.2.2 Typemap scope

    +

    11.2.2 Typemap scope

    @@ -847,7 +850,7 @@ class Foo { -

    10.2.3 Copying a typemap

    +

    11.2.3 Copying a typemap

    @@ -905,7 +908,7 @@ The patterns for %apply follow the same rules as for %typemap. -

    10.2.4 Deleting a typemap

    +

    11.2.4 Deleting a typemap

    @@ -938,7 +941,7 @@ For example: after the clear operation.

    -

    10.2.5 Placement of typemaps

    +

    11.2.5 Placement of typemaps

    @@ -1018,7 +1021,7 @@ It should be noted that for scoping to work, SWIG has to know that stringclass string.

    -

    10.3 Pattern matching rules

    +

    11.3 Pattern matching rules

    @@ -1026,7 +1029,7 @@ The section describes the pattern matching rules by which C/C++ datatypes are as The matching rules can be observed in practice by using the debugging options also described.

    -

    10.3.1 Basic matching rules

    +

    11.3.1 Basic matching rules

    @@ -1125,7 +1128,7 @@ void F(int x[1000]); // int [ANY] rule (typemap 5) stripped all qualifiers in one step.

    -

    10.3.2 Typedef reductions matching

    +

    11.3.2 Typedef reductions matching

    @@ -1300,7 +1303,7 @@ void go(Struct aStruct); -

    10.3.3 Default typemap matching rules

    +

    11.3.3 Default typemap matching rules

    @@ -1438,7 +1441,7 @@ Finally the best way to view the typemap matching rules in action is via the -

    10.3.4 Multi-arguments typemaps

    +

    11.3.4 Multi-arguments typemaps

    @@ -1468,7 +1471,7 @@ but all subsequent arguments must match exactly.

    -

    10.3.5 Matching rules compared to C++ templates

    +

    11.3.5 Matching rules compared to C++ templates

    @@ -1627,7 +1630,7 @@ are similar to those for specialized template handling.

    -

    10.3.6 Debugging typemap pattern matching

    +

    11.3.6 Debugging typemap pattern matching

    @@ -1840,7 +1843,7 @@ Also the types may be displayed slightly differently - char const * and -

    10.4 Code generation rules

    +

    11.4 Code generation rules

    @@ -1848,7 +1851,7 @@ This section describes rules by which typemap code is inserted into the generated wrapper code.

    -

    10.4.1 Scope

    +

    11.4.1 Scope

    @@ -1926,7 +1929,7 @@ a block scope when it is emitted. This sometimes results in a less complicated Note that only the third of the three typemaps have the typemap code passed through the SWIG preprocessor.

    -

    10.4.2 Declaring new local variables

    +

    11.4.2 Declaring new local variables

    @@ -2050,6 +2053,22 @@ wrap_foo() { +

    There is an exception: if the variable name starts with the _global_ prefix, +the argument number is not appended. Such variables can be used throughout the generated +wrapper function. For example, the above typemap could be rewritten to use _global_temp +instead of temp and the generated code would then contain a single _global_temp variable +instead of temp1, temp2 and temp3: +

    + +
    +
    +%typemap(in) std::string * (std::string _global_temp) {
    + ... as above ...
    +}
    +
    +
    + +

    Some typemaps do not recognize local variables (or they may simply not apply). At this time, only typemaps that apply to argument conversion support this (input typemaps such as the "in" typemap). @@ -2077,7 +2096,7 @@ each type must have its own local variable declaration. -

    10.4.3 Special variables

    +

    11.4.3 Special variables

    @@ -2329,7 +2348,7 @@ Another approach, which only works for arrays is to use the $1_basetype -

    10.4.4 Special variable macros

    +

    11.4.4 Special variable macros

    @@ -2341,7 +2360,7 @@ it is done during the SWIG parsing/compilation stages. The following special variable macros are available across all language modules.

    -

    10.4.4.1 $descriptor(type)

    +

    11.4.4.1 $descriptor(type)

    @@ -2352,7 +2371,7 @@ For example, $descriptor(std::vector<int> *) will expand into Run-time type checker usage section.

    -

    10.4.4.2 $typemap(method, typepattern)

    +

    11.4.4.2 $typemap(method, typepattern)

    @@ -2409,7 +2428,77 @@ The result is the following expansion -

    10.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

    @@ -2417,7 +2506,7 @@ The set of typemaps recognized by a language module may vary. However, the following typemap methods are nearly universal:

    -

    10.5.1 "in" typemap

    +

    11.5.1 "in" typemap

    @@ -2477,7 +2566,7 @@ Usually numinputs is not specified, whereupon the default value is 1, t is the same as the old "ignore" typemap.

    -

    10.5.2 "typecheck" typemap

    +

    11.5.2 "typecheck" typemap

    @@ -2503,7 +2592,7 @@ If you define new "in" typemaps and your program uses overloaded method "typecheck" typemaps. More details about this follow in the Typemaps and overloading section.

    -

    10.5.3 "out" typemap

    +

    11.5.3 "out" typemap

    @@ -2534,7 +2623,7 @@ $symname - Name of function/method being wrapped The "out" typemap supports an optional attribute flag called "optimal". This is for code optimisation and is detailed in the Optimal code generation when returning by value section.

    -

    10.5.4 "arginit" typemap

    +

    11.5.4 "arginit" typemap

    @@ -2553,7 +2642,7 @@ For example: -

    10.5.5 "default" typemap

    +

    11.5.5 "default" typemap

    @@ -2586,7 +2675,7 @@ See the Default/optional arguments sec for further information on default argument wrapping.

    -

    10.5.6 "check" typemap

    +

    11.5.6 "check" typemap

    @@ -2605,7 +2694,7 @@ converted. For example: -

    10.5.7 "argout" typemap

    +

    11.5.7 "argout" typemap

    @@ -2651,7 +2740,7 @@ return values are often appended to return value of the function. See the typemaps.i library file for examples.

    -

    10.5.8 "freearg" typemap

    +

    11.5.8 "freearg" typemap

    @@ -2684,7 +2773,7 @@ be used in other typemaps whenever a wrapper function needs to abort prematurely.

    -

    10.5.9 "newfree" typemap

    +

    11.5.9 "newfree" typemap

    @@ -2713,7 +2802,7 @@ string *foo(); See Object ownership and %newobject for further details.

    -

    10.5.10 "memberin" typemap

    +

    11.5.10 "memberin" typemap

    @@ -2735,7 +2824,7 @@ It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

    -

    10.5.11 "varin" typemap

    +

    11.5.11 "varin" typemap

    @@ -2743,7 +2832,7 @@ The "varin" typemap is used to convert objects in the target language to C for t purposes of assigning to a C/C++ global variable. This is implementation specific.

    -

    10.5.12 "varout" typemap

    +

    11.5.12 "varout" typemap

    @@ -2751,7 +2840,7 @@ The "varout" typemap is used to convert a C/C++ object to an object in the targe language when reading a C/C++ global variable. This is implementation specific.

    -

    10.5.13 "throws" typemap

    +

    11.5.13 "throws" typemap

    @@ -2797,7 +2886,7 @@ Note that if your methods do not have an exception specification yet they do thr For a neat way to handle these, see the Exception handling with %exception section.

    -

    10.6 Some typemap examples

    +

    11.6 Some typemap examples

    @@ -2805,7 +2894,7 @@ This section contains a few examples. Consult language module documentation for more examples.

    -

    10.6.1 Typemaps for arrays

    +

    11.6.1 Typemaps for arrays

    @@ -2962,8 +3051,8 @@ For example, suppose you had a structure like this:

     struct SomeObject {
    -	float  value[4];
    -        ...
    +  float  value[4];
    +  ...
     };
     
    @@ -3064,7 +3153,7 @@ Now, you will find that member access is quite nice: useless and has since been eliminated. To return structure members, simply use the "out" typemap.

    -

    10.6.2 Implementing constraints with typemaps

    +

    11.6.2 Implementing constraints with typemaps

    @@ -3077,9 +3166,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"); + } } ... @@ -3112,7 +3201,7 @@ a NULL pointer. As a result, SWIG can often prevent a potential segmentation faults or other run-time problems by raising an exception rather than blindly passing values to the underlying C/C++ program.

    -

    10.7 Typemaps for multiple target languages

    +

    11.7 Typemaps for multiple target languages

    @@ -3142,7 +3231,7 @@ The example above also shows a common approach of issuing a warning for an as ye %typemap(ruby,in) int "$1 = NUM2INT($input);".

    -

    10.8 Optimal code generation when returning by value

    +

    11.8 Optimal code generation when returning by value

    @@ -3331,7 +3420,7 @@ example.i:7: Warning 475: optimal attribute usage in the out typemap. However, it doesn't always get it right, for example when $1 is within some commented out code.

    -

    10.9 Multi-argument typemaps

    +

    11.9 Multi-argument typemaps

    @@ -3355,12 +3444,12 @@ list of strings like this:

    ->>> foo(["ale","lager","stout"])
    +>>> foo(["ale", "lager", "stout"])
     

    -To do this, you not only need to map a list of strings to char *argv[], but the +To do this, you not only need to map a list of strings to char *argv[], but the value of int argc is implicitly determined by the length of the list. Using only simple typemaps, this type of conversion is possible, but extremely painful. Multi-argument typemaps help in this situation. @@ -3398,6 +3487,11 @@ maps perform the conversion described for the above example: %typemap(freearg) (int argc, char *argv[]) { if ($2) free($2); } + +/* Required for C++ method overloading */ +%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char *argv[]) { + $1 = PyList_Check($input) ? 1 : 0; +} @@ -3465,6 +3559,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 @@ -3598,7 +3697,7 @@ with non-consecutive C/C++ arguments; a workaround such as a helper function re- the arguments to make them consecutive will need to be written.

    -

    10.10 Typemap warnings

    +

    11.10 Typemap warnings

    @@ -3607,7 +3706,7 @@ See the information in the issuing warnings

    -

    10.11 Typemap fragments

    +

    11.11 Typemap fragments

    @@ -3860,7 +3959,7 @@ fragment usage unless a desire to really get to grips with some powerful but tricky macro and fragment usage that is used in parts of the SWIG typemap library.

    -

    10.11.1 Fragment type specialization

    +

    11.11.1 Fragment type specialization

    @@ -3893,7 +3992,7 @@ struct A { -

    10.11.2 Fragments and automatic typemap specialization

    +

    11.11.2 Fragments and automatic typemap specialization

    @@ -3939,7 +4038,7 @@ The interested (or very brave) reader can take a look at the fragments.swg file

    -

    10.12 The run-time type checker

    +

    11.12 The run-time type checker

    @@ -3956,7 +4055,7 @@ Requirements for the type system:

  • Store inheritance and type equivalence information and be able to correctly re-create the type pointer.
  • Share type information between modules.
  • -
  • Modules can be loaded in any order, irregardless of actual type +
  • Modules can be loaded in any order, regardless of actual type dependency.
  • Avoid the use of dynamically allocated memory, and library/system calls in general.
  • Provide a reasonably fast implementation, minimizing the lookup time for all @@ -3965,7 +4064,7 @@ language modules.
  • Modules can be unloaded from the type system.
  • -

    10.12.1 Implementation

    +

    11.12.1 Implementation

    @@ -4151,7 +4250,7 @@ structures rather than creating new ones. These swig_module_info structures are chained together in a circularly linked list.

    -

    10.12.2 Usage

    +

    11.12.2 Usage

    This section covers how to use these functions from typemaps. To learn how to @@ -4245,7 +4344,7 @@ probably just look at the output of SWIG to get a better sense for how types are managed.

    -

    10.13 Typemaps and overloading

    +

    11.13 Typemaps and overloading

    @@ -4413,7 +4512,7 @@ before arrays, and so forth.

    Using the above table as a guide, each target language defines a collection of "typecheck" typemaps. -The follow excerpt from the Python module illustrates this: +The following excerpt from the Python module illustrates this:

    @@ -4422,22 +4521,22 @@ The follow 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; } @@ -4526,11 +4625,31 @@ Here is an example,

    The bottom line: If you are writing new typemaps and you are using overloaded methods, you will probably -have to write typecheck code or copy existing code. Since this is a relatively new SWIG feature, there are -few examples to work with. However, you might look at some of the existing library files likes 'typemaps.i' for -a guide. +have to write new typecheck code or copy and modify existing typecheck code.

    +

    +If you write a typecheck typemap and omit the precedence level, for example commenting it out as shown below: +

    + +
    +
    +%typemap(typecheck /*,precedence=SWIG_TYPECHECK_INTEGER*/) int {
    +   $1 = PyInt_Check($input) ? 1 : 0;
    +}
    +
    +
    + +

    +then the type is given a precedence higher than any other known precedence level and a warning is issued: +

    + +
    +
    +example.i:18: Warning 467: Overloaded method foo(int) not supported (incomplete type checking rule - no precedence level in typecheck typemap for 'int').
    +
    +
    +

    Notes:

    @@ -4556,7 +4675,7 @@ Subsequent "in" typemaps would then perform more extensive type-checking. -

    10.14 More about %apply and %clear

    +

    11.14 More about %apply and %clear

    @@ -4642,7 +4761,7 @@ example:

    -

    10.15 Passing data between typemaps

    +

    11.15 Passing data between typemaps

    @@ -4679,7 +4798,7 @@ sure that the typemaps sharing information have exactly the same types and names

    -

    10.16 C++ "this" pointer

    +

    11.16 C++ "this" pointer

    @@ -4739,7 +4858,7 @@ will also match the typemap. One work around is to create an interface file tha the method, but gives the argument a name other than self.

    -

    10.17 Where to go for more information?

    +

    11.17 Where to go for more information?

    diff --git a/Doc/Manual/Varargs.html b/Doc/Manual/Varargs.html index c27db603d..1c99804f1 100644 --- a/Doc/Manual/Varargs.html +++ b/Doc/Manual/Varargs.html @@ -1,12 +1,13 @@ - + Variable Length Arguments + -

    13 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.

      -

      13.1 Introduction

      +

      14.1 Introduction

      @@ -139,7 +140,7 @@ List make_list(const char *s, ...) {

    -

    13.2 The Problem

    +

    14.2 The Problem

    @@ -232,7 +233,7 @@ can also support real varargs wrapping (with stack-frame manipulation) if you are willing to get hands dirty. Keep reading.

    -

    13.3 Default varargs support

    +

    14.3 Default varargs support

    @@ -301,7 +302,7 @@ Read on for further solutions.

    -

    13.4 Argument replacement using %varargs

    +

    14.4 Argument replacement using %varargs

    @@ -398,7 +399,7 @@ int execlp(const char *path, const char *arg, ...);

    -Note that str3 is the name of the last argument, as we have used %vargars with 3. +Note that str3 is the name of the last argument, as we have used %varargs with 3. Now execlp("a", "b", "c", "d", "e") will result in an error as one too many arguments has been passed, as now only 2 additional 'str' arguments can be passed with the 3rd one always using the specified default NULL.

    @@ -412,7 +413,7 @@ mixed argument types such as printf(). Providing general purpose wrappers to such functions presents special problems (covered shortly).

    -

    13.5 Varargs and typemaps

    +

    14.5 Varargs and typemaps

    @@ -509,10 +510,10 @@ like this:

    -%typemap(in) (...)(char *args[10]) {
    +%typemap(in) (...)(char *vargs[10]) {
       int i;
       int argc;
    -  for (i = 0; i < 10; i++) args[i] = 0;
    +  for (i = 0; i < 10; i++) vargs[i] = 0;
       argc = PyTuple_Size(varargs);
       if (argc > 10) {
         PyErr_SetString(PyExc_ValueError, "Too many arguments");
    @@ -528,7 +529,7 @@ like this:
            return NULL;
         }
         pystr = PyUnicode_AsUTF8String(pyobj);
    -    str = PyBytes_AsString(pystr);
    +    str = strdup(PyBytes_AsString(pystr));
         Py_XDECREF(pystr);
     %#else  
         if (!PyString_Check(pyobj)) {
    @@ -537,22 +538,34 @@ like this:
         }
         str = PyString_AsString(pyobj);
     %#endif
    -    args[i] = str;
    +    vargs[i] = str;
       }
    -  $1 = (void *) args;
    +  $1 = (void *)vargs;
    +}
    +
    +%typemap(freearg) (...) {
    +%#if PY_VERSION_HEX>=0x03000000
    +  int i;
    +  for (i = 0; i < 10; i++) {
    +    free(vargs$argnum[i]);
    +  }
    +%#endif
     }
     

    -In this typemap, the special variable varargs is a tuple +In the 'in' typemap, the special variable varargs is a tuple holding all of the extra arguments passed (this is specific to the Python module). The typemap then pulls this apart and sticks the values into the array of strings args. Then, the array is assigned to $1 (recall that this is the void * variable corresponding to (...)). However, this assignment is only half of the picture----clearly this alone is not enough to -make the function work. To patch everything up, you have to rewrite the +make the function work. The 'freearg' typemap cleans up memory +allocated in the 'in' typemap; this code is generated to be called +after the execlp function is called. To patch everything +up, you have to rewrite the underlying action code using the %feature directive like this:

    @@ -560,9 +573,9 @@ this:
     %feature("action") execlp {
    -   char *args = (char **) arg3;
    -   result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4],
    -                   args[5],args[6],args[7],args[8],args[9], NULL);
    +  char **vargs = (char **) arg3;
    +  result = execlp(arg1, arg2, vargs[0], vargs[1], vargs[2], vargs[3], vargs[4],
    +                  vargs[5], vargs[6], vargs[7], vargs[8], vargs[9], NULL);
     }
     
     int execlp(const char *path, const char *arg, ...);
    @@ -577,7 +590,7 @@ really want to elevate your guru status and increase your job
     security, continue to the next section.
     

    -

    13.6 Varargs wrapping with libffi

    +

    14.6 Varargs wrapping with libffi

    @@ -593,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 @@ -623,7 +636,7 @@ example. For example: PyObject *o = PyTuple_GetItem(varargs,i); if (!PyString_Check(o)) { PyErr_SetString(PyExc_ValueError,"Expected a string"); - free(argv); + free(argv); return NULL; } argv[i] = PyString_AsString(o); @@ -829,7 +842,7 @@ provide an argument number for the first extra argument. This can be used to in values. Please consult the chapter on each language module for more details.

    -

    13.7 Wrapping of va_list

    +

    14.7 Wrapping of va_list

    @@ -839,13 +852,13 @@ of type va_list. For example:

    -int vfprintf(FILE *f, const char *fmt, va_list ap);
    +int vprintf(const char *fmt, va_list ap);
     

    -As far as we know, there is no obvious way to wrap these functions -with SWIG. This is because there is no documented way to assemble the +As far as we know, there is no obvious way to wrap these functions with +SWIG. This is because there is no documented way to assemble the proper va_list structure (there are no C library functions to do it and the contents of va_list are opaque). Not only that, the contents of a va_list structure are closely tied to the underlying @@ -853,7 +866,37 @@ call-stack. It's not clear that exporting a va_list would have any use or that it would work at all.

    -

    13.8 C++ Issues

    +

    +A workaround can be implemented by writing a simple varargs C wrapper and then using the techniques +discussed earlier in this chapter for varargs. Below is a simple wrapper for vprintf renamed so that +it can still be called as vprintf from your target language. The %varargs +used in the example restricts the function to taking one string argument. +

    + +
    +
    +%{
    +int vprintf(const char *fmt, va_list ap);
    +%}
    +
    +%varargs(const char *) my_vprintf;
    +%rename(vprintf) my_vprintf;
    +
    +%inline %{
    +int my_vprintf(const char *fmt, ...) {
    +  va_list ap;
    +  int result;
    +
    +  va_start(ap, fmt);
    +  result = vprintf(fmt, ap);
    +  va_end(ap);
    +  return result;
    +}
    +%}
    +
    +
    + +

    14.8 C++ Issues

    @@ -922,7 +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.

    -

    13.9 Discussion

    +

    14.9 Discussion

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index 2a3ce560d..89a8375a5 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -1,12 +1,13 @@ - + Warning Messages + -

    14 Warning Messages

    +

    15 Warning Messages

      @@ -35,7 +36,7 @@ -

      14.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.

      -

      14.2 Warning message suppression

      +

      15.2 Warning message suppression

      @@ -147,7 +148,7 @@ your interface. Ignore the warning messages at your own peril.

      -

      14.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.

      -

      14.4 Issuing a warning message

      +

      15.4 Issuing a warning message

      @@ -274,7 +275,7 @@ example.i:24: Warning 901: You are really going to regret this usage of blah * s

    -

    14.5 Symbolic symbols

    +

    15.5 Symbolic symbols

    @@ -309,7 +310,7 @@ or -

    14.6 Commentary

    +

    15.6 Commentary

    @@ -326,7 +327,7 @@ no obvious recovery. There is no mechanism for suppressing error messages.

    -

    14.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.

    -

    14.8 Message output format

    +

    15.8 Message output format

    @@ -349,15 +350,15 @@ These can be overridden using command line options, for example:

     $ swig -python -Fstandard example.i
    -example.i:4: Syntax error in input.
    +example.i:4: Syntax error in input(1).
     $ swig -python -Fmicrosoft example.i
    -example.i(4) : Syntax error in input.
    +example.i(4) : Syntax error in input(1).
     
    -

    14.9 Warning number reference

    +

    15.9 Warning number reference

    -

    14.9.1 Deprecated features (100-199)

    +

    15.9.1 Deprecated features (100-199)

      @@ -382,9 +383,10 @@ example.i(4) : Syntax error in input.
    • 119. Deprecated %typemap(ignore).
    • 120. Deprecated command line option (-runtime, -noruntime).
    • 121. Deprecated %name directive. +
    • 126. The 'nestedworkaround' feature is deprecated.
    -

    14.9.2 Preprocessor (200-299)

    +

    15.9.2 Preprocessor (200-299)

      @@ -396,7 +398,7 @@ example.i(4) : Syntax error in input.
    • 206. Unexpected tokens after #directive directive.
    -

    14.9.3 C/C++ Parser (300-399)

    +

    15.9.3 C/C++ Parser (300-399)

      @@ -423,7 +425,8 @@ example.i(4) : Syntax error in input.
    • 322. Redundant redeclaration of 'name'.
    • 323. Recursive scope inheritance of 'name'.
    • 324. Named nested template instantiations not supported. Processing as if no name was given to %template(). -
    • 325. Nested class not currently supported (name ignored). +
    • 325. Nested kind not currently supported (name ignored). +
    • 326. Deprecated %extend name used - the kind name 'name' should be used instead of the typedef name 'name'.
    • 350. operator new ignored.
    • 351. operator delete ignored.
    • 352. operator+ ignored. @@ -472,7 +475,7 @@ example.i(4) : Syntax error in input.
    • 395. operator delete[] ignored.
    -

    14.9.4 Types and typemaps (400-499)

    +

    15.9.4 Types and typemaps (400-499)

      @@ -490,18 +493,20 @@ example.i(4) : Syntax error in input.
    • 464. Unsupported constant value.
    • 465. Unable to handle type type.
    • 466. Unsupported variable type type. -
    • 467. Overloaded declaration not supported (no type checking rule for 'type') +
    • 467. Overloaded declaration not supported (incomplete type checking rule - no precedence level in typecheck typemap for 'type')
    • 468. No 'throw' typemap defined for exception type type
    • 469. No or improper directorin typemap defined for type
    • 470. Thread/reentrant unsafe wrapping, consider returning by value instead.
    • 471. Unable to use return type type in director method
    • 474. Method method usage of the optimal attribute ignored in the out typemap as the following cannot be used to generate optimal code: code
    • 475. Multiple calls to method might be generated due to optimal attribute usage in the out typemap. +
    • 476. Initialization using std::initializer_list. +
    • 477. No directorthrows typemap defined for type
    -

    14.9.5 Code generation (500-599)

    +

    15.9.5 Code generation (500-599)

      @@ -526,9 +531,11 @@ example.i(4) : Syntax error in input.
    • 519. %template() contains no name. Template method ignored: declaration
    • 520. Base/Derived class 'classname1' of 'classname2' is not similarly marked as a smart pointer.
    • 521. Illegal destructor name name. Ignored. +
    • 522. Use of an illegal constructor name 'name' in %extend is deprecated, the constructor name should be 'name'. +
    • 523. Use of an illegal destructor name 'name' in %extend is deprecated, the destructor name should be 'name'.
    -

    14.9.6 Language module specific (700-899)

    +

    15.9.6 Language module specific (700-899)

      @@ -539,7 +546,7 @@ example.i(4) : Syntax error in input.
    • 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). @@ -551,13 +558,15 @@ example.i(4) : Syntax error in input.
    • 822. Covariant return types not supported in Java. Proxy method will return basetype (Java).
    • 823. No javaconstruct typemap defined for type (Java).
    • 824. Missing JNI descriptor in directorin typemap defined for type (Java). +
    • 825. "directorconnect" attribute missing in type "javaconstruct" typemap. (Java). +
    • 826. The nspace feature is used on 'type' without -package. The generated code may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package. (Java).
    • 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#). @@ -573,18 +582,18 @@ example.i(4) : Syntax error in input.
      -
    • 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).
    -

    14.9.7 User defined (900-999)

    +

    15.9.7 User defined (900-999)

    These numbers can be used by your own application.

    -

    14.10 History

    +

    15.10 History

    diff --git a/Doc/Manual/Windows.html b/Doc/Manual/Windows.html index 6349f355a..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,22 +73,22 @@ If you want to build your own swig.exe have a look at 3.2 SWIG Windows Examples +

    3.2 SWIG Windows Examples

    Using Microsoft Visual C++ is the most common approach to compiling and linking SWIG's output. The Examples directory has a few Visual C++ project files (.dsp files). These were produced by Visual C++ 6. -Later versions of Visual Studio should also be able to open and convert these project files. -The C# examples come with .NET 2003 solution (.sln) and project files instead of Visual C++ 6 project files. +Newer versions of Visual Studio should be able to open and convert these project files. +Each C# example comes with a Visual Studio 2005 solution and associated project files instead of Visual C++ 6 project files. The project files have been set up to execute SWIG in a custom build rule for the SWIG interface (.i) file. 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,11 +144,11 @@ PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib

    -

    3.2.1.4 Python

    +

    3.2.1.4 Python

    -PYTHON_INCLUDE : Set this to the directory that contains python.h
    +PYTHON_INCLUDE : Set this to the directory that contains Python.h
    PYTHON_LIB : Set this to the python library including path for linking

    Example using Python 2.1.1:
    @@ -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

    @@ -236,8 +237,8 @@ The short abbreviated instructions follow...

    -The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from SVN follow... -Note that the instructions for obtaining SWIG from SVN are also online at SWIG SVN. +The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from Github follow... +Note that the instructions for obtaining SWIG from Github are also online at SWIG Bleeding Edge.

    @@ -293,22 +294,26 @@ Execute the steps in the order shown and don't use spaces in path names. In fact Start the MSYS command prompt and execute:

     cd /
    -tar -jxf msys-automake-1.8.2.tar.bz2 
    +tar -jxf msys-automake-1.8.2.tar.bz2
     tar -jxf msys-autoconf-2.59.tar.bz2
    -tar -zxf bison-2.0-MSYS.tar.gz   
    +tar -zxf bison-2.0-MSYS.tar.gz
     
  • - To get the latest SWIG SVN (version from Subversion source control), type in the following: + The very latest development version of SWIG is available from SWIG on Github + and can be downloaded as a zip file or if you have Git installed, via Git. + Either download the latest Zip file snapshot and unzip and rename the top level folder to /usr/src/swig. + + Otherwise if using Git, type in the following:
     mkdir /usr/src
     cd /usr/src
    -svn co https://swig.svn.sourceforge.net/svnroot/swig/trunk swig
    +git clone https://github.com/swig/swig.git
     
    Pitfall note: -If you want to check out SWIG to a different folder to the proposed +If you want to place SWIG in a different folder to the proposed /usr/src/swig, do not use MSYS emulated windows drive letters, because the autotools will fail miserably on those.
  • @@ -337,7 +342,7 @@ make -

    3.3.1.2 Building swig.exe using Cygwin

    +

    3.3.1.2 Building swig.exe using Cygwin

    @@ -348,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

    @@ -358,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

    @@ -367,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

    @@ -384,6 +389,53 @@ Include it like you would any other interface file, for example: __declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);

    +

    Note that if you follow Microsoft's recommendation of wrapping the +__declspec calls in a preprocessor definition, you will need to +make sure that the definition is included by SWIG as well, by either defining it +manually or via a header. For example, if you have specified the +preprocessor definition in a header named export_lib.h and include +other headers which depend on it, you should use the %include directive +to include the definition explicitly. For example, if you had a header file, +bar.h, which depended on export_lib.h, your SWIG definition +file might look like:

    + +
    +// bar.i
    +%module bar
    +%include <windows.i>
    +%include "export_lib.h"
    +%include "bar.h"
    +
    + +

    +where export_lib.h may contain: +

    + +
    +// export_lib.h
    +#define BAR_API __declspec(dllexport)
    +
    + +

    +and bar.h may look like: +

    + +
    +// bar.h
    +#include "export_lib.h"
    +BAR_API void bar_function(int, double);
    +
    + +

    +Using the preprocessor to remove BAR_API is a popular simpler solution: +

    + +
    +// bar.i
    +%module bar
    +#define BAR_API
    +%include "bar.h"
    +
    diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters index 9564a3096..f7b7d00c0 100644 --- a/Doc/Manual/chapters +++ b/Doc/Manual/chapters @@ -4,6 +4,7 @@ Windows.html Scripting.html SWIG.html SWIGPlus.html +CPlusPlus11.html Preprocessor.html Library.html Arguments.html @@ -23,6 +24,7 @@ D.html Go.html Guile.html Java.html +Javascript.html Lisp.html Lua.html Modula3.html @@ -35,5 +37,6 @@ Pike.html Python.html R.html Ruby.html +Scilab.html Tcl.html Extending.html 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 30c69578f..26cc81ea1 100644 --- a/Doc/Manual/index.html +++ b/Doc/Manual/index.html @@ -1,10 +1,11 @@ - + -SWIG-2.0 Documentation +SWIG-3.0 Documentation + -

    SWIG-2.0 Documentation

    +

    SWIG-3.0 Documentation

    The SWIG documentation is available in one of the following formats.
      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 70f087b92..000000000 --- a/Doc/Manual/margin-left.patch +++ /dev/null @@ -1,269 +0,0 @@ -# -# Patch managed by http://www.holgerschurig.de/patcher.html -# -# This patch is against htmldoc 1.8.24, 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 -# stabalizes, 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. -# ---- htmldoc-1.8.24/htmldoc/ps-pdf.cxx~margin-left -+++ htmldoc-1.8.24/htmldoc/ps-pdf.cxx -@@ -158,6 +158,7 @@ - # undef page_t - #endif // __hpux - -+extern int lookup_div_class(uchar *); - - /* - * Constants... -@@ -4188,9 +4189,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); ---- htmldoc-1.8.24/htmldoc/htmldoc.cxx~margin-left -+++ htmldoc-1.8.24/htmldoc/htmldoc.cxx -@@ -62,6 +62,8 @@ - const char *__XOS2RedirRoot(const char *); - } - #endif -+ -+extern void parse_style(char *); - - - /* -@@ -2140,6 +2142,10 @@ - } - else if (strcmp(temp, "--cookies") == 0) - file_cookies(temp2); -+ else if (strcmp(temp, "--stylesheet") == 0) -+ { -+ parse_style(temp2); -+ } - } - } - ---- /dev/null -+++ htmldoc-1.8.24/htmldoc/style.cxx -@@ -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); -+} ---- htmldoc-1.8.24/htmldoc/Makefile~margin-left -+++ htmldoc-1.8.24/htmldoc/Makefile -@@ -35,7 +35,7 @@ - - OBJS = gui.o file.o html.o htmldoc.o htmllib.o htmlsep.o http.o \ - http-addr.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 -+ progress.o ps-pdf.o rc4.o snprintf.o string.o toc.o util.o style.o - - - # - 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 f9f866d27..d169686a4 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -14,17 +14,41 @@ # # 2. To use this makefile, set required variables, eg SRCS, INTERFACE, # INTERFACEDIR, INCLUDES, LIBS, TARGET, and do a -# $(MAKE) -f Makefile.template.in SRCS='$(SRCS)' \ +# $(MAKE) -f Makefile.template.in SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ # INCLUDES='$(INCLUDES) LIBS='$(LIBS)' INTERFACE='$(INTERFACE)' \ # INTERFACEDIR='$(INTERFACEDIR)' TARGET='$(TARGET)' method # # 'method' describes what is being built. #--------------------------------------------------------------- +# Regenerate Makefile if Makefile.in or config.status have changed. +Makefile: @srcdir@/Makefile.in ../config.status + cd .. && $(SHELL) ./config.status Examples/Makefile + +# SRCDIR is the relative path to the current source directory +# - For in-source-tree builds, SRCDIR with be either '' or './', but +# '../' for the test suites that build in a subdir (e.g. C#, Java) +# - For out-of-source-tree builds, SRCDIR will be a relative +# path ending with a '/' + +# SRCDIR_SRCS, etc. are $(SRCS), etc. with $(SRCDIR) prepended +SRCDIR_SRCS = $(addprefix $(SRCDIR),$(SRCS)) +SRCDIR_CSRCS = $(addprefix $(SRCDIR),$(CSRCS)) +SRCDIR_CXXSRCS = $(addprefix $(SRCDIR),$(CXXSRCS)) + +ifeq (,$(SRCDIR)) +SRCDIR_INCLUDE = -I. +else +SRCDIR_INCLUDE = -I. -I$(SRCDIR) +endif + TARGET = CC = @CC@ CXX = @CXX@ -CFLAGS = @PLATFLAGS@ +CPPFLAGS = $(SRCDIR_INCLUDE) +CFLAGS = @PLATCFLAGS@ +CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +LDFLAGS = prefix = @prefix@ exec_prefix= @exec_prefix@ SRCS = @@ -32,9 +56,15 @@ INCLUDES = LIBS = INTERFACE = INTERFACEDIR = -INTERFACEPATH = $(INTERFACEDIR)$(INTERFACE) +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@ @@ -46,11 +76,10 @@ LIBPREFIX = RUNTOOL = # COMPILETOOL is a way to run the compiler under another tool, or more commonly just to stop the compiler executing COMPILETOOL= +# RUNPIPE is for piping output of running interpreter/compiled code somewhere, eg RUNPIPE=\>/dev/null +RUNPIPE= -# X11 options - -XLIB = @XLIBSW@ -XINCLUDE = @XINCLUDES@ +RUNME = runme IWRAP = $(INTERFACE:.i=_wrap.i) IPROXYSRCS = $(INTERFACE:.i=_proxy.c) @@ -58,6 +87,27 @@ ISRCS = $(IWRAP:.i=.c) ICXXSRCS = $(IWRAP:.i=.cxx) IOBJS = $(IWRAP:.i=.o) $(IPROXYSRCS:.c=.o) +################################################################## +# Some options for silent output +################################################################## + +ifneq (,$(findstring s, $(filter-out --%, $(MAKEFLAGS)))) + # make -s detected + SILENT=1 +else + SILENT= +endif + +ifneq (,$(SILENT)) + SILENT_OPTION = -s + SILENT_PIPE = >/dev/null + ANT_QUIET = -q -logfile /dev/null +else + SILENT_OPTION = + SILENT_PIPE = + ANT_QUIET = +endif + ################################################################## # Dynamic loading for C++ # If you are going to be building dynamic loadable modules in C++, @@ -68,7 +118,7 @@ IOBJS = $(IWRAP:.i=.o) $(IPROXYSRCS:.c=.o) ################################################################## CPP_DLLIBS = #-L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \ - -L/usr/local/lib -lg++ -lstdc++ -lgcc + -L/usr/local/lib -lg++ -lstdc++ -lgcc # Solaris workshop 5.0 # CPP_DLLIBS = -L/opt/SUNWspro/lib -lCrun @@ -87,15 +137,23 @@ OBJS = $(SRCS:.c=.@OBJEXT@) $(CXXSRCS:.cxx=.@OBJEXT@) distclean: rm -f Makefile - rm -f guile/Makefile + rm -f d/example.mk rm -f xml/Makefile +################################################################## +# Very generic invocation of swig +################################################################## + +swiginvoke: + $(SWIG) $(SWIGOPT) + ################################################################## ##### Tcl/Tk ###### ################################################################## # Set these to your local copy of Tcl/Tk. +TCLSH = tclsh TCL_INCLUDE = @TCLINCLUDE@ TCL_LIB = @TCLLIB@ TCL_OPTS = @LIBS@ @@ -106,54 +164,53 @@ TCL_DLNK = @TCLDYNAMICLINKING@ TCL_SO = @TCL_SO@ TCLLDSHARED = @TCLLDSHARED@ TCLCXXSHARED = @TCLCXXSHARED@ +TCL_SCRIPT = $(SRCDIR)$(RUNME).tcl # ----------------------------------------------------------- # Build a new version of the tclsh shell # ----------------------------------------------------------- - -tclsh: $(SRCS) - $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACEPATH) - $(CC) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ +tclsh: $(SRCDIR_SRCS) + $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) -tclsh_cpp: $(SRCS) - $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ +tclsh_cpp: $(SRCDIR_SRCS) + $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) -# ----------------------------------------------------------- -# Build a new copy of wish -# ----------------------------------------------------------- - -wish: $(SRCS) - $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACEPATH) - $(CC) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ - $(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET) - - -wish_cpp: $(SRCS) - $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ - $(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET) - # ----------------------------------------------------------- # Build a Tcl dynamic loadable module (you might need to tweak this) # ----------------------------------------------------------- -tcl: $(SRCS) - $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLLDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) +tcl: $(SRCDIR_SRCS) + $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) + $(TCLLDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) # ----------------------------------------------------------- # Build a Tcl7.5 dynamic loadable module for C++ # ----------------------------------------------------------- -tcl_cpp: $(SRCS) - $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLCXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) +tcl_cpp: $(SRCDIR_SRCS) + $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) + $(TCLCXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) + +# ----------------------------------------------------------------- +# Run Tcl example +# ----------------------------------------------------------------- + +tcl_run: + $(RUNTOOL) $(TCLSH) $(TCL_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +tcl_version: + echo 'puts $$tcl_version;exit 0' | $(TCLSH) # ----------------------------------------------------------------- # Cleaning the Tcl examples @@ -162,7 +219,7 @@ tcl_cpp: $(SRCS) tcl_clean: rm -f *_wrap* *~ .~* mytclsh@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(TCL_SO) ################################################################## ##### PERL 5 ###### @@ -177,45 +234,63 @@ PERL5_INCLUDE= @PERL5EXT@ # Extra Perl specific dynamic linking options PERL5_DLNK = @PERL5DYNAMICLINKING@ PERL5_CCFLAGS = @PERL5CCFLAGS@ +PERL5_CCDLFLAGS = @PERL5CCDLFLAGS@ +PERL5_CCCDLFLAGS = @PERL5CCCDLFLAGS@ +PERL5_LDFLAGS = @PERL5LDFLAGS@ +PERL = @PERL@ +PERL5_LIB = -L$(PERL5_INCLUDE) -l@PERL5LIB@ @LIBS@ $(SYSLIBS) +PERL5_SCRIPT = $(SRCDIR)$(RUNME).pl # ---------------------------------------------------------------- # Build a Perl5 dynamically loadable module (C) # ---------------------------------------------------------------- -perl5: $(SRCS) - $(SWIG) -perl5 $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c -Dbool=char $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) -I$(PERL5_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PERL5_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +perl5: $(SRCDIR_SRCS) + $(SWIG) -perl5 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c -Dbool=char $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a Perl5 dynamically loadable module (C++) # ---------------------------------------------------------------- -perl5_cpp: $(SRCS) - $(SWIG) -perl5 -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) -I$(PERL5_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +perl5_cpp: $(SRCDIR_SRCS) + $(SWIG) -perl5 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a module from existing XS C source code. (ie. from xsubpp). # ---------------------------------------------------------------- -perl5_xs: $(SRCS) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(INCLUDES) -I$(PERL5_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(LIBS) -o $(TARGET)$(SO) +perl5_xs: $(SRCDIR_SRCS) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) -I$(PERL5_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $(TARGET)$(SO) # ---------------------------------------------------------------- # Build a statically linked Perl5 executable # ---------------------------------------------------------------- -PERL5_LIB = -L$(PERL5_INCLUDE) -l@PERL5LIB@ @LIBS@ $(SYSLIBS) +perl5_static: $(SRCDIR_SRCS) + $(SWIG) -perl5 -static -lperlmain.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -Dbool=char $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) -perl5_static: $(SRCS) - $(SWIG) -perl5 -static -lperlmain.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) -Dbool=char $(SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) +perl5_static_cpp: $(SRCDIR_SRCS) + $(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) -perl5_static_cpp: $(SRCS) - $(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) +# ----------------------------------------------------------------- +# Running a Perl5 example +# ----------------------------------------------------------------- + +perl5_run: + $(RUNTOOL) $(PERL) $(PERL5_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +perl5_version: + $(PERL) -v | grep "This is" # ----------------------------------------------------------------- # Cleaning the Perl5 examples @@ -230,15 +305,17 @@ perl5_clean: ##### PYTHON ###### ################################################################## +PYTHON_FLAGS = + # Make sure these locate your Python installation ifeq (,$(PY3)) PYTHON_INCLUDE= $(DEFS) @PYINCLUDE@ PYTHON_LIB = @PYLIB@ - PYTHON = @PYTHON@ + PYTHON = @PYTHON@ $(PYTHON_FLAGS) else PYTHON_INCLUDE= $(DEFS) @PY3INCLUDE@ PYTHON_LIB = @PY3LIB@ - PYTHON = @PYTHON3@ + PYTHON = @PYTHON3@ $(PYTHON_FLAGS) endif # Extra Python specific linking options @@ -258,23 +335,26 @@ else SWIGPYTHON = $(SWIG) -python -py3 endif +PEP8 = @PEP8@ +PEP8_FLAGS = --ignore=E402,E501,E30,W291,W391 + # ---------------------------------------------------------------- # Build a C dynamically loadable module # ---------------------------------------------------------------- -python: $(SRCS) - $(SWIGPYTHON) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(PYTHON_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) +python: $(SRCDIR_SRCS) + $(SWIGPYTHON) $(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) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -python_cpp: $(SRCS) - $(SWIGPYTHON) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) +python_cpp: $(SRCDIR_SRCS) + $(SWIGPYTHON) -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) # ----------------------------------------------------------------- # Build statically linked Python interpreter @@ -287,14 +367,14 @@ python_cpp: $(SRCS) TKINTER = PYTHON_LIBOPTS = $(PYTHON_LINK) @LIBS@ $(TKINTER) $(SYSLIBS) -python_static: $(SRCS) - $(SWIGPYTHON) -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \ +python_static: $(SRCDIR_SRCS) + $(SWIGPYTHON) -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: $(SRCS) - $(SWIGPYTHON) -c++ -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +python_static_cpp: $(SRCDIR_SRCS) + $(SWIGPYTHON) -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) # ----------------------------------------------------------------- @@ -302,29 +382,47 @@ python_static_cpp: $(SRCS) # ----------------------------------------------------------------- ifeq (,$(PY3)) - PYSCRIPT = runme.py + PYSCRIPT = $(RUNME).py else - PYSCRIPT = runme3.py + PYSCRIPT = $(RUNME)3.py endif PY2TO3 = 2to3 `2to3 -l | grep -v -E "Available|import$$" | awk '{print "-f "$$0}'` python_run: $(PYSCRIPT) - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=$(srcdir):$$PYTHONPATH $(PYTHON) $(PYSCRIPT) >/dev/null +ifneq (,$(PEP8)) + $(COMPILETOOL) $(PEP8) $(PEP8_FLAGS) $(PYSCRIPT) +endif + env PYTHONPATH=$$PWD $(RUNTOOL) $(PYTHON) $(PYSCRIPT) $(RUNPIPE) -runme3.py: runme.py +ifneq (,$(SRCDIR)) +$(RUNME).py: $(SRCDIR)$(RUNME).py + cp $< $@ +endif + +$(RUNME)3.py: $(SRCDIR)$(RUNME).py cp $< $@ $(PY2TO3) -w $@ >/dev/null 2>&1 +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +python_version: + $(PYTHON) -V + # ----------------------------------------------------------------- # Cleaning the python examples # ----------------------------------------------------------------- python_clean: + rm -rf __pycache__ rm -f *_wrap* *~ .~* mypython@EXEEXT@ *.pyc rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ *@PYTHON_SO@ - if [ -f runme.py ]; then rm -f runme3.py runme3.py.bak; fi + rm -f *.@OBJEXT@ *@SO@ *$(PYTHON_SO) + rm -f $(TARGET).py + if test -f $(SRCDIR)$(RUNME).py; then rm -f $(RUNME)3.py $(RUNME)3.py.bak; fi + case "x$(SRCDIR)" in x|x./);; *) rm -f $(RUNME).py;; esac ################################################################## @@ -332,134 +430,138 @@ python_clean: ################################################################## # Make sure these locate your Octave installation -OCTAVE_INCLUDE= $(DEFS) @OCTAVEEXT@ -OCTAVE_LIB = -OCTAVE = @OCTAVE@ -qf +OCTAVE = OCTAVE_HISTFILE=/dev/null @OCTAVE@ +OCTAVE_CXX = $(DEFS) @OCTAVE_CPPFLAGS@ @OCTAVE_CXXFLAGS@ # Extra Octave specific dynamic linking options -OCTAVE_DLNK = @OCTAVEDYNAMICLINKING@ +OCTAVE_DLNK = @OCTAVE_LDFLAGS@ OCTAVE_SO = @OCTAVE_SO@ +OCTAVE_SCRIPT = $(SRCDIR)$(RUNME).m + # ---------------------------------------------------------------- # Build a C dynamically loadable module # Note: Octave requires C++ compiler when compiling C wrappers # ---------------------------------------------------------------- -octave: $(SRCS) - $(SWIG) -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CSRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) +octave: $(SRCDIR_SRCS) + $(SWIG) -octave $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(INCLUDES) $(OCTAVE_CXX) + $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -octave_cpp: $(SRCS) - $(SWIG) -c++ -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) - $(CXXSHARED) -g $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) +octave_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -octave $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(OCTAVE_CXX) + $(CXXSHARED) -g $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- # Running an Octave example # ----------------------------------------------------------------- -OCTSCRIPT = runme.m - -octave_run: $(OCTSCRIPT) - for file in $(OCTSCRIPT); do \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH OCTAVE_PATH=$(srcdir):$$OCTAVE_PATH $(OCTAVE) $$file >/dev/null || break; \ - done +octave_run: + $(RUNTOOL) $(OCTAVE) $(OCTAVE_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- -# Cleaning the octave examples +# Version display +# ----------------------------------------------------------------- + +octave_version: + $(OCTAVE) --version | head -n 1 + +# ----------------------------------------------------------------- +# Cleaning the Octave examples # ----------------------------------------------------------------- octave_clean: + rm -rf __pycache__ rm -f *_wrap* *~ .~* myoctave@EXEEXT@ *.pyc rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ *@OCTAVE_SO@ + rm -f *.@OBJEXT@ *@SO@ *$(OCTAVE_SO) ################################################################## ##### GUILE ###### ################################################################## # Make sure these locate your Guile installation -GUILE_INCLUDE = @GUILEINCLUDE@ -GUILE_LIB = @GUILELIB@ +GUILE = @GUILE@ +GUILE_CFLAGS = @GUILE_CFLAGS@ GUILE_SO = @GUILE_SO@ +GUILE_LIBS = @GUILE_LIBS@ +GUILE_LIBOPTS = @LIBS@ $(SYSLIBS) GUILE_LIBPREFIX = lib +GUILE_SCRIPT = $(SRCDIR)$(RUNME).scm #------------------------------------------------------------------ -# Build a dynamically loaded module with passive linkage and the scm interface +# Build a dynamically loaded module with passive linkage #------------------------------------------------------------------ -guile: $(SRCS) - $(SWIG) -guile -scm -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ISRCS) $(SRCS) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) +guile: $(SRCDIR_SRCS) + $(SWIG) -guile -Linkage passive $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) -guile_cpp: $(SRCS) - $(SWIG) -c++ -guile -scm -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) +guile_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) guile_externalhdr: $(SWIG) -guile -external-runtime $(TARGET) -#------------------------------------------------------------------ -# Build a dynamically loaded module with passive linkage and the gh interface -#------------------------------------------------------------------ -guile_gh: $(SRCS) - $(SWIG) -guile -gh -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ISRCS) $(SRCS) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) - -guile_gh_cpp: $(SRCS) - $(SWIG) -c++ -guile -gh -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) - # ----------------------------------------------------------------- -# Build a dynamically loadable module with passive linkage +# Build Guile interpreter augmented with extra functions # ----------------------------------------------------------------- -guile_passive: $(SRCS) - $(SWIG) -guile -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ISRCS) $(SRCS) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) - -guile_passive_cpp: $(SRCS) - $(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) +guile_augmented: $(SRCDIR_SRCS) + $(SWIG) -guile $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Build statically linked Guile interpreter # ----------------------------------------------------------------- -GUILE_LIBOPTS = @GUILELINK@ @LIBS@ $(SYSLIBS) - -guile_static: $(SRCS) - $(SWIG) -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) \ +guile_static: $(SRCDIR_SRCS) + $(SWIG) -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ - $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile + $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile -guile_static_cpp: $(SRCS) - $(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +guile_static_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ - $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile + $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile -guile_simple: $(SRCS) - $(SWIG) -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) \ - $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile +guile_simple: $(SRCDIR_SRCS) + $(SWIG) -guile -lguilemain.i -Linkage simple $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ + $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile -guile_simple_cpp: $(SRCS) - $(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ - $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile +guile_simple_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ + $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile + +# ----------------------------------------------------------------- +# Running a Guile example +# ----------------------------------------------------------------- + +guile_run: + env GUILE_AUTO_COMPILE=0 $(RUNTOOL) $(GUILE) -l $(GUILE_SCRIPT) $(RUNPIPE) + +guile_augmented_run: + env GUILE_AUTO_COMPILE=0 $(RUNTOOL) ./$(TARGET) $(GUILE_RUNOPTIONS) -s $(GUILE_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +guile_version: + $(GUILE) --version | head -n 1 # ----------------------------------------------------------------- # Cleaning the Guile examples @@ -468,7 +570,7 @@ guile_simple_cpp: $(SRCS) guile_clean: rm -f *_wrap* *~ .~* my-guile@EXEEXT@ $(TARGET)@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@GUILE_SO@ + rm -f *.@OBJEXT@ *$(GUILE_SO) ################################################################## ##### JAVA ###### @@ -486,34 +588,223 @@ JAVASO =@JAVASO@ JAVALDSHARED = @JAVALDSHARED@ JAVACXXSHARED = @JAVACXXSHARED@ JAVACFLAGS = @JAVACFLAGS@ +JAVA = @JAVA@ +JAVAC = @JAVAC@ -d . # ---------------------------------------------------------------- # Build a java dynamically loadable module (C) # ---------------------------------------------------------------- -java: $(SRCS) - $(SWIG) -java $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) - $(JAVALDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) +java: $(SRCDIR_SRCS) + $(SWIG) -java $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) + $(JAVALDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) # ---------------------------------------------------------------- # Build a java dynamically loadable module (C++) # ---------------------------------------------------------------- -java_cpp: $(SRCS) - $(SWIG) -java -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) - $(JAVACXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) +java_cpp: $(SRCDIR_SRCS) + $(SWIG) -java -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) + $(JAVACXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) + +# ---------------------------------------------------------------- +# Compile java files +# ---------------------------------------------------------------- + +java_compile: $(SRCDIR_SRCS) + $(COMPILETOOL) $(JAVAC) $(addprefix $(SRCDIR),$(JAVASRCS)) + +# ----------------------------------------------------------------- +# Run java example +# ----------------------------------------------------------------- + +java_run: + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(JAVA) $(RUNME) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +java_version: + $(JAVA) -version + $(JAVAC) -version || echo "Unknown javac version" # ----------------------------------------------------------------- # Cleaning the java examples # ----------------------------------------------------------------- java_clean: - rm -f *_wrap* *~ .~* *.class `find . -name \*.java | grep -v runme.java` + rm -f *_wrap* *~ .~* *.class `find . -name \*.java | grep -v $(RUNME).java` rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JAVASO@ +################################################################## +##### JAVASCRIPT ###### +################################################################## + +# Note: These targets are also from within Makefiles in the Example directories. +# There is a common makefile, 'Examples/javascript/js_example.mk' to simplify +# create a configuration for a new example. + +ROOT_DIR = @ROOT_DIR@ +JSINCLUDES = @JSCOREINC@ @JSV8INC@ +JSDYNAMICLINKING = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ +NODEJS = @NODEJS@ +NODEGYP = @NODEGYP@ + +# ---------------------------------------------------------------- +# Creating and building Javascript wrappers +# ---------------------------------------------------------------- + +javascript_wrapper: + $(SWIG) -javascript $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.c $(INTERFACEPATH) + +javascript_wrapper_cpp: $(SRCDIR_SRCS) + $(SWIG) -javascript -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cxx $(INTERFACEPATH) + +javascript_build: $(SRCDIR_SRCS) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +javascript_build_cpp: $(SRCDIR_SRCS) +ifeq (node,$(JSENGINE)) + sed -e 's|$$srcdir|./$(SRCDIR)|g' $(SRCDIR)binding.gyp.in > binding.gyp + $(NODEGYP) --loglevel=silent configure build 1>>/dev/null +else + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +endif + +# These targets are used by the test-suite: + +javascript: $(SRCDIR_SRCS) javascript_custom_interpreter + $(SWIG) -javascript $(SWIGOPT) $(INTERFACEPATH) +ifeq (jsc, $(ENGINE)) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +else # (v8 | node) # v8 and node must be compiled as c++ + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +endif + +javascript_cpp: $(SRCDIR_SRCS) javascript_custom_interpreter + $(SWIG) -javascript -c++ $(SWIGOPT) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +# ----------------------------------------------------------------- +# Running a Javascript example +# ----------------------------------------------------------------- + +javascript_custom_interpreter: + (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) JSENGINE='$(JSENGINE)') + +ifeq (node,$(JSENGINE)) +javascript_run: + env NODE_PATH=$$PWD:$(SRCDIR) $(RUNTOOL) $(NODEJS) $(SRCDIR)$(RUNME).js $(RUNPIPE) +else +javascript_run: javascript_custom_interpreter + $(RUNTOOL) $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) -L $(TARGET) $(SRCDIR)$(RUNME).js $(RUNPIPE) +endif + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +javascript_version: +ifeq (, $(ENGINE)) + @if [ "$(NODEJS)" != "" ]; then \ + echo "Node.js: `($(NODEJS) --version)`"; \ + echo "node-gyp: `($(NODEGYP) --version)`"; \ + else \ + echo "Version depends on the interpreter"; \ + fi +endif +ifeq (node, $(ENGINE)) + echo "Node.js: `($(NODEJS) --version)`" + echo "node-gyp: `($(NODEGYP) --version)`" +endif +ifeq (jsc, $(ENGINE)) + @if [ "@JSCOREVERSION@" != "" ]; then \ + echo "@JSCOREVERSION@"; \ + else \ + echo "Unknown JavascriptCore version."; \ + fi +endif +ifeq (v8, $(ENGINE)) + echo "Unknown v8 version." +endif + +# ----------------------------------------------------------------- +# Cleaning the Javascript examples +# ----------------------------------------------------------------- + +javascript_clean: + rm -rf build + rm -f *_wrap* $(RUNME) + rm -f core @EXTRA_CLEAN@ + rm -f *.@OBJEXT@ *@SO@ + rm -f binding.gyp example-gypcopy.cxx + cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean + +################################################################## +##### ANDROID ###### +################################################################## + +ANDROID = @ANDROID@ +ANDROID_NDK_BUILD = @NDKBUILD@ +ANDROID_ADB = @ADB@ +ANT = @ANT@ +TARGETID = 1 + +# ---------------------------------------------------------------- +# Build an Android dynamically loadable module (C) +# ---------------------------------------------------------------- + +android: $(SRCDIR_SRCS) + $(ANDROID) $(SILENT_OPTION) update project --target $(TARGETID) --name $(PROJECTNAME) --path . + $(SWIG) -java $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.c $(INTERFACEPATH) + +$(ANDROID_NDK_BUILD) $(SILENT_PIPE) + $(ANT) $(ANT_QUIET) debug + +# ---------------------------------------------------------------- +# Build an Android dynamically loadable module (C++) +# ---------------------------------------------------------------- + +android_cpp: $(SRCDIR_SRCS) + $(ANDROID) $(SILENT_OPTION) update project --target $(TARGETID) --name $(PROJECTNAME) --path . + $(SWIG) -java -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cpp $(INTERFACEPATH) + +$(ANDROID_NDK_BUILD) $(SILENT_PIPE) + $(ANT) $(ANT_QUIET) debug + +# ---------------------------------------------------------------- +# Android install +# ---------------------------------------------------------------- + +android_install: + -$(ANDROID_ADB) uninstall $(PACKAGENAME) + $(ANDROID_ADB) install $(INSTALLOPTIONS) bin/$(PROJECTNAME)-debug.apk + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +android_version: + $(ANDROID_ADB) version + +# ----------------------------------------------------------------- +# Cleaning the Android examples +# ----------------------------------------------------------------- + +android_clean: + test -n "$(SRCDIR)" && cd $(SRCDIR) ; $(ANT) -q -logfile /dev/null clean + rm -f $(INTERFACEDIR)$(TARGET)_wrap.* + rm -f `find $(PACKAGEDIR) -name \*.java | grep -v $(PROJECTNAME).java` + rm -rf obj + ################################################################## ##### MODULA3 ###### ################################################################## @@ -524,13 +815,25 @@ MODULA3_INCLUDE= @MODULA3INC@ # Build a modula3 dynamically loadable module (C) # ---------------------------------------------------------------- -modula3: $(SRCS) - $(SWIG) -modula3 $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) \ -# $(OBJS) $(IOBJS) $(LIBS) +modula3: $(SRCDIR_SRCS) + $(SWIG) -modula3 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) -modula3_cpp: $(SRCS) - $(SWIG) -modula3 -c++ $(SWIGOPT) $(INTERFACEPATH) +modula3_cpp: $(SRCDIR_SRCS) + $(SWIG) -modula3 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + +# ----------------------------------------------------------------- +# Run modula3 example +# ----------------------------------------------------------------- + +modula3_run: + $(RUNTOOL) false $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +modula3_version: + echo "Unknown modula3 version" # ----------------------------------------------------------------- # Cleaning the modula3 examples @@ -545,23 +848,40 @@ modula3_clean: ##### MZSCHEME ###### ################################################################## +MZSCHEME = mzscheme MZC = @MZC@ MZDYNOBJ = @MZDYNOBJ@ MZSCHEME_SO = @MZSCHEME_SO@ +MZSCHEME_SCRIPT = $(RUNME).scm # ---------------------------------------------------------------- # Build a C/C++ dynamically loadable module # ---------------------------------------------------------------- -mzscheme: $(SRCS) - $(SWIG) -mzscheme $(SWIGOPT) $(INTERFACEPATH) - $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ISRCS) $(SRCS) +mzscheme: $(SRCDIR_SRCS) + $(SWIG) -mzscheme $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ISRCS) $(SRCDIR_SRCS) $(COMPILETOOL) $(MZC) --ld $(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) -mzscheme_cpp: $(SRCS) - $(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACEPATH) - $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) +mzscheme_cpp: $(SRCDIR_SRCS) + $(SWIG) -mzscheme -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) + $(CXXSHARED) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) + +# ----------------------------------------------------------------- +# Run mzscheme example +# ----------------------------------------------------------------- + +mzscheme_run: + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(MZSCHEME) -r $(MZSCHEME_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +mzscheme_version: + $(MZSCHEME) -v + $(MZC) -v # ----------------------------------------------------------------- # Cleaning the mzscheme examples @@ -570,7 +890,7 @@ mzscheme_cpp: $(SRCS) mzscheme_clean: rm -f *_wrap* *~ .~* rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(MZSCHEME_SO) ################################################################## ##### Ocaml ##### @@ -582,7 +902,7 @@ OCAMLFIND=@OCAMLFIND@ OCAMLMKTOP=@OCAMLMKTOP@ $(SWIGWHERE) NOLINK ?= false OCAMLPP= -pp "camlp4o ./swigp4.cmo" -OCAMLP4WHERE=`$(COMPILETOOL) camlp4 -where` +OCAMLP4WHERE=`$(COMPILETOOL) @CAMLP4@ -where` OCAMLCORE=\ rm -rf swig.mli swig.ml swigp4.ml && \ $(SWIG) -ocaml -co swig.mli 2>/dev/null && \ @@ -593,10 +913,10 @@ OCAMLCORE=\ $(OCC) -I $(OCAMLP4WHERE) -pp "camlp4o pa_extend.cmo q_MLast.cmo" \ -c swigp4.ml -ocaml_static: $(SRCS) +ocaml_static: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) - $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) + $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -607,11 +927,11 @@ ocaml_static: $(SRCS) $(PROGFILE:%.ml=%.cmo) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) -cclib "$(LIBS)" -ocaml_dynamic: $(SRCS) +ocaml_dynamic: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) - $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) - $(CXXSHARED) $(CFLAGS) $(CCSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ + $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) + $(CXXSHARED) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(CCSHARED) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ $(INTERFACE:%.i=%_dynamic.ml) @@ -626,10 +946,10 @@ ocaml_dynamic: $(SRCS) -package dl -linkpkg \ $(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo) -ocaml_static_toplevel: $(SRCS) +ocaml_static_toplevel: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) - $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) + $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -641,12 +961,12 @@ ocaml_static_toplevel: $(SRCS) $(INTERFACE:%.i=%.cmo) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) -cclib "$(LIBS)" -ocaml_static_cpp: $(SRCS) +ocaml_static_cpp: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -ocaml -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ - $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) + $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -658,12 +978,12 @@ ocaml_static_cpp: $(SRCS) $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ -cclib "$(LIBS)" -cc '$(CXX) -Wno-write-strings' -ocaml_static_cpp_toplevel: $(SRCS) +ocaml_static_cpp_toplevel: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -ocaml -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ - $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) + $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -676,13 +996,13 @@ ocaml_static_cpp_toplevel: $(SRCS) $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ -cclib "$(LIBS)" -cc '$(CXX) -Wno-write-strings' -ocaml_dynamic_cpp: $(SRCS) +ocaml_dynamic_cpp: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -ocaml -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ - $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) -ccopt -fPIC - $(CXXSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ + $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) -ccopt -fPIC + $(CXXSHARED) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ $(CPP_DLLIBS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ @@ -699,6 +1019,24 @@ ocaml_dynamic_cpp: $(SRCS) -package dl -linkpkg \ $(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo) -cc '$(CXX) -Wno-write-strings' +# ----------------------------------------------------------------- +# Run ocaml example +# ----------------------------------------------------------------- + +ocaml_run: + $(RUNTOOL) ./$(TARGET) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +ocaml_version: + $(OCC) -version + +# ----------------------------------------------------------------- +# Cleaning the Ocaml examples +# ----------------------------------------------------------------- + ocaml_clean: rm -f *_wrap* *~ .~* *.cmo *.cmi $(MLFILE) $(MLFILE)i swig.mli swig.cmi swig.ml swig.cmo swigp4.ml swigp4.cmo rm -f core @EXTRA_CLEAN@ @@ -713,24 +1051,29 @@ RUBY_CFLAGS= @RUBYCCDLFLAGS@ $(DEFS) RUBY_INCLUDE= @RUBYINCLUDE@ RUBY_LIB = @RUBYLIB@ RUBY_DLNK = @RUBYDYNAMICLINKING@ +RUBY_LIBOPTS = @RUBYLINK@ @LIBS@ $(SYSLIBS) +RUBY_SO = @RUBYSO@ +RUBY = @RUBY@ +RUBY_SCRIPT = $(SRCDIR)$(RUNME).rb + # ---------------------------------------------------------------- # Build a C dynamically loadable module # ---------------------------------------------------------------- -ruby: $(SRCS) - $(SWIG) -ruby $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +ruby: $(SRCDIR_SRCS) + $(SWIG) -ruby $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(RUBY_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -ruby_cpp: $(SRCS) - $(SWIG) -c++ -ruby $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +ruby_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -ruby $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build statically linked Ruby interpreter @@ -739,62 +1082,79 @@ ruby_cpp: $(SRCS) # library file # ----------------------------------------------------------------- -RUBY_LIBOPTS = @RUBYLINK@ @LIBS@ $(SYSLIBS) - -ruby_static: $(SRCS) - $(SWIG) -ruby -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \ +ruby_static: $(SRCDIR_SRCS) + $(SWIG) -ruby -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) -ruby_cpp_static: $(SRCS) - $(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +ruby_cpp_static: $(SRCDIR_SRCS) + $(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) +# ----------------------------------------------------------------- +# Run Ruby example +# ----------------------------------------------------------------- + +ruby_run: + $(RUNTOOL) $(RUBY) $(RUBYFLAGS) -I. $(RUBY_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +ruby_version: + $(RUBY) -v # ----------------------------------------------------------------- # Cleaning the Ruby examples # ----------------------------------------------------------------- ruby_clean: - rm -f *_wrap* *~ .~* myruby@EXEEXT@ *.pm + rm -f *_wrap* *~ .~* myruby@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(RUBY_SO) ################################################################## ##### PHP ###### ################################################################## +PHP = @PHP@ +PHP_INCLUDE = @PHPINC@ +PHP_SO = @PHP_SO@ +PHP_SCRIPT = $(SRCDIR)$(RUNME).php + # ------------------------------------------------------------------- # Build a PHP dynamically loadable module (C) # ------------------------------------------------------------------- -PHP_INCLUDE = @PHPINC@ -PHP_SO = @PHP_SO@ - -php: $(SRCS) - $(SWIG) -php $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) +php: $(SRCDIR_SRCS) + $(SWIG) -php $(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) # -------------------------------------------------------------------- # Build a PHP dynamically loadable module (C++) # -------------------------------------------------------------------- -php_cpp: $(SRCS) - $(SWIG) -php -cppext cxx -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) +php_cpp: $(SRCDIR_SRCS) + $(SWIG) -php -cppext cxx -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) # ----------------------------------------------------------------- # Running a PHP example # ----------------------------------------------------------------- -PHP=@PHP@ -PHPSCRIPT ?= runme.php - php_run: - $(RUNTOOL) $(PHP) -n -q -d extension_dir=. -d safe_mode=Off $(PHPSCRIPT) + $(RUNTOOL) $(PHP) -n -q -d extension_dir=. -d safe_mode=Off $(PHP_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +php_version: + $(PHP) -v | head -n 1 # ----------------------------------------------------------------- # Cleaning the PHP examples @@ -803,35 +1163,38 @@ php_run: php_clean: rm -f *_wrap* *~ .~* example.php php_example.h rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(PHP_SO) ################################################################## ##### Pike ###### ################################################################## # Make sure these locate your Pike installation +PIKE = pike PIKE_CFLAGS = @PIKECCDLFLAGS@ -DHAVE_CONFIG_H PIKE_INCLUDE = @PIKEINCLUDE@ PIKE_LIB = @PIKELIB@ PIKE_DLNK = @PIKEDYNAMICLINKING@ +PIKE_LIBOPTS = @PIKELINK@ @LIBS@ $(SYSLIBS) +PIKE_SCRIPT = $(RUNME).pike # ---------------------------------------------------------------- # Build a C dynamically loadable module # ---------------------------------------------------------------- -pike: $(SRCS) - $(SWIG) -pike $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(PIKE_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +pike: $(SRCDIR_SRCS) + $(SWIG) -pike $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PIKE_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -pike_cpp: $(SRCS) - $(SWIG) -c++ -pike $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +pike_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -pike $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Build statically linked Pike interpreter @@ -840,18 +1203,30 @@ pike_cpp: $(SRCS) # library file # ----------------------------------------------------------------- -PIKE_LIBOPTS = @PIKELINK@ @LIBS@ $(SYSLIBS) - -pike_static: $(SRCS) - $(SWIG) -pike -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \ +pike_static: $(SRCDIR_SRCS) + $(SWIG) -pike -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) -pike_cpp_static: $(SRCS) - $(SWIG) -c++ -pike -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +pike_cpp_static: $(SRCDIR_SRCS) + $(SWIG) -c++ -pike -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) +# ----------------------------------------------------------------- +# Run pike example +# ----------------------------------------------------------------- + +pike_run: + $(RUNTOOL) $(PIKE) $(PIKE_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +pike_version: + $(PIKE) -v 2>&1 | head -n 1 + # ----------------------------------------------------------------- # Cleaning the Pike examples # ----------------------------------------------------------------- @@ -868,11 +1243,13 @@ pike_clean: CHICKEN = @CHICKEN@ CHICKEN_CSC = @CHICKEN_CSC@ +CHICKEN_CSI = @CHICKEN_CSI@ CHICKEN_LIBOPTS = @CHICKENLIB@ $(SYSLIBS) CHICKEN_SHAREDLIBOPTS = @CHICKENSHAREDLIB@ $(SYSLIBS) CHICKEN_CFLAGS = @CHICKENOPTS@ CHICKENOPTS = -quiet CHICKEN_MAIN = +CHICKEN_SCRIPT = $(RUNME).scm # SWIG produces $(ISRCS) (the C wrapper file) # and $(CHICKEN_GENERATED_SCHEME) (the Scheme wrapper file): @@ -880,7 +1257,7 @@ CHICKEN_GENERATED_SCHEME = $(INTERFACE:.i=.scm) CHICKEN_COMPILED_SCHEME = $(INTERFACE:.i=_chicken.c) CHICKEN_COMPILED_OBJECT = $(CHICKEN_COMPILED_SCHEME:.c=.@OBJEXT@) -# flags for the main chicken sources (only used when compiling staticly) +# flags for the main chicken sources (only used when compiling statically) CHICKEN_COMPILED_MAIN = $(CHICKEN_MAIN:.scm=_chicken.c) CHICKEN_COMPILED_MAIN_OBJECT = $(CHICKEN_COMPILED_MAIN:.c=.@OBJEXT@) @@ -889,24 +1266,24 @@ CHICKEN_COMPILED_MAIN_OBJECT = $(CHICKEN_COMPILED_MAIN:.c=.@OBJEXT@) # ----------------------------------------------------------------- # This is the old way to build chicken, but it does not work correctly with exceptions -chicken_direct: $(SRCS) +chicken_direct: $(SRCDIR_SRCS) $(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCS) $(CHICKEN_COMPILED_SCHEME) - $(LDSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(CHICKEN_CFLAGS) \ + $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCDIR_SRCS) $(CHICKEN_COMPILED_SCHEME) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) -chicken_direct_cpp: $(CXXSRCS) $(CHICKSRCS) +chicken_direct_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) $(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(CHICKEN_COMPILED_SCHEME) - $(CXXSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ + $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(CHICKEN_COMPILED_SCHEME) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -914,28 +1291,28 @@ chicken_direct_cpp: $(CXXSRCS) $(CHICKSRCS) # ----------------------------------------------------------------- # The following two targets are also used by the test suite -chicken_static: $(SRCS) $(CHICKSRCS) +chicken_static: $(SRCDIR_SRCS) $(CHICKSRCS) $(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCS) \ + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(CHICKEN_CFLAGS) \ + $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCDIR_SRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) - $(CC) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ + $(CC) $(CFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ $(OBJS) $(IOBJS) $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET) -chicken_static_cpp: $(CXXSRCS) $(CHICKSRCS) +chicken_static_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) $(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) \ + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ + $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) - $(CXX) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ + $(CXX) $(CXXFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET) # ---------------------------------------------------------------- @@ -944,15 +1321,33 @@ chicken_static_cpp: $(CXXSRCS) $(CHICKSRCS) chicken: $(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) - $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCS) $(ISRCS) -o $(TARGET)$(SO) + $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCDIR_SRCS) $(ISRCS) -o $(TARGET)$(SO) chicken_cpp: $(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) - $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCS) $(ICXXSRCS) $(CXXSRCS) -o $(TARGET)$(SO) + $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCDIR_SRCS) $(ICXXSRCS) $(SRCDIR_CXXSRCS) -o $(TARGET)$(SO) chicken_externalhdr: $(SWIG) -chicken -external-runtime $(TARGET) +# ----------------------------------------------------------------- +# Run CHICKEN example +# ----------------------------------------------------------------- + +chicken_run: + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(CHICKEN_CSI) $(CHICKEN_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +chicken_version: + $(CHICKEN) -version | grep -i version + +# ----------------------------------------------------------------- +# Cleaning the CHICKEN examples +# ----------------------------------------------------------------- + chicken_clean: rm -f *_wrap* *~ .~* *_chicken* rm -f core @EXTRA_CLEAN@ @@ -967,40 +1362,66 @@ CSHARP_DLNK = @CSHARPDYNAMICLINKING@ CSHARP_LIBPREFIX = @CSHARPLIBRARYPREFIX@ CSHARPCOMPILER = @CSHARPCOMPILER@ CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ +CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ CSHARPCFLAGS = @CSHARPCFLAGS@ +CSHARPFLAGS = +CSHARPOPTIONS = CSHARPSO = @CSHARPSO@ +CSHARP_RUNME = $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$(RUNME).exe # ---------------------------------------------------------------- # Build a CSharp dynamically loadable module (C) # ---------------------------------------------------------------- -csharp: $(SRCS) - $(SWIG) -csharp $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) +csharp: $(SRCDIR_SRCS) + $(SWIG) -csharp $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Build a CSharp dynamically loadable module (C++) # ---------------------------------------------------------------- -csharp_cpp: $(SRCS) - $(SWIG) -csharp -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) +csharp_cpp: $(SRCDIR_SRCS) + $(SWIG) -csharp -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Compile CSharp files # ---------------------------------------------------------------- -csharp_compile: $(SRCS) - $(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPSRCS) +ifneq (,$(SRCDIR)) +SRCDIR_CSHARPSRCS = $(addprefix $(SRCDIR),$(CSHARPSRCS)) +else +SRCDIR_CSHARPSRCS = +endif + +csharp_compile: $(SRCDIR_SRCS) + $(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPOPTIONS) $(CSHARPSRCS) $(SRCDIR_CSHARPSRCS) + +# ----------------------------------------------------------------- +# Run CSharp example +# ----------------------------------------------------------------- + +csharp_run: + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(CSHARP_RUNME) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +# Version check below also works with MS csc.exe which does not understand --version +csharp_version: + $(CSHARPCOMPILER) --version | head -n 1 + if test -n "$(CSHARPCILINTERPRETER)" ; then "$(CSHARPCILINTERPRETER)" --version ; fi # ----------------------------------------------------------------- # Cleaning the CSharp examples # ----------------------------------------------------------------- csharp_clean: - rm -f *_wrap* *~ .~* runme runme.exe *.exe.mdb gc.log `find . -name \*.cs | grep -v runme.cs` + rm -f *_wrap* *~ .~* $(RUNME) $(RUNME).exe *.exe.mdb gc.log `find . -name \*.cs | grep -v $(RUNME).cs` rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@CSHARPSO@ @@ -1016,41 +1437,67 @@ LUA_LIB = @LUALINK@ LUA_DLNK = @LUADYNAMICLINKING@ LUA_SO = @LUA_SO@ +LUA = @LUABIN@ +LUA_SCRIPT = $(SRCDIR)$(RUNME).lua + # Extra code for lua static link -LUA_INTERP = ../lua.c +LUA_INTERP = ../lua.c # ---------------------------------------------------------------- # Build a C dynamically loadable module # ---------------------------------------------------------------- -lua: $(SRCS) - $(SWIG) -lua $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(LUA_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) +lua: $(SRCDIR_SRCS) + $(SWIG) -lua $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(LUA_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -lua_cpp: $(SRCS) - $(SWIG) -c++ -lua $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(LUA_INCLUDE) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) +lua_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) + $(SWIG) -c++ -lua $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(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 # ----------------------------------------------------------------- -lua_static: $(SRCS) - $(SWIG) -lua -module example $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(LUA_INTERP) $(INCLUDES) \ +lua_static: $(SRCDIR_SRCS) + $(SWIG) -lua -module example $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) -lua_static_cpp: $(SRCS) - $(SWIG) -c++ -lua -module example $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(LUA_INTERP) $(INCLUDES) \ +lua_static_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) + $(SWIG) -c++ -lua -module example $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) +# ----------------------------------------------------------------- +# Run Lua example +# ----------------------------------------------------------------- + +lua_run: + $(RUNTOOL) $(LUA) $(LUA_SCRIPT) $(RUNPIPE) + +lua_embed_run: + $(RUNTOOL) ./$(TARGET) $(LUA_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +lua_version: + $(LUA) -v | head -n 1 + # ----------------------------------------------------------------- # Cleaning the lua examples # ----------------------------------------------------------------- @@ -1058,21 +1505,42 @@ lua_static_cpp: $(SRCS) lua_clean: rm -f *_wrap* *~ .~* mylua@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(LUA_SO) ################################################################## ##### ALLEGRO CL ###### ################################################################## -allegrocl: $(SRCS) - $(SWIG) -allegrocl -cwrap $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +ALLEGROCL = @ALLEGROCLBIN@ +ALLEGROCL_SCRIPT=$(RUNME).lisp -allegrocl_cpp: $(SRCS) - $(SWIG) -c++ -allegrocl $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +allegrocl: $(SRCDIR_SRCS) + $(SWIG) -allegrocl -cwrap $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +allegrocl_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -allegrocl $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +# ----------------------------------------------------------------- +# Run ALLEGRO CL example +# ----------------------------------------------------------------- + +allegrocl_run: + $(RUNTOOL) $(ALLEGROCL) -batch -s $(ALLEGROCL_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +allegrocl_version: + $(ALLEGROCL) --version + +# ----------------------------------------------------------------- +# Cleaning the ALLEGRO CL examples +# ----------------------------------------------------------------- allegrocl_clean: rm -f *_wrap* *~ .~* @@ -1083,11 +1551,32 @@ allegrocl_clean: ##### CLISP ###### ################################################################## -clisp: $(SRCS) - $(SWIG) -clisp $(SWIGOPT) $(INTERFACEPATH) +CLISP = @CLISPBIN@ +CLISP_SCRIPT=$(RUNME).lisp -clisp_cpp: $(SRCS) - $(SWIG) -c++ -clisp $(SWIGOPT) $(INTERFACEPATH) +clisp: $(SRCDIR_SRCS) + $(SWIG) -clisp $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + +clisp_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -clisp $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + +# ----------------------------------------------------------------- +# Run CLISP example +# ----------------------------------------------------------------- + +clisp_run: + $(RUNTOOL) $(CLISP) -batch -s $(CLISP_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +clisp_version: + $(CLISP) --version | head -n 1 + +# ----------------------------------------------------------------- +# Cleaning the CLISP examples +# ----------------------------------------------------------------- clisp_clean: rm -f *_wrap* *~ .~* @@ -1098,15 +1587,36 @@ clisp_clean: ##### CFFI ###### ################################################################## -cffi: $(SRCS) - $(SWIG) -cffi $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) -# $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +CFFI = @CFFIBIN@ +CFFI_SCRIPT=$(RUNME).lisp -cffi_cpp: $(SRCS) - $(SWIG) -c++ -cffi $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +cffi: $(SRCDIR_SRCS) + $(SWIG) -cffi $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +# $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) +# $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +cffi_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -cffi $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +# ----------------------------------------------------------------- +# Run CFFI example +# ----------------------------------------------------------------- + +cffi_run: + $(RUNTOOL) $(CFFI) -batch -s $(CFFI_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +cffi_version: + $(CFFI) --version + +# ----------------------------------------------------------------- +# Cleaning the CFFI examples +# ----------------------------------------------------------------- cffi_clean: rm -f *_wrap* *~ .~* @@ -1117,15 +1627,36 @@ cffi_clean: ##### UFFI ###### ################################################################## -uffi: $(SRCS) - $(SWIG) -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) -# $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +UFFI = @UFFIBIN@ +UFFI_SCRIPT=$(RUNME).lisp -uffi_cpp: $(SRCS) - $(SWIG) -c++ -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -# $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +uffi: $(SRCDIR_SRCS) + $(SWIG) -uffi $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +# $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) +# $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +uffi_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -uffi $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) +# $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) +# $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +# ----------------------------------------------------------------- +# Run UFFI example +# ----------------------------------------------------------------- + +uffi_run: + $(RUNTOOL) $(UFFI) -batch -s $(UFFI_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +uffi_version: + $(UFFI) --version + +# ----------------------------------------------------------------- +# Cleaning the UFFI examples +# ----------------------------------------------------------------- uffi_clean: rm -f *_wrap* *~ .~* @@ -1140,30 +1671,56 @@ 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=$(SRCDIR)$(RUNME).R # need to compile .cxx files outside of R build system to make sure that # we get -fPIC # CMD SHLIB stdout is piped to /dev/null to prevent echo of compiler command -r: $(SRCS) - $(SWIG) -r $(SWIGOPT) $(INTERFACEPATH) -ifneq ($(SRCS),) - $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES) -endif - +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null ) +# ---------------------------------------------------------------- +# Build a R dynamically loadable module (C) +# ---------------------------------------------------------------- -r_cpp: $(CXXSRCS) - $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) -ifneq ($(CXXSRCS),) - $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) +r: $(SRCDIR_SRCS) + $(SWIG) -r $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +ifneq ($(SRCDIR_SRCS),) + $(CC) -g -c $(CPPFLAGS) $(CFLAGS) $(R_CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) endif - +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) + +( PKG_CPPFLAGS="$(CPPFLAGS) $(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null ) + +# ---------------------------------------------------------------- +# Build a R dynamically loadable module (C++) +# ---------------------------------------------------------------- +r_cpp: $(SRCDIR_CXXSRCS) + $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) +ifneq ($(SRCDIR_CXXSRCS),) + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(R_CFLAGS) $(SRCDIR_CXXSRCS) $(INCLUDES) +endif + +( PKG_CPPFLAGS="$(CPPFLAGS) $(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) + +# ----------------------------------------------------------------- +# Run R example +# ----------------------------------------------------------------- + +r_run: + $(RUNTOOL) $(R) CMD BATCH $(R_SCRIPT) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +r_version: + $(R) --version | head -n 1 + +# ----------------------------------------------------------------- +# Cleaning the R examples +# ----------------------------------------------------------------- r_clean: rm -f *_wrap* *~ .~* rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ NAMESPACE - rm -f $(RRSRC) runme.Rout .RData + rm -f $(RRSRC) $(RUNME).Rout .RData ################################################################## ##### C ###### @@ -1193,78 +1750,293 @@ c_cpp: $(SRCS) c_compile: $(RUNME) $(PROXY) $(CC) $(RUNME) $(PROXY) -L. -l$(TARGET) -o $(RUNME:.c=) +################################################################## +##### SCILAB ###### +################################################################## + +SCILAB = @SCILAB@ +SCILAB_INC= @SCILABINCLUDE@ +SCILAB_OPT = @SCILABOPT@ +SCILAB_LIBPREFIX = lib + +# ---------------------------------------------------------------- +# Build a C dynamically loadable module +# ---------------------------------------------------------------- + +scilab: + $(SWIG) -scilab $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SCILAB_INC) $(INCLUDES) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(IOBJS) $(OBJS) $(LIBS) -o $(SCILAB_LIBPREFIX)$(TARGET)$(SO) + +# ---------------------------------------------------------------- +# Build a C++ dynamically loadable module +# ---------------------------------------------------------------- + +scilab_cpp: + $(SWIG) -c++ -scilab $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SCILAB_INC) $(INCLUDES) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(IOBJS) $(OBJS) $(LIBS) $(CPP_DLLIBS) -o $(SCILAB_LIBPREFIX)$(TARGET)$(SO) + +# ----------------------------------------------------------------- +# Running a Scilab example +# ----------------------------------------------------------------- + +scilab_run: + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(SCILAB) $(SCILAB_OPT) -f $(SRCDIR)$(RUNME).sci $(RUNPIPE) + +# ----------------------------------------------------------------- +# Scilab version +# ----------------------------------------------------------------- + +scilab_version: + echo `$(SCILAB) -version | head -1` + +# ----------------------------------------------------------------- +# Cleaning the scilab examples +# ----------------------------------------------------------------- + +scilab_clean: + rm -f *_wrap* *~ .~* + rm -f core @EXTRA_CLEAN@ + rm -f *.@OBJEXT@ *@SO@ + rm -f *.sce + ################################################################## ##### Go ###### ################################################################## +# TODO: The Go make targets need simplifying to use configure time +# configuration or to use Make's ifeq rather than using lots of +# runtime shell code. The output will then be a lot less verbose. + GO = @GO@ GOGCC = @GOGCC@ +GCCGO = @GCCGO@ GO1 = @GO1@ +GO12 = @GO12@ +GO13 = @GO13@ +GO15 = @GO15@ GOC = @GOC@ +GOOPT = @GOOPT@ +GCCGOOPT = @GCCGOOPT@ +GOVERSIONOPTION = @GOVERSIONOPTION@ GOSWIGARG = `if $(GOGCC) ; then echo -gccgo; fi` -GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` +GOCOMPILEARG = `if $(GO15); then echo tool compile; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` `if $(GO13) || $(GO15); then echo -pack ; fi` GOSRCS = $(INTERFACE:.i=.go) GOCSRCS = $(INTERFACE:.i=_gc.c) -GOLD = $(GOC:c=l) +GOLD = `if $(GO15); then echo link; else echo $(GOC:c=l); fi` GOTOOL = `if $(GO1) ; then echo go tool; fi` GOPACK = `if $(GO1) ; then echo go tool pack; else echo gopack; fi` -GOPACKAGE = $(INTERFACE:.i=.a) +GOPACKAGE = $(notdir $(INTERFACE:.i=.a)) -GOOBJEXT = $(GOC:c=) +GOPATHDIR = gopath/src/$(INTERFACE:.i=) + +GOOBJEXT = `if $(GO15); then echo o; else echo $(GOC:c=); fi` GOGCOBJS = $(GOSRCS:.go=.$(GOOBJEXT)) GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) # ---------------------------------------------------------------- -# Build a Go dynamically loadable module (C) +# Build a Go module (C) # ---------------------------------------------------------------- -go: $(SRCS) - $(SWIG) -go $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) - if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ - $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ - fi - -# ---------------------------------------------------------------- -# Build a Go dynamically loadable module (C++) -# ---------------------------------------------------------------- - -go_cpp: $(SRCS) - $(SWIG) -go -c++ $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) - if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ - $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ - fi - -# ----------------------------------------------------------------- -# Running a Go example -# ----------------------------------------------------------------- - -go_run: runme.go - $(GO) $(GOCOMPILEARG) runme.go - if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(LIBPREFIX)$(TARGET)$(SO); \ +go_nocgo: $(SRCDIR_SRCS) + $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + if $(GO12) || $(GO13) || $(GO15) || $(GOGCC); then \ + $(CC) -g -c $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ else \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ + $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -g -c -I . $(GOSRCS); \ + else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ + rm -f $(GOPACKAGE); \ + if $(GO13) || $(GO15); then \ + cp $(GOGCOBJS) $(GOPACKAGE); \ + $(COMPILETOOL) $(GOPACK) r $(GOPACKAGE) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + else \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + fi; \ + fi + if test -f $(SRCDIR)$(RUNME).go; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -g -c $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CC)" -extldflags "$(CFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi + +go: $(SRCDIR_SRCS) + $(SWIG) -go -cgo $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + @mkdir gopath 2>/dev/null || true + @mkdir gopath/src 2>/dev/null || true + @mkdir gopath/src/$(INTERFACE:.i=) 2>/dev/null || true + rm -f $(GOPATHDIR)/* + cp $(ISRCS) $(GOPATHDIR)/ + if test -f $(IWRAP:.i=.h); then \ + cp $(IWRAP:.i=.h) $(GOPATHDIR)/; \ + fi + if test -n "$(SRCDIR_SRCS)"; then \ + cp $(SRCDIR_SRCS) $(GOPATHDIR)/; \ + fi + cp $(GOSRCS) $(GOPATHDIR)/ + GOPATH=`pwd`/gopath; \ + export GOPATH; \ + CGO_CPPFLAGS="$(CPPFLAGS) $(INCLUDES) -I `cd $(SRCDIR) && pwd` -I `pwd`"; \ + export CGO_CPPFLAGS; \ + CGO_CFLAGS="$(CFLAGS)"; \ + export CGO_CFLAGS; \ + CGO_LDFLAGS="$(LDFLAGS) -lm"; \ + export CGO_LDFLAGS; \ + (cd $(GOPATHDIR)/ && $(COMPILETOOL) $(GO) build `if $(GOGCC); then echo -compiler=gccgo; fi` -o $(GOPACKAGE)) + cp $(GOPATHDIR)/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE) + if $(GOGCC); then \ + cp $(dir $(INTERFACE))/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE:.a=.gox); \ + fi + if test -f $(SRCDIR)$(RUNME).go; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -c -g $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(dir $(INTERFACE))/$(GOPACKAGE); \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -o $(RUNME).$(GOOBJEXT) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CC)" -extldflags "$(CFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi + +# ---------------------------------------------------------------- +# Build a Go module (C++) +# ---------------------------------------------------------------- + +go_cpp_nocgo: $(SRCDIR_SRCS) + $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + if $(GO12) || $(GO13) || $(GO15) || $(GOGCC); then \ + if test -n "$(SRCDIR_CXXSRCS)$(SRCDIR_SRCS)"; then \ + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_CXXSRCS) $(SRCDIR_SRCS) $(INCLUDES); \ + fi; \ + $(foreach f,$(ICXXSRCS), \ + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) -o $(addsuffix .@OBJEXT@,$(basename $f)) $f $(INCLUDES); \ + ) \ + else \ + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ + fi + if ! $(GOGCC) ; then \ + $(foreach f,$(GOSRCS), \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . -o $(addsuffix .$(GOOBJEXT),$(basename $f)) $f \ + ); \ + $(foreach f,$(GOCSRCS), \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} \ + -o $(addsuffix .$(GOOBJEXT),$(basename $f)) $f; \ + ) \ + rm -f $(GOPACKAGE); \ + if $(GO13) || $(GO15); then \ + cp $(GOGCOBJS) $(GOPACKAGE); \ + $(COMPILETOOL) $(GOPACK) r $(GOPACKAGE) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + elif $(GO12); then \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ + else \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + fi; \ + else \ + $(foreach f,$(GOSRCS), \ + $(COMPILETOOL) $(GCCGO) -g -c -I . -o $(addsuffix .@OBJEXT@,$(basename $f)) $f \ + ); \ + fi + if test -f $(SRCDIR)$(RUNME).go; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -g -c $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CXX)" -extldflags "$(CXXFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi + +go_cpp: $(SRCDIR_SRCS) + $(SWIG) -go -c++ -cgo $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + @mkdir gopath 2>/dev/null || true + @mkdir gopath/src 2>/dev/null || true + @mkdir gopath/src/$(INTERFACE:.i=) 2>/dev/null || true + rm -f $(GOPATHDIR)/* + cp $(ICXXSRCS) $(GOPATHDIR)/ + if test -f $(IWRAP:.i=.h); then \ + cp $(IWRAP:.i=.h) $(GOPATHDIR)/; \ + fi + if test -n "$(SRCDIR_CXXSRCS)"; then \ + cp $(SRCDIR_CXXSRCS) $(GOPATHDIR)/; \ + fi + if test -n "$(SRCDIR_SRCS)"; then \ + cp $(SRCDIR_SRCS) $(GOPATHDIR)/; \ + fi + cp $(GOSRCS) $(GOPATHDIR)/ + GOPATH=`pwd`/gopath; \ + export GOPATH; \ + CGO_CPPFLAGS="$(CPPFLAGS) $(INCLUDES) -I `cd $(SRCDIR) && pwd` -I `pwd`"; \ + export CGO_CPPFLAGS; \ + CGO_CFLAGS="$(CFLAGS)"; \ + export CGO_CFLAGS; \ + CGO_CXXFLAGS="$(CXXFLAGS)"; \ + export CGO_CXXFLAGS; \ + CGO_LDFLAGS="$(LDFLAGS) -lm"; \ + export CGO_LDFLAGS; \ + (cd $(GOPATHDIR) && $(COMPILETOOL) $(GO) build `if $(GOGCC); then echo -compiler=gccgo; fi` -o $(GOPACKAGE)) + cp $(GOPATHDIR)/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE) + if $(GOGCC); then \ + cp $(dir $(INTERFACE))/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE:.a=.gox); \ + fi + if test -f $(SRCDIR)$(RUNME).go; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -g -c $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(dir $(INTERFACE))/$(GOPACKAGE) -lstdc++; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -o $(RUNME).$(GOOBJEXT) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CXX)" -extldflags "$(CXXFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi + +# ----------------------------------------------------------------- +# Running Go example +# ----------------------------------------------------------------- + +go_run: + env $(RUNTOOL) ./$(RUNME) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +go_version: + $(GO) $(GOVERSIONOPTION) # ----------------------------------------------------------------- # Cleaning the Go examples # ----------------------------------------------------------------- go_clean: - rm -f *_wrap* *_gc* .~* runme + rm -f *_wrap* *_gc* *.gox .~* $(RUNME) $(GOSRCS) + rm -rf gopath rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *.[568] *.a *@SO@ @@ -1286,23 +2058,25 @@ else DCOMPILER = @D1COMPILER@ endif +D_RUNME = ./$(RUNME) + # ---------------------------------------------------------------- # Build a dynamically loadable D wrapper for a C module # ---------------------------------------------------------------- -d: $(SRCS) - $(SWIGD) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) +d: $(SRCDIR_SRCS) + $(SWIGD) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a dynamically loadable D wrapper for a C++ module # ---------------------------------------------------------------- -d_cpp: $(SRCS) - $(SWIGD) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) +d_cpp: $(SRCDIR_SRCS) + $(SWIGD) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Compile D files @@ -1310,7 +2084,7 @@ d_cpp: $(SRCS) # Clear the DFLAGS environment variable for the compiler call itself # to work around a discrepancy in argument handling between DMD and LDC. -d_compile: $(SRCS) +d_compile: $(SRCDIR_SRCS) DFLAGS="" $(COMPILETOOL) $(DCOMPILER) $(DFLAGS) $(DSRCS) # ----------------------------------------------------------------- @@ -1318,14 +2092,22 @@ d_compile: $(SRCS) # ----------------------------------------------------------------- d_run: - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(D_RUNME) $(RUNPIPE) + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +d_version: + # Needs improvement! + echo D version guess - $(D_VERSION) # ----------------------------------------------------------------- # Clean the D examples # ----------------------------------------------------------------- d_clean: - rm -f *_wrap* *~ .~* runme runme.exe `find . -name \*.d | grep -v runme.d` + rm -f *_wrap* *~ .~* $(RUNME) $(RUNME).exe `find . -name \*.d | grep -v $(RUNME).d` rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ diff --git a/Examples/README b/Examples/README index 4dda3222d..eff0f2c98 100644 --- a/Examples/README +++ b/Examples/README @@ -1,24 +1,18 @@ SWIG Examples -The "perl5", "python", "tcl", "guile", "java", "mzscheme", "ruby", and -"chicken" directories contain a number of simple examples that are -primarily used for testing. +The subdirectories of "Examples" named after SWIG's language backends +contain a number of simple examples that are primarily used for testing. The file 'index.html' is the top of a hyperlinked document that contains information about all of the examples along with various notes related to each example. -The Examples directory is currently quite incomplete because it -is being reorganized. A more complete set of examples can be found -in the SWIG1.1p5 distribution (most of which should still work with -SWIG1.3). - Note: All of the examples rely upon the Makefile in this directory. You may need to edit it to reflect the configuration of your machine in case the configure script guesses incorrect settings. -*** Special note concering C++ *** +*** Special note concerning C++ *** The configure script is currently unable to handle all of the possible options for producing dynamically loadable C++ extensions. Here are diff --git a/Examples/android/check.list b/Examples/android/check.list index 69d56a4f6..0068e25ab 100644 --- a/Examples/android/check.list +++ b/Examples/android/check.list @@ -1,3 +1,4 @@ # see top-level Makefile.in class +extend simple diff --git a/Examples/android/class/Makefile b/Examples/android/class/Makefile index 7de95f559..8b5a090e9 100644 --- a/Examples/android/class/Makefile +++ b/Examples/android/class/Makefile @@ -1,29 +1,28 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib TARGET = example INTERFACE = example.i -PACKAGEDIR = src/org/swig +INTERFACEDIR = jni/ +PACKAGEDIR = $(SRCDIR)src/org/swig PACKAGENAME= org.swig.classexample -SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/classexample +SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/classexample PROJECTNAME= SwigClass TARGETID = 1 +#INSTALLOPTIONS = -s # To install on SD Card -all:: android +check: build -android:: - android update project --target $(TARGETID) --name $(PROJECTNAME) --path . - $(SWIG) -c++ -java $(SWIGOPT) -o jni/$(TARGET)_wrap.cpp jni/$(INTERFACE) - ndk-build - ant debug +build: + $(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:: - -adb uninstall $(PACKAGENAME) - adb install bin/$(PROJECTNAME)-debug.apk +install: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ + PACKAGEDIR='$(PACKAGEDIR)' PACKAGENAME='$(PACKAGENAME)' android_install -clean:: - ant clean - rm -f jni/$(TARGET)_wrap.cpp - rm -f `find $(PACKAGEDIR) -name \*.java | grep -v $(PROJECTNAME).java` - - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ + PACKAGEDIR='$(PACKAGEDIR)' INTERFACEDIR='$(INTERFACEDIR)' android_clean diff --git a/Examples/android/class/jni/example.cpp b/Examples/android/class/jni/example.cpp index d59cc7c32..7686159fa 100644 --- a/Examples/android/class/jni/example.cpp +++ b/Examples/android/class/jni/example.cpp @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/android/class/jni/example.h b/Examples/android/class/jni/example.h index 64b7684fa..0dff185b2 100644 --- a/Examples/android/class/jni/example.h +++ b/Examples/android/class/jni/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,16 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/android/extend/AndroidManifest.xml b/Examples/android/extend/AndroidManifest.xml new file mode 100644 index 000000000..66d2469fa --- /dev/null +++ b/Examples/android/extend/AndroidManifest.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/Examples/android/extend/Makefile b/Examples/android/extend/Makefile new file mode 100644 index 000000000..19d90ecca --- /dev/null +++ b/Examples/android/extend/Makefile @@ -0,0 +1,28 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +TARGET = example +INTERFACE = example.i +INTERFACEDIR = jni/ +PACKAGEDIR = $(SRCDIR)src/org/swig +PACKAGENAME= org.swig.extendexample +SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/extendexample +PROJECTNAME= SwigExtend +TARGETID = 1 +#INSTALLOPTIONS = -s # To install on SD Card + +check: build + +build: + $(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: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ + PACKAGEDIR='$(PACKAGEDIR)' PACKAGENAME='$(PACKAGENAME)' android_install + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ + PACKAGEDIR='$(PACKAGEDIR)' INTERFACEDIR='$(INTERFACEDIR)' android_clean diff --git a/Examples/android/extend/ant.properties b/Examples/android/extend/ant.properties new file mode 100644 index 000000000..ee52d86d9 --- /dev/null +++ b/Examples/android/extend/ant.properties @@ -0,0 +1,17 @@ +# This file is used to override default values used by the Ant build system. +# +# This file must be checked in Version Control Systems, as it is +# integral to the build system of your project. + +# This file is only used by the Ant script. + +# You can use this to override default values such as +# 'source.dir' for the location of your java source folder and +# 'out.dir' for the location of your output folder. + +# You can also use it define how the release builds are signed by declaring +# the following properties: +# 'key.store' for the location of your keystore and +# 'key.alias' for the name of the key to use. +# The password will be asked during the build when you use the 'release' target. + diff --git a/Examples/android/extend/build.xml b/Examples/android/extend/build.xml new file mode 100644 index 000000000..94fe847b7 --- /dev/null +++ b/Examples/android/extend/build.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/android/extend/jni/Android.mk b/Examples/android/extend/jni/Android.mk new file mode 100644 index 000000000..25d42b541 --- /dev/null +++ b/Examples/android/extend/jni/Android.mk @@ -0,0 +1,10 @@ +# File: Android.mk +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := example +LOCAL_SRC_FILES := example_wrap.cpp example.cpp +LOCAL_CFLAGS := -frtti + +include $(BUILD_SHARED_LIBRARY) diff --git a/Examples/android/extend/jni/Application.mk b/Examples/android/extend/jni/Application.mk new file mode 100644 index 000000000..45d13be4e --- /dev/null +++ b/Examples/android/extend/jni/Application.mk @@ -0,0 +1,2 @@ +# File: Application.mk +APP_STL := gnustl_static diff --git a/Examples/android/extend/jni/example.cpp b/Examples/android/extend/jni/example.cpp new file mode 100644 index 000000000..7d76571ca --- /dev/null +++ b/Examples/android/extend/jni/example.cpp @@ -0,0 +1,14 @@ +/* File : example.cxx */ + +#include "example.h" + +static Streamer * streamerInstance = 0; + +void setStreamer(Streamer* streamer) { + streamerInstance = streamer; +} + +Streamer& getStreamer() { + return *streamerInstance; +} + diff --git a/Examples/android/extend/jni/example.h b/Examples/android/extend/jni/example.h new file mode 100644 index 000000000..22430b501 --- /dev/null +++ b/Examples/android/extend/jni/example.h @@ -0,0 +1,71 @@ +/* File : example.h */ + +#include +#include +#include +#include +#include +#include + +struct Streamer { + virtual void display(std::string text) const = 0; + virtual ~Streamer() {} +}; +void setStreamer(Streamer* streamer); +Streamer& getStreamer(); + +template Streamer& operator<<(Streamer& stream, T const& val) { + std::ostringstream s; + s << val; + stream.display(s.str()); + return stream; +} + +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() { getStreamer() << "~Employee() @ " << this << "\n"; } +}; + + +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); + getStreamer() << "New employee added. Current employees are:" << "\n"; + std::vector::iterator i; + for (i=list.begin(); i!=list.end(); i++) { + getStreamer() << " " << (*i)->getTitle() << "\n"; + } + } + const Employee *get_item(int i) { + return list[i]; + } + ~EmployeeList() { + std::vector::iterator i; + getStreamer() << "~EmployeeList, deleting " << list.size() << " employees." << "\n"; + for (i=list.begin(); i!=list.end(); i++) { + delete *i; + } + getStreamer() << "~EmployeeList empty." << "\n"; + } +}; + diff --git a/Examples/python/swigrun/example.i b/Examples/android/extend/jni/example.i similarity index 70% rename from Examples/python/swigrun/example.i rename to Examples/android/extend/jni/example.i index c8ec32e09..e550aac2c 100644 --- a/Examples/python/swigrun/example.i +++ b/Examples/android/extend/jni/example.i @@ -11,5 +11,8 @@ %feature("director") Employee; %feature("director") Manager; +/* A base class for callbacks from C++ to output text on the Java side */ +%feature("director") Streamer; + %include "example.h" diff --git a/Examples/android/extend/local.properties b/Examples/android/extend/local.properties new file mode 100644 index 000000000..14b8d63b4 --- /dev/null +++ b/Examples/android/extend/local.properties @@ -0,0 +1,10 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must *NOT* be checked in Version Control Systems, +# as it contains information specific to your local configuration. + +# location of the SDK. This is only used by Ant +# For customization when using a Version Control System, please read the +# header note. +sdk.dir=/home/william/android/android-sdk-linux_x86 diff --git a/Examples/android/extend/proguard.cfg b/Examples/android/extend/proguard.cfg new file mode 100644 index 000000000..b1cdf17b5 --- /dev/null +++ b/Examples/android/extend/proguard.cfg @@ -0,0 +1,40 @@ +-optimizationpasses 5 +-dontusemixedcaseclassnames +-dontskipnonpubliclibraryclasses +-dontpreverify +-verbose +-optimizations !code/simplification/arithmetic,!field/*,!class/merging/* + +-keep public class * extends android.app.Activity +-keep public class * extends android.app.Application +-keep public class * extends android.app.Service +-keep public class * extends android.content.BroadcastReceiver +-keep public class * extends android.content.ContentProvider +-keep public class * extends android.app.backup.BackupAgentHelper +-keep public class * extends android.preference.Preference +-keep public class com.android.vending.licensing.ILicensingService + +-keepclasseswithmembernames class * { + native ; +} + +-keepclasseswithmembers class * { + public (android.content.Context, android.util.AttributeSet); +} + +-keepclasseswithmembers class * { + public (android.content.Context, android.util.AttributeSet, int); +} + +-keepclassmembers class * extends android.app.Activity { + public void *(android.view.View); +} + +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +-keep class * implements android.os.Parcelable { + public static final android.os.Parcelable$Creator *; +} diff --git a/Examples/android/extend/project.properties b/Examples/android/extend/project.properties new file mode 100644 index 000000000..ea89160e0 --- /dev/null +++ b/Examples/android/extend/project.properties @@ -0,0 +1,11 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "ant.properties", and override values to adapt the script to your +# project structure. + +# Project target. +target=android-8 diff --git a/Examples/android/extend/res/layout/main.xml b/Examples/android/extend/res/layout/main.xml new file mode 100644 index 000000000..d4e5d7fe8 --- /dev/null +++ b/Examples/android/extend/res/layout/main.xml @@ -0,0 +1,25 @@ + + +

    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 b0aa9c970..ba172611d 100644 --- a/Examples/go/multimap/Makefile +++ b/Examples/go/multimap/Makefile @@ -1,18 +1,18 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = multimap.c TARGET = example INTERFACE = example.i SWIGOPT = -all:: go +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run -go:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go -clean:: - $(MAKE) -f $(TOP)/Makefile go_clean - -check: all - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/multimap/example.i b/Examples/go/multimap/example.i index 8de6b0dc3..30a37d3bf 100644 --- a/Examples/go/multimap/example.i +++ b/Examples/go/multimap/example.i @@ -74,16 +74,21 @@ extern int count(char *bytes, int len, char c); %} /* Return the mutated string as a modified element in the array. */ -%typemap(argout) (char *str, int len) +%typemap(argout,fragment="AllocateString") (char *str, int len) %{ { _gostring_ *a; a = (_gostring_*) $input.array; - a[0] = _swig_makegostring($1, $2); + a[0] = Swig_AllocateString($1, $2); } %} +%typemap(goargout,fragment="CopyString") (char *str, int len) +%{ + $input[0] = swigCopyString($input[0]) +%} + %typemap(freearg) (char *str, int len) %{ free($1); diff --git a/Examples/go/multimap/example.c b/Examples/go/multimap/multimap.c similarity index 100% rename from Examples/go/multimap/example.c rename to Examples/go/multimap/multimap.c diff --git a/Examples/go/multimap/runme.go b/Examples/go/multimap/runme.go index 94c29127c..390205a80 100644 --- a/Examples/go/multimap/runme.go +++ b/Examples/go/multimap/runme.go @@ -1,8 +1,8 @@ package main import ( - "fmt" . "./example" + "fmt" ) func main() { diff --git a/Examples/go/pointer/Makefile b/Examples/go/pointer/Makefile index b0aa9c970..20587fd95 100644 --- a/Examples/go/pointer/Makefile +++ b/Examples/go/pointer/Makefile @@ -1,18 +1,18 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = pointer.c TARGET = example INTERFACE = example.i SWIGOPT = -all:: go +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run -go:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go -clean:: - $(MAKE) -f $(TOP)/Makefile go_clean - -check: all - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/pointer/example.c b/Examples/go/pointer/pointer.c similarity index 100% rename from Examples/go/pointer/example.c rename to Examples/go/pointer/pointer.c diff --git a/Examples/go/pointer/runme.go b/Examples/go/pointer/runme.go index 63deb11b7..1414d341e 100644 --- a/Examples/go/pointer/runme.go +++ b/Examples/go/pointer/runme.go @@ -1,8 +1,8 @@ package main import ( - "fmt" . "./example" + "fmt" ) func main() { diff --git a/Examples/go/reference/Makefile b/Examples/go/reference/Makefile index 9dc8b8851..d203fff6d 100644 --- a/Examples/go/reference/Makefile +++ b/Examples/go/reference/Makefile @@ -1,18 +1,18 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = reference.cxx TARGET = example INTERFACE = example.i SWIGOPT = -all:: go +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run -go:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(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:: - $(MAKE) -f $(TOP)/Makefile go_clean - -check: all - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/reference/example.h b/Examples/go/reference/example.h index 4915adb1b..bcfcfb72f 100644 --- a/Examples/go/reference/example.h +++ b/Examples/go/reference/example.h @@ -4,8 +4,8 @@ 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) { }; + 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 *print(); }; @@ -20,7 +20,3 @@ public: Vector &operator[](int); int size(); }; - - - - diff --git a/Examples/go/reference/example.i b/Examples/go/reference/example.i index 1cf19c82c..173143d79 100644 --- a/Examples/go/reference/example.i +++ b/Examples/go/reference/example.i @@ -29,7 +29,7 @@ public: VectorArray(int maxsize); ~VectorArray(); int size(); - + /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { diff --git a/Examples/go/reference/reference.cxx b/Examples/go/reference/reference.cxx new file mode 100644 index 000000000..9dbaed2ee --- /dev/null +++ b/Examples/go/reference/reference.cxx @@ -0,0 +1,46 @@ +/* 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::print() { + 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; +} + +VectorArray::~VectorArray() { + delete [] items; +} + +Vector &VectorArray::operator[](int index) { + if ((index < 0) || (index >= maxsize)) { + printf("Panic! Array index out of bounds.\n"); + exit(1); + } + return items[index]; +} + +int VectorArray::size() { + return maxsize; +} + diff --git a/Examples/go/reference/runme.go b/Examples/go/reference/runme.go index 3683d6144..004a04c2e 100644 --- a/Examples/go/reference/runme.go +++ b/Examples/go/reference/runme.go @@ -3,8 +3,8 @@ package main import ( - "fmt" . "./example" + "fmt" ) func main() { diff --git a/Examples/go/simple/Makefile b/Examples/go/simple/Makefile index e67fa8bb6..89b936f3d 100644 --- a/Examples/go/simple/Makefile +++ b/Examples/go/simple/Makefile @@ -1,15 +1,17 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = simple.c TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go -clean:: - $(MAKE) -f $(TOP)/Makefile go_clean - -check: all - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/simple/runme.go b/Examples/go/simple/runme.go index c829ad21a..9eb0ff454 100644 --- a/Examples/go/simple/runme.go +++ b/Examples/go/simple/runme.go @@ -1,8 +1,8 @@ package main import ( - "fmt" "./example" + "fmt" ) func main() { diff --git a/Examples/go/simple/example.c b/Examples/go/simple/simple.c similarity index 100% rename from Examples/go/simple/example.c rename to Examples/go/simple/simple.c diff --git a/Examples/go/template/Makefile b/Examples/go/template/Makefile index b9278b53e..f79b083cb 100644 --- a/Examples/go/template/Makefile +++ b/Examples/go/template/Makefile @@ -1,18 +1,18 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i SWIGOPT = -all:: go +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run -go:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(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:: - $(MAKE) -f $(TOP)/Makefile go_clean - -check: all - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/template/index.html b/Examples/go/template/index.html index a14e3b29a..cf2b1337b 100644 --- a/Examples/go/template/index.html +++ b/Examples/go/template/index.html @@ -17,7 +17,7 @@ SWIG.

    The C++ Code

    -Lets take a templated function and a templated class as follows: +Let's take a templated function and a templated class as follows:
    diff --git a/Examples/go/template/runme.go b/Examples/go/template/runme.go
    index 8b3d4000e..fca2f1b75 100644
    --- a/Examples/go/template/runme.go
    +++ b/Examples/go/template/runme.go
    @@ -3,8 +3,8 @@
     package main
     
     import (
    -	"fmt"
     	. "./example"
    +	"fmt"
     )
     
     func main() {
    diff --git a/Examples/go/variables/Makefile b/Examples/go/variables/Makefile
    index b0aa9c970..cef1186af 100644
    --- a/Examples/go/variables/Makefile
    +++ b/Examples/go/variables/Makefile
    @@ -1,18 +1,18 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       = variables.c
     TARGET     = example
     INTERFACE  = example.i
     SWIGOPT    =
     
    -all::	go
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run
     
    -go::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile go_clean
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean
    diff --git a/Examples/go/variables/runme.go b/Examples/go/variables/runme.go
    index 26cad4b3c..3d9737f5c 100644
    --- a/Examples/go/variables/runme.go
    +++ b/Examples/go/variables/runme.go
    @@ -3,8 +3,8 @@
     package main
     
     import (
    -	"fmt"
     	"./example"
    +	"fmt"
     )
     
     func main() {
    diff --git a/Examples/go/variables/example.c b/Examples/go/variables/variables.c
    similarity index 97%
    rename from Examples/go/variables/example.c
    rename to Examples/go/variables/variables.c
    index aa4ffe9b3..05e17c8c5 100644
    --- a/Examples/go/variables/example.c
    +++ b/Examples/go/variables/variables.c
    @@ -51,7 +51,7 @@ void print_vars() {
       printf("dvar      = %g\n", dvar);
       printf("cvar      = %c\n", cvar);
       printf("strvar    = %s\n", strvar ? strvar : "(null)");
    -  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
    +  printf("cstrvar   = %s\n", cstrvar);
       printf("iptrvar   = %p\n", iptrvar);
       printf("name      = %s\n", name);
       printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
    diff --git a/Examples/guile/Makefile.in b/Examples/guile/Makefile.in
    deleted file mode 100644
    index a11095599..000000000
    --- a/Examples/guile/Makefile.in
    +++ /dev/null
    @@ -1,40 +0,0 @@
    -# Makefile for Guile.  Used by all of the example programs.
    -
    -subdirs		= simple matrix port constants multimap multivalue
    -
    -top_srcdir	= @top_srcdir@
    -SWIG		= ../$(top_srcdir)/preinst-swig
    -CC		= @CC@
    -CXX		= @CXX@
    -CFLAGS		= @PLATFLAGS@
    -GUILEINCLUDE	= @GUILEINCLUDE@
    -GUILELINK	= @GUILELINK@
    -SWIGOPT		=
    -
    -WRAP		= $(IFILE:.i=_wrap.c)
    -CXXWRAP		= $(IFILE:.i=_wrap.cxx)
    -
    -SO		= @SO@
    -
    -all:
    -	for d in $(subdirs) ; do (cd $$d ; $(MAKE)) ; done
    -
    -clean::
    -	for d in $(subdirs) ; do (cd $$d ; $(MAKE) clean) ; done
    -	rm -f *~ .~*
    -
    -guile_clean:
    -	rm -f *.@OBJEXT@ *$(SO) *_wrap* *~ .~* core my-guile $(TARGET)
    -
    -# This is meant to be used w/ "make -f ../Makefile" from subdirs.
    -# Doesn't make sense to use it from here.
    -
    -sub-all::
    -	$(SWIG) -guile $(SWIGOPT) $(IFILE)
    -	$(CC) $(CFLAGS) -o $(TARGET) $(SRCS) $(WRAP) $(GUILEINCLUDE) $(GUILELINK)
    -
    -sub-all-cxx::
    -	$(SWIG) -c++ -guile $(SWIGOPT) $(IFILE)
    -	$(CXX) $(CFLAGS) -o $(TARGET) $(SRCS) $(CXXWRAP) $(GUILEINCLUDE) $(GUILELINK)
    -
    -# Makefile ends here
    diff --git a/Examples/guile/README b/Examples/guile/README
    index 7d726619e..03ce8e450 100644
    --- a/Examples/guile/README
    +++ b/Examples/guile/README
    @@ -1,6 +1,7 @@
     This directory contains examples for Guile.
     
     constants   -- handling #define and %constant literals
    +class       -- classic c++ class example
     matrix      -- a very simple Matrix example
     multimap    -- typemaps with multiple sub-types
     multivalue  -- using the %values_as_list directive
    diff --git a/Examples/guile/check.list b/Examples/guile/check.list
    index 7ccd0730a..726e6ab75 100644
    --- a/Examples/guile/check.list
    +++ b/Examples/guile/check.list
    @@ -1,6 +1,9 @@
     # see top-level Makefile.in
     constants
    -simple
    +class
     port
    +simple
    +std_vector
    +matrix
     multimap
     multivalue
    diff --git a/Examples/guile/class/Makefile b/Examples/guile/class/Makefile
    new file mode 100644
    index 000000000..84a7b4322
    --- /dev/null
    +++ b/Examples/guile/class/Makefile
    @@ -0,0 +1,22 @@
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    = example.cxx
    +TARGET     = example
    +INTERFACE  = example.i
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run
    +
    +build:
    +	$(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static_cpp
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/go/class/example.cxx b/Examples/guile/class/example.cxx
    similarity index 66%
    rename from Examples/go/class/example.cxx
    rename to Examples/guile/class/example.cxx
    index 1e8e203dd..046304519 100644
    --- a/Examples/go/class/example.cxx
    +++ b/Examples/guile/class/example.cxx
    @@ -1,4 +1,4 @@
    -/* File : example.c */
    +/* File : example.cxx */
     
     #include "example.h"
     #define M_PI 3.14159265358979323846
    @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) {
     
     int Shape::nshapes = 0;
     
    -double Circle::area(void) {
    +double Circle::area() {
       return M_PI*radius*radius;
     }
     
    -double Circle::perimeter(void) {
    +double Circle::perimeter() {
       return 2*M_PI*radius;
     }
     
    -double Square::area(void) {
    +double Square::area() {
       return width*width;
     }
     
    -double Square::perimeter(void) {
    +double Square::perimeter() {
       return 4*width;
     }
    diff --git a/Examples/guile/class/example.h b/Examples/guile/class/example.h
    new file mode 100644
    index 000000000..0dff185b2
    --- /dev/null
    +++ b/Examples/guile/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/guile/class/example.i b/Examples/guile/class/example.i
    new file mode 100644
    index 000000000..fbdf7249f
    --- /dev/null
    +++ b/Examples/guile/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/guile/class/runme.scm b/Examples/guile/class/runme.scm
    new file mode 100644
    index 000000000..4e47d458d
    --- /dev/null
    +++ b/Examples/guile/class/runme.scm
    @@ -0,0 +1,60 @@
    +; file: runme.scm
    +
    +; This file illustrates the proxy class C++ interface generated
    +; by SWIG.
    +
    +(load-extension "./libexample" "scm_init_example_module")
    +
    +; Convenience wrapper around the display function
    +; (which only accepts one argument at the time)
    +
    +(define (mdisplay-newline . args)
    +  (for-each display args)
    +  (newline))
    +
    +; ----- Object creation -----
    +
    +(mdisplay-newline "Creating some objects:")
    +(define c (new-Circle 10))
    +(mdisplay-newline "    Created circle " c)
    +(define s (new-Square 10))
    +(mdisplay-newline "    Created square " s)
    +
    +; ----- Access a static member -----
    +
    +(mdisplay-newline "\nA total of " (Shape-nshapes) " shapes were created")
    +
    +; ----- Member data access -----
    +
    +; Set the location of the object
    +
    +(Shape-x-set c 20)
    +(Shape-y-set c 30)
    +
    +(Shape-x-set s -10)
    +(Shape-y-set s 5)
    +
    +(mdisplay-newline "\nHere is their current position:")
    +(mdisplay-newline "    Circle = (" (Shape-x-get c) "," (Shape-y-get c) ")")
    +(mdisplay-newline "    Square = (" (Shape-x-get s) "," (Shape-y-get s) ")")
    +
    +; ----- Call some methods -----
    +
    +(mdisplay-newline "\nHere are some properties of the shapes:")
    +(define (shape-props o)
    +  (mdisplay-newline "   " o)
    +  (mdisplay-newline "   area      = " (Shape-area o))
    +  (mdisplay-newline "   perimeter = " (Shape-perimeter o)))
    +(for-each  shape-props (list c s))
    +
    +(mdisplay-newline "\nGuess I'll clean up now")
    +
    +; Note: this invokes the virtual destructor
    +(delete-Shape c)
    +(delete-Shape s)
    +
    +(define s 3)
    +(mdisplay-newline (Shape-nshapes) " shapes remain")
    +(mdisplay-newline "Goodbye")
    +
    +(exit 0)
    diff --git a/Examples/guile/constants/Makefile b/Examples/guile/constants/Makefile
    index 70243c75e..abe63d4b1 100644
    --- a/Examples/guile/constants/Makefile
    +++ b/Examples/guile/constants/Makefile
    @@ -1,17 +1,17 @@
    -SRCS   = 
    -TARGET = my-guile
    -IFILE  = example.i
    -MKDIR  = ..
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
    +TARGET     = my-guile
    +INTERFACE  = example.i
     
    -all::
    -	$(MAKE) -f $(MKDIR)/Makefile		\
    -		SRCS='$(SRCS)'			\
    -		TARGET=$(TARGET)		\
    -		IFILE=$(IFILE)			\
    -	    sub-all
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_run
     
    -clean::
    -	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented
     
    -check: all
    -	./my-guile -s constants.scm
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/guile/constants/constants.scm b/Examples/guile/constants/constants.scm
    deleted file mode 100644
    index 5220150f1..000000000
    --- a/Examples/guile/constants/constants.scm
    +++ /dev/null
    @@ -1,10 +0,0 @@
    -(or (= (ICONST) 42) (exit 1))
    -(or (< (abs (- (FCONST) 2.1828)) 0.00001) (exit 1))
    -(or (char=? (CCONST) #\x) (exit 1))
    -(or (char=? (CCONST2) #\newline) (exit 1))
    -(or (string=? (SCONST) "Hello World") (exit 1))
    -(or (string=? (SCONST2) "\"Hello World\"") (exit 1))
    -(or (< (abs (- (EXPR) (+ (ICONST) (* 3 (FCONST))))) 0.00001) (exit 1))
    -(or (= (iconst) 37) (exit 1))
    -(or (< (abs (- (fconst) 3.14)) 0.00001) (exit 1))
    -(exit 0)
    diff --git a/Examples/guile/constants/runme.scm b/Examples/guile/constants/runme.scm
    new file mode 100644
    index 000000000..59fd26e5a
    --- /dev/null
    +++ b/Examples/guile/constants/runme.scm
    @@ -0,0 +1,19 @@
    +(or (= (ICONST) 42) (exit 1))
    +(display "ICONST  = ")(display (ICONST))(display " (should be 42)\n")
    +(or (< (abs (- (FCONST) 2.1828)) 0.00001) (exit 1))
    +(display "FCONST  = ")(display (FCONST))(display " (should be 2.1828)\n")
    +(or (char=? (CCONST) #\x) (exit 1))
    +(display "CCONST  = ")(display (CCONST))(display " (should be 'x')\n")
    +(or (char=? (CCONST2) #\newline) (exit 1))
    +(display "CCONST2 = ")(display (CCONST2))(display " (this should be on a new line)\n")
    +(or (string=? (SCONST) "Hello World") (exit 1))
    +(display "SCONST  = ")(display (SCONST))(display " (should be 'Hello World')\n")
    +(or (string=? (SCONST2) "\"Hello World\"") (exit 1))
    +(display "SCONST2 = ")(display (SCONST2))(display " (should be \"Hello World\")\n")
    +(or (< (abs (- (EXPR) (+ (ICONST) (* 3 (FCONST))))) 0.00001) (exit 1))
    +(display "EXPR    = ")(display (abs (- (EXPR) (+ (ICONST) (* 3 (FCONST))))))(display " (should round to 0.0)\n")
    +(or (= (iconst) 37) (exit 1))
    +(display "iconst  = ")(display (iconst))(display " (should be 37)\n")
    +(or (< (abs (- (fconst) 3.14)) 0.00001) (exit 1))
    +(display "fconst  = ")(display (fconst))(display " (should be 3.14)\n")
    +(exit 0)
    diff --git a/Examples/guile/matrix/Makefile b/Examples/guile/matrix/Makefile
    index 5df2c6515..cfe0c8536 100644
    --- a/Examples/guile/matrix/Makefile
    +++ b/Examples/guile/matrix/Makefile
    @@ -1,18 +1,17 @@
    -SRCS   = matrix.c vector.c
    -TARGET = matrix
    -IFILE  = package.i
    -MKDIR  = ..
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       = matrix.c vector.c
    +TARGET     = my-guile
    +INTERFACE  = example.i
     
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' GUILE_RUNOPTIONS='-e do-test' guile_augmented_run
     
    -all::
    -	$(MAKE) -f $(MKDIR)/Makefile		\
    -		SRCS='$(SRCS)'			\
    -		TARGET=$(TARGET)		\
    -		IFILE=$(IFILE)			\
    -		MODULE=$(MODULE)		\
    -	  sub-all
    +build:
    +	$(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::
    -	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/guile/matrix/README b/Examples/guile/matrix/README
    index dc1957719..496e81bf1 100644
    --- a/Examples/guile/matrix/README
    +++ b/Examples/guile/matrix/README
    @@ -1,13 +1,13 @@
     Matrix example.  To run the example, execute the program 'matrix' and
     type the following :
     
    -	(load "matrix.scm")
    +	(load "runme.scm")
     	(do-test 0)
     
     Alternatively, use the command-line:
     
    -	./matrix -e do-test -s matrix.scm
    +	./my-guile -e do-test -s runme.scm
     
     Or, if your operating system is spiffy enough:
     
    -	./matrix.scm
    +	./runme.scm
    diff --git a/Examples/guile/matrix/package.i b/Examples/guile/matrix/example.i
    similarity index 72%
    rename from Examples/guile/matrix/package.i
    rename to Examples/guile/matrix/example.i
    index aaa55511c..3f801dcdf 100644
    --- a/Examples/guile/matrix/package.i
    +++ b/Examples/guile/matrix/example.i
    @@ -1,7 +1,4 @@
    -// FILE : package.i
    -// See the SWIG users manual
    -
    -/*** Matrix and vector package ***/
    +/*** Matrix and vector example ***/
     
     %module Matrix
     %{
    diff --git a/Examples/guile/matrix/main.c b/Examples/guile/matrix/main.c
    deleted file mode 100644
    index 88209aea7..000000000
    --- a/Examples/guile/matrix/main.c
    +++ /dev/null
    @@ -1,24 +0,0 @@
    -#include 
    -extern int matrix_init(Tcl_Interp *);    /* Init function from matrix.i */
    -
    -int main() {
    -
    -  int        code;
    -  char       input[1024];
    -  Tcl_Interp *interp;
    -  
    -  interp = Tcl_CreateInterp();
    -
    -  /* Initialize the wrappers */
    -
    -  if (matrix_init(interp) == TCL_ERROR)
    -    exit(0);
    -  
    -  fprintf(stdout,"matrix > ");
    -  while(fgets(input, 1024, stdin) != NULL) {
    -    code = Tcl_Eval(interp, input);
    -    fprintf(stdout,"%s\n",interp->result);
    -    fprintf(stdout,"matrix > ");
    -  }
    -}
    -
    diff --git a/Examples/guile/matrix/matrix.scm b/Examples/guile/matrix/runme.scm
    similarity index 92%
    rename from Examples/guile/matrix/matrix.scm
    rename to Examples/guile/matrix/runme.scm
    index 18e52842d..f11061e56 100644
    --- a/Examples/guile/matrix/matrix.scm
    +++ b/Examples/guile/matrix/runme.scm
    @@ -138,24 +138,28 @@
                   (set-m m1 i j (+ (get-m m1 i j) (get-m m2 i j)))
                   (add-two m1 m2 i (+ j 1)))
     	    (add-two m1 m2 (+ i 1) 0))))
    -  (if (null? ML) () (begin
    -		      (add-two M (car ML) 0 0)
    -		      (add-mat M (cdr ML)))))
    +  (if (null? ML) *unspecified*
    +		 (begin
    +		   (add-two M (car ML) 0 0)
    +		   (add-mat M (cdr ML)))))
     
     (define (cleanup ML)
    -  (if (null? ML) () (begin
    -		      (destroy-matrix (car ML))
    -		      (cleanup (cdr ML)))))
    +  (if (null? ML) *unspecified*
    +		 (begin
    +		   (destroy-matrix (car ML))
    +		   (cleanup (cdr ML)))))
     
     (define (make-random ML)		; Put random values in them
    -  (if (null? ML) () (begin
    -		      (randmat (car ML))
    -		      (make-random (cdr ML)))))
    +  (if (null? ML) *unspecified*
    +		 (begin
    +		   (randmat (car ML))
    +		   (make-random (cdr ML)))))
     
     (define (mul-mat m ML)
    -  (if (null? ML) () (begin
    -		      (mat-mult m (car ML) m)
    -		      (mul-mat m (cdr ML)))))
    +  (if (null? ML) *unspecified*
    +		 (begin
    +		   (mat-mult m (car ML) m)
    +		   (mul-mat m (cdr ML)))))
     
     ;;; Now we'll hammer on things a little bit just to make
     ;;; sure everything works.
    @@ -207,4 +211,3 @@
     
       (cleanup M-list))
     
    -;;; matrix.scm ends here
    diff --git a/Examples/guile/multimap/Makefile b/Examples/guile/multimap/Makefile
    index dc9c66d1f..f87670219 100644
    --- a/Examples/guile/multimap/Makefile
    +++ b/Examples/guile/multimap/Makefile
    @@ -1,18 +1,22 @@
     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
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/guile/multimap/example.i b/Examples/guile/multimap/example.i
    index 7337d1e9e..c24d45ddc 100644
    --- a/Examples/guile/multimap/example.i
    +++ b/Examples/guile/multimap/example.i
    @@ -15,43 +15,54 @@ extern int squareCubed (int n, int *OUTPUT);
     
     extern int    gcd(int x, int y);
     
    -%typemap(in) (int argc, char *argv[]) {
    -  int i;
    -  SCM *v;
    -  if (!(SCM_NIMP($input) && SCM_VECTORP($input))) {
    +%typemap(in) (int argc, char *argv[]) %{
    +  scm_t_array_handle handle;
    +  size_t i;
    +  size_t lenp;
    +  ssize_t inc;
    +  const SCM *v;
    +  if (!(SCM_NIMP($input) && scm_is_vector($input))) {
         SWIG_exception(SWIG_ValueError, "Expecting a vector");
         return 0;
       }
    -  $1 = SCM_LENGTH($input);
    +  v = scm_vector_elements($input, &handle, &lenp, &inc);
    +  $1 = (int)lenp;
       if ($1 == 0) {
         SWIG_exception(SWIG_ValueError, "Vector must contain at least 1 element");
       }
       $2 = (char **) malloc(($1+1)*sizeof(char *));
    -  v = SCM_VELTS($input);
    -  for (i = 0; i < $1; i++) {
    -    if (!(SCM_NIMP(v[i]) && SCM_STRINGP(v[i]))) {
    -      free($2);	
    +  for (i = 0; i < $1; i++, v +=inc ) {
    +    if (!(SCM_NIMP(*v) && scm_is_string(*v))) {
    +      free($2);
           SWIG_exception(SWIG_ValueError, "Vector items must be strings");
           return 0;
         }
    -    $2[i] = SCM_CHARS(v[i]);
    +    $2[i] = scm_to_locale_string(*v);
       }
       $2[i] = 0;
    -}
    +  scm_array_handle_release (&handle);
    +%}
     
    -%typemap(freearg) (int argc, char *argv[]) {
    -   free($2);
    -}
    +%typemap(freearg) (int argc, char *argv[]) %{
    +  for (i = 0; i < $1; i++) {
    +    free($2[i]);
    +  }
    +  free($2);
    +%}
     
     extern int gcdmain(int argc, char *argv[]);
     
    -%typemap(in) (char *bytes, int len) {
    -  if (!(SCM_NIMP($input) && SCM_STRINGP($input))) {
    +%typemap(in) (char *bytes, int len) %{
    +  if (!(SCM_NIMP($input) && scm_is_string($input))) {
         SWIG_exception(SWIG_ValueError, "Expecting a string");
       }
    -  $1 = SCM_CHARS($input);
    -  $2 = SCM_LENGTH($input);
    -}
    +  $1 = scm_to_locale_string($input);
    +  $2 = scm_c_string_length($input);
    +%}
    +
    +%typemap(freearg) (char *bytes, int len) %{
    +  free($1);
    +%}
     
     extern int count(char *bytes, int len, char c);
     
    @@ -59,15 +70,15 @@ extern int count(char *bytes, int len, char c);
     
     %typemap(in) (char *str, int len) {
       size_t temp;
    -  $1 = gh_scm2newstr($input,&temp);
    +  $1 = SWIG_Guile_scm2newstr($input,&temp);
       $2 = temp;
     }
     
     /* Return the mutated string as a new object.  */
     
     %typemap(argout) (char *str, int len) {
    -  SWIG_APPEND_VALUE(gh_str2scm($1,$2));
    -  if ($1) scm_must_free($1);
    +  SWIG_APPEND_VALUE(scm_from_locale_stringn($1,$2));
    +  if ($1) SWIG_free($1);
     }   
     
     extern void capitalize(char *str, int len);
    @@ -78,7 +89,7 @@ extern void capitalize(char *str, int len);
     %typemap(check) (double cx, double cy) {
        double a = $1*$1 + $2*$2;
        if (a > 1.0) {
    -	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
    +     SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
        }
     }
     
    diff --git a/Examples/guile/multimap/runme.scm b/Examples/guile/multimap/runme.scm
    index edc197259..a4a518a02 100644
    --- a/Examples/guile/multimap/runme.scm
    +++ b/Examples/guile/multimap/runme.scm
    @@ -1,6 +1,6 @@
     ;;; Test out some multi-argument typemaps
     
    -(use-modules (example))
    +(load-extension "./libexample" "scm_init_example_module")
     
     ; Call the GCD function
     
    @@ -27,4 +27,4 @@
     (display (capitalize "hello world"))
     (newline)
     
    -
    +(exit 0)
    diff --git a/Examples/guile/multivalue/Makefile b/Examples/guile/multivalue/Makefile
    index dc9c66d1f..f87670219 100644
    --- a/Examples/guile/multivalue/Makefile
    +++ b/Examples/guile/multivalue/Makefile
    @@ -1,18 +1,22 @@
     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
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/guile/multivalue/runme.scm b/Examples/guile/multivalue/runme.scm
    index 73eb5affa..0f65797ca 100644
    --- a/Examples/guile/multivalue/runme.scm
    +++ b/Examples/guile/multivalue/runme.scm
    @@ -1,6 +1,6 @@
     ;;;; Show the three different ways to deal with multiple return values
     
    -(use-modules (example))
    +(load-extension "./libexample" "scm_init_example_module")
     
     ;;; Multiple values as lists. By default, if more than one value is to
     ;;; be returned, a list of the values is created and returned.  The
    @@ -64,3 +64,4 @@
       (display remainder)
       (newline))
     
    +(exit 0)
    diff --git a/Examples/guile/port/Makefile b/Examples/guile/port/Makefile
    index 824f3f823..09ee821f5 100644
    --- a/Examples/guile/port/Makefile
    +++ b/Examples/guile/port/Makefile
    @@ -1,18 +1,18 @@
    -SRCS   = port.c
    -TARGET = port
    -IFILE  = port.i
    -MKDIR  = ..
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       = example.c
    +TARGET     = my-guile
    +INTERFACE  = example.i
     
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_run
     
    -all::
    -	$(MAKE) -f $(MKDIR)/Makefile		\
    -		SRCS='$(SRCS)'			\
    -		TARGET=$(TARGET)		\
    -		IFILE=$(IFILE)			\
    -		MODULE=$(MODULE)		\
    -	  sub-all
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented
     
    -clean::
    -	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    +	rm -f test.out
    diff --git a/Examples/guile/port/README b/Examples/guile/port/README
    index 5ed0199e2..174d8767a 100644
    --- a/Examples/guile/port/README
    +++ b/Examples/guile/port/README
    @@ -1,2 +1,2 @@
     This example illustrates the translation from Scheme file ports to
    -temporary FILE streams. Read the source and run ./port -s port.scm
    +temporary FILE streams. Read the source and run ./my-guile -s runme.scm
    diff --git a/Examples/guile/port/port.c b/Examples/guile/port/example.c
    similarity index 100%
    rename from Examples/guile/port/port.c
    rename to Examples/guile/port/example.c
    diff --git a/Examples/guile/port/port.i b/Examples/guile/port/example.i
    similarity index 100%
    rename from Examples/guile/port/port.i
    rename to Examples/guile/port/example.i
    diff --git a/Examples/guile/port/port.scm b/Examples/guile/port/runme.scm
    similarity index 79%
    rename from Examples/guile/port/port.scm
    rename to Examples/guile/port/runme.scm
    index 68e9b8e85..3ff447eff 100644
    --- a/Examples/guile/port/port.scm
    +++ b/Examples/guile/port/runme.scm
    @@ -21,12 +21,15 @@
     	   (lambda ()
     	     (print-int (current-output-port) 314159))))
            (lambda args
    +	 (display "Below shows that attempting to write to a string or soft port will result in a wrong-type-error...")
    +	 (newline)
     	 (write args) (newline)))
     
     ;; Read from a file port. Note that it is a bad idea to mix Scheme and
    -;; C input because of buffering.
    +;; C input because of buffering, hence the call to seek to rewind the file.
     (with-input-from-file "test.out"
       (lambda ()
    +    (seek (current-input-port) 0 SEEK_SET)
         (display (read-int (current-input-port)))
         (newline)))
     
    diff --git a/Examples/guile/simple/Makefile b/Examples/guile/simple/Makefile
    index 702b5bb96..d8fb2da81 100644
    --- a/Examples/guile/simple/Makefile
    +++ b/Examples/guile/simple/Makefile
    @@ -1,19 +1,17 @@
    -SRCS   = example.c
    -TARGET = my-guile
    -IFILE  = example.i
    -MKDIR  = ..
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       = example.c
    +TARGET     = my-guile
    +INTERFACE  = example.i
     
    -all: $(TARGET)
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_run
     
    -$(TARGET):
    -	$(MAKE) -f $(MKDIR)/Makefile		\
    -		SRCS='$(SRCS)'			\
    -		TARGET=$(TARGET)		\
    -		IFILE=$(IFILE)			\
    -	    sub-all
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented
     
    -clean::
    -	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
    -
    -check: $(TARGET)
    -	./$(TARGET) -s example.scm > /dev/null
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/guile/simple/README b/Examples/guile/simple/README
    index 982216eaa..27b54dc5b 100644
    --- a/Examples/guile/simple/README
    +++ b/Examples/guile/simple/README
    @@ -2,8 +2,8 @@ A very simple example.
     
     To run it, start the program 'my-guile' and type:
     
    -	(load "example.scm")
    +	(load "runme.scm")
     
     Alternatively, you can use the shell command:
     
    -	./my-guile -s example.scm
    +	./my-guile -s runme.scm
    diff --git a/Examples/guile/simple/example.scm b/Examples/guile/simple/runme.scm
    similarity index 93%
    rename from Examples/guile/simple/example.scm
    rename to Examples/guile/simple/runme.scm
    index 9408b1aa6..c3fd0b41f 100644
    --- a/Examples/guile/simple/example.scm
    +++ b/Examples/guile/simple/runme.scm
    @@ -1,4 +1,3 @@
    -;;; example.scm
     
     (define (mdisplay-newline . args)       ; does guile-1.3.4 have `format #t'?
       (for-each display args)
    @@ -25,4 +24,3 @@
     (exit (and (= 1932053504 (fact 13))
                (= 745470.0 (My-variable))))
     
    -;;; example.scm ends here
    diff --git a/Examples/guile/std_vector/Makefile b/Examples/guile/std_vector/Makefile
    index 2733fb017..1146242c2 100644
    --- a/Examples/guile/std_vector/Makefile
    +++ b/Examples/guile/std_vector/Makefile
    @@ -1,18 +1,22 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    =
     TARGET     = example
     INTERFACE  = example.i
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(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::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean
    diff --git a/Examples/guile/std_vector/runme.scm b/Examples/guile/std_vector/runme.scm
    index 77443a156..64f56a147 100644
    --- a/Examples/guile/std_vector/runme.scm
    +++ b/Examples/guile/std_vector/runme.scm
    @@ -1,6 +1,5 @@
    -;; run with mzscheme -r example.scm
     
    -(use-modules (example))
    +(load-extension "./libexample" "scm_init_example_module")
     
     ; repeatedly invoke a procedure with v and an index as arguments
     (define (with-vector v proc size-proc)
    @@ -52,3 +51,4 @@
     (print-DoubleVector v)
     (delete-DoubleVector v)
     
    +(exit 0)
    diff --git a/Examples/java/callback/Makefile b/Examples/java/callback/Makefile
    index 14c301703..c76e09262 100644
    --- a/Examples/java/callback/Makefile
    +++ b/Examples/java/callback/Makefile
    @@ -1,18 +1,20 @@
     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
     SWIGOPT    =
    +JAVASRCS   = *.java
     
    -all::	java
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run
     
    -java::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
    -	javac *.java
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile java_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean
    diff --git a/Examples/java/callback/example.i b/Examples/java/callback/example.i
    index 90beda01a..cf61ef9d2 100644
    --- a/Examples/java/callback/example.i
    +++ b/Examples/java/callback/example.i
    @@ -4,8 +4,6 @@
     #include "example.h"
     %}
     
    -%include "std_string.i"
    -
     /* turn on director wrapping Callback */
     %feature("director") Callback;
     
    diff --git a/Examples/java/check.list b/Examples/java/check.list
    index 9728342f2..825d04a6d 100644
    --- a/Examples/java/check.list
    +++ b/Examples/java/check.list
    @@ -7,6 +7,7 @@ extend
     funcptr
     multimap
     native
    +nested
     pointer
     reference
     simple
    diff --git a/Examples/java/class/Makefile b/Examples/java/class/Makefile
    index 14c301703..c76e09262 100644
    --- a/Examples/java/class/Makefile
    +++ b/Examples/java/class/Makefile
    @@ -1,18 +1,20 @@
     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
     SWIGOPT    =
    +JAVASRCS   = *.java
     
    -all::	java
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run
     
    -java::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
    -	javac *.java
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile java_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean
    diff --git a/Examples/java/class/example.cxx b/Examples/java/class/example.cxx
    index 1e8e203dd..046304519 100644
    --- a/Examples/java/class/example.cxx
    +++ b/Examples/java/class/example.cxx
    @@ -1,4 +1,4 @@
    -/* File : example.c */
    +/* File : example.cxx */
     
     #include "example.h"
     #define M_PI 3.14159265358979323846
    @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) {
     
     int Shape::nshapes = 0;
     
    -double Circle::area(void) {
    +double Circle::area() {
       return M_PI*radius*radius;
     }
     
    -double Circle::perimeter(void) {
    +double Circle::perimeter() {
       return 2*M_PI*radius;
     }
     
    -double Square::area(void) {
    +double Square::area() {
       return width*width;
     }
     
    -double Square::perimeter(void) {
    +double Square::perimeter() {
       return 4*width;
     }
    diff --git a/Examples/java/class/example.dsp b/Examples/java/class/example.dsp
    index fbe87e7a4..f52544b95 100644
    --- a/Examples/java/class/example.dsp
    +++ b/Examples/java/class/example.dsp
    @@ -136,7 +136,7 @@ InputName=example
     	echo JAVA_INCLUDE: %JAVA_INCLUDE% 
     	echo JAVA_BIN: %JAVA_BIN% 
     	echo on 
    -	..\..\..\swig.exe -c++ -java $(InputPath) 
    +	..\..\..\swig.exe -c++ -java "$(InputPath)" 
     	
     # End Custom Build
     
    @@ -151,7 +151,7 @@ InputName=example
     	echo JAVA_INCLUDE: %JAVA_INCLUDE% 
     	echo JAVA_BIN: %JAVA_BIN% 
     	echo on 
    -	..\..\..\swig.exe -c++ -java $(InputPath) 
    +	..\..\..\swig.exe -c++ -java "$(InputPath)" 
     	
     # End Custom Build
     
    diff --git a/Examples/java/class/example.h b/Examples/java/class/example.h
    index 46d901361..0dff185b2 100644
    --- a/Examples/java/class/example.h
    +++ b/Examples/java/class/example.h
    @@ -7,11 +7,11 @@ public:
       }
       virtual ~Shape() {
         nshapes--;
    -  };
    -  double  x, y;   
    +  }
    +  double  x, y;
       void    move(double dx, double dy);
    -  virtual double area(void) = 0;
    -  virtual double perimeter(void) = 0;
    +  virtual double area() = 0;
    +  virtual double perimeter() = 0;
       static  int nshapes;
     };
     
    @@ -19,21 +19,16 @@ class Circle : public Shape {
     private:
       double radius;
     public:
    -  Circle(double r) : radius(r) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    +  Circle(double r) : radius(r) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
     
     class Square : public Shape {
     private:
       double width;
     public:
    -  Square(double w) : width(w) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    +  Square(double w) : width(w) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
    -
    -
    -
    -
    -  
    diff --git a/Examples/java/class/example.i b/Examples/java/class/example.i
    index 75700b305..fbdf7249f 100644
    --- a/Examples/java/class/example.i
    +++ b/Examples/java/class/example.i
    @@ -7,4 +7,3 @@
     
     /* Let's just grab the original header file here */
     %include "example.h"
    -
    diff --git a/Examples/java/class/index.html b/Examples/java/class/index.html
    index cf9130c62..b0a5e221d 100644
    --- a/Examples/java/class/index.html
    +++ b/Examples/java/class/index.html
    @@ -32,8 +32,8 @@ public:
       }
       virtual ~Shape() {
         nshapes--;
    -  };
    -  double  x, y;   
    +  }
    +  double  x, y;
       void    move(double dx, double dy);
       virtual double area() = 0;
       virtual double perimeter() = 0;
    @@ -44,7 +44,7 @@ class Circle : public Shape {
     private:
       double radius;
     public:
    -  Circle(double r) : radius(r) { };
    +  Circle(double r) : radius(r) { }
       virtual double area();
       virtual double perimeter();
     };
    @@ -53,7 +53,7 @@ class Square : public Shape {
     private:
       double width;
     public:
    -  Square(double w) : width(w) { };
    +  Square(double w) : width(w) { }
       virtual double area();
       virtual double perimeter();
     };
    @@ -146,50 +146,15 @@ Shape.setNshapes(13);       // Set a static data member
     
     
    • This high-level interface using proxy classes is not the only way to handle C++ code. -A low level interface using c functions to access member variables and member functions is the alternative SWIG -approach. This entails passing around the c pointer or c++ 'this' pointer and as such it is not difficult to crash the JVM. +A low level interface using C functions to access member variables and member functions is the alternative SWIG +approach. This entails passing around the C pointer or C++ 'this' pointer and as such it is not difficult to crash the JVM. The abstraction of the underlying pointer by the java proxy classes far better fits the java programming paradigm.

      -

    • SWIG *does* know how to properly perform upcasting of objects in an inheritance +
    • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). However Java classes can only derive from one base class so multiple inheritance is not implemented. Java classes can implement more than one interface so there is scope for improvement in the future. -

      -

    • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

      -

        -
      • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
        -
        -void foo(int a);  
        -%name(foo2) void foo(double a, double b);
        -
        -
        - -

        -

      • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
        -
        -%inline %{
        -    Vector *vector_add(Vector *a, Vector *b) {
        -          ... whatever ...
        -    }
        -%}
        -
        -
        - -

        -

      • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). - -

    diff --git a/Examples/java/constants/Makefile b/Examples/java/constants/Makefile index 2b3d35c6a..ddc2157a6 100644 --- a/Examples/java/constants/Makefile +++ b/Examples/java/constants/Makefile @@ -1,18 +1,20 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/enum/Makefile b/Examples/java/enum/Makefile index 14c301703..c76e09262 100644 --- a/Examples/java/enum/Makefile +++ b/Examples/java/enum/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/extend/Makefile b/Examples/java/extend/Makefile index 14c301703..c76e09262 100644 --- a/Examples/java/extend/Makefile +++ b/Examples/java/extend/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/extend/example.h b/Examples/java/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/java/extend/example.h +++ b/Examples/java/extend/example.h @@ -14,7 +14,7 @@ public: 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", this); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/java/extend/runme.java b/Examples/java/extend/runme.java index 629bb14a6..f1ec1ea06 100644 --- a/Examples/java/extend/runme.java +++ b/Examples/java/extend/runme.java @@ -55,7 +55,7 @@ public class runme { // methods of all these instances are treated the same. For items 0, 1, and // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls // getPosition which resolves in Java. The call to getPosition is - // slightly different, however, because of the overidden getPosition() call, since + // slightly different, however, because of the overridden getPosition() call, since // now the object reference has been "laundered" by passing through // EmployeeList as an Employee*. Previously, Java resolved the call // immediately in CEO, but now Java thinks the object is an instance of diff --git a/Examples/java/funcptr/Makefile b/Examples/java/funcptr/Makefile index 968c92c6c..4babc683d 100644 --- a/Examples/java/funcptr/Makefile +++ b/Examples/java/funcptr/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/multimap/Makefile b/Examples/java/multimap/Makefile index 968c92c6c..4babc683d 100644 --- a/Examples/java/multimap/Makefile +++ b/Examples/java/multimap/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/multimap/example.dsp b/Examples/java/multimap/example.dsp index 8e1f8415e..551866fd6 100644 --- a/Examples/java/multimap/example.dsp +++ b/Examples/java/multimap/example.dsp @@ -132,7 +132,7 @@ InputName=example echo JAVA_INCLUDE: %JAVA_INCLUDE% echo JAVA_BIN: %JAVA_BIN% echo on - ..\..\..\swig.exe -java $(InputPath) + ..\..\..\swig.exe -java "$(InputPath)" # End Custom Build @@ -147,7 +147,7 @@ InputName=example echo JAVA_INCLUDE: %JAVA_INCLUDE% echo JAVA_BIN: %JAVA_BIN% echo on - ..\..\..\swig.exe -java $(InputPath) + ..\..\..\swig.exe -java "$(InputPath)" # End Custom Build diff --git a/Examples/java/native/Makefile b/Examples/java/native/Makefile index 92afbd4d0..b43a7d152 100644 --- a/Examples/java/native/Makefile +++ b/Examples/java/native/Makefile @@ -1,18 +1,20 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/nested/Makefile b/Examples/java/nested/Makefile new file mode 100644 index 000000000..c76e09262 --- /dev/null +++ b/Examples/java/nested/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 +SWIGOPT = +JAVASRCS = *.java + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run + +build: + $(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 + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/nested/example.cxx b/Examples/java/nested/example.cxx new file mode 100644 index 000000000..03bb74d9e --- /dev/null +++ b/Examples/java/nested/example.cxx @@ -0,0 +1,62 @@ +#include "example.h" + +int MotorCar::DesignOpinion::AceDesignCount = 0; +int MotorCar::DesignOpinion::TotalDesignCount = 0; + +int MotorCar::DesignOpinion::PercentScore() { + return AceDesignCount*100/TotalDesignCount; +} + +MotorCar::Wheels::Wheels(Shape shape, size_t count) : shape(shape), count(count) {} + +MotorCar::WindScreen::WindScreen(bool opaque) : opaque(opaque) {} + +MotorCar::MotorCar(const std::string &name, const Wheels &wheels, const WindScreen &windscreen) : name(name), wheels(wheels), windscreen(windscreen) {} + +MotorCar MotorCar::DesignFromComponents(const std::string &name, const Wheels &wheels, const WindScreen &windscreen) { + MotorCar car = MotorCar(name, wheels, windscreen); + DesignOpinion::TotalDesignCount++; + if (car.wheels.Opinion().itrocks && car.windscreen.Opinion().itrocks) + DesignOpinion::AceDesignCount++; + return car; +} + +MotorCar::DesignOpinion MotorCar::Wheels::Opinion() { + DesignOpinion opinion; + opinion.itrocks = true; + if (shape == Square) { + opinion.itrocks = false; + opinion.reason = "you'll have a few issues with wheel rotation"; + } + if (count <= 2) { + opinion.reason += opinion.itrocks ? "" : " and "; + opinion.itrocks = false; + opinion.reason += "a few more wheels are needed for stability"; + } + if (opinion.itrocks) + opinion.reason = "your choice of wheels was top notch"; + + return opinion; +} + +MotorCar::DesignOpinion MotorCar::WindScreen::Opinion() { + DesignOpinion opinion; + opinion.itrocks = !opaque; + opinion.reason = opinion.itrocks ? "the driver will have a commanding view out the window" : "you can't see out the windscreen"; + return opinion; +} + +std::string MotorCar::WillItWork() { + DesignOpinion wh = wheels.Opinion(); + DesignOpinion ws = windscreen.Opinion(); + std::string willit; + if (wh.itrocks && ws.itrocks) { + willit = "Great car design because " + wh.reason + " and " + ws.reason; + } else { + willit = "You need a rethink because "; + willit += wh.itrocks ? "" : wh.reason; + willit += (!wh.itrocks && !ws.itrocks) ? " and " : ""; + willit += ws.itrocks ? "" : ws.reason; + } + return willit; +} diff --git a/Examples/java/nested/example.dsp b/Examples/java/nested/example.dsp new file mode 100644 index 000000000..f52544b95 --- /dev/null +++ b/Examples/java/nested/example.dsp @@ -0,0 +1,162 @@ +# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=example - Win32 Release +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "example.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "example - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x809 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Desc=Java compile post-build step +PostBuild_Cmds=echo on "%JAVA_BIN%\javac" *.java +# End Special Build Tool + +!ELSEIF "$(CFG)" == "example - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x809 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"example.dll" +# Begin Special Build Tool +SOURCE="$(InputPath)" +PostBuild_Desc=Java compile post-build step +PostBuild_Cmds=echo on "%JAVA_BIN%\javac" *.java +# End Special Build Tool + +!ENDIF + +# Begin Target + +# Name "example - Win32 Debug" +# Name "example - Win32 Release" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\example.cxx +# End Source File +# Begin Source File + +SOURCE=.\example_wrap.cxx +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\example.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# Begin Source File + +SOURCE=.\example.i + +!IF "$(CFG)" == "example - Win32 Debug" + +# Begin Custom Build +InputPath=.\example.i +InputName=example + +"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + echo In order to function correctly, please ensure the following environment variables are correctly set: + echo JAVA_INCLUDE: %JAVA_INCLUDE% + echo JAVA_BIN: %JAVA_BIN% + echo on + ..\..\..\swig.exe -c++ -java "$(InputPath)" + +# End Custom Build + +!ELSEIF "$(CFG)" == "example - Win32 Release" + +# Begin Custom Build +InputPath=.\example.i +InputName=example + +"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + echo In order to function correctly, please ensure the following environment variables are correctly set: + echo JAVA_INCLUDE: %JAVA_INCLUDE% + echo JAVA_BIN: %JAVA_BIN% + echo on + ..\..\..\swig.exe -c++ -java "$(InputPath)" + +# End Custom Build + +!ENDIF + +# End Source File +# End Target +# End Project diff --git a/Examples/java/nested/example.h b/Examples/java/nested/example.h new file mode 100644 index 000000000..4fb107cb5 --- /dev/null +++ b/Examples/java/nested/example.h @@ -0,0 +1,48 @@ +#include + +/** Design a motor car from various components */ +struct MotorCar { + + /** Information about an opinion of the design of a car component */ + struct DesignOpinion { + bool itrocks; + std::string reason; + static int AceDesignCount; + static int TotalDesignCount; + static int PercentScore(); + }; + + /** Wheels component */ + struct Wheels { + enum Shape { Round, Square }; + Wheels(Shape shape, size_t count); + DesignOpinion Opinion(); + private: + Shape shape; + size_t count; + }; + + /** Windscreen component */ + struct WindScreen { + WindScreen(bool opaque); + DesignOpinion Opinion(); + private: + bool opaque; + }; + + /** Factory method for creating a car */ + static MotorCar DesignFromComponents(const std::string &name, const Wheels &wheels, const WindScreen &windscreen); + + std::string Name() { + return name; + } + + /** Get an overall opinion on the car design */ + std::string WillItWork(); + +private: + MotorCar(const std::string &name, const Wheels &wheels, const WindScreen &windscreen); + std::string name; + Wheels wheels; + WindScreen windscreen; +}; diff --git a/Examples/java/nested/example.i b/Examples/java/nested/example.i new file mode 100644 index 000000000..c07c1521a --- /dev/null +++ b/Examples/java/nested/example.i @@ -0,0 +1,13 @@ +%module example + +// This example shows how wrappers for numerous aspects of C++ nested classes work: +// Nested static and instance variables and methods and nested enums + +%include + +%{ +#include "example.h" +%} + +%include "example.h" + diff --git a/Examples/java/nested/runme.java b/Examples/java/nested/runme.java new file mode 100644 index 000000000..855dbea91 --- /dev/null +++ b/Examples/java/nested/runme.java @@ -0,0 +1,32 @@ +// This example illustrates wrapping of nested C++ classes + +public class runme { + static { + try { + System.loadLibrary("example"); + } 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); + } + } + + public static void main(String argv[]) + { + MotorCar car1 = MotorCar.DesignFromComponents("Bumpy", new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 4), new MotorCar.WindScreen(false)); + MotorCar car2 = MotorCar.DesignFromComponents("Wobbly", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 2), new MotorCar.WindScreen(false)); + MotorCar car3 = MotorCar.DesignFromComponents("Batty", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 4), new MotorCar.WindScreen(true)); + MotorCar car4 = MotorCar.DesignFromComponents("Spiffing", new MotorCar.Wheels(MotorCar.Wheels.Shape.Round, 4), new MotorCar.WindScreen(false)); + + System.out.println("Expert opinion on " + car1.Name() + " : \n " + car1.WillItWork()); + System.out.println("Expert opinion on " + car2.Name() + " : \n " + car2.WillItWork()); + System.out.println("Expert opinion on " + car3.Name() + " : \n " + car3.WillItWork()); + System.out.println("Expert opinion on " + car4.Name() + " : \n " + car4.WillItWork()); + + int count = MotorCar.DesignOpinion.getAceDesignCount(); + int total = MotorCar.DesignOpinion.getTotalDesignCount(); + int percent = MotorCar.DesignOpinion.PercentScore(); + System.out.println("Overall opinion rating on car design is " + count + "/" + total + " = " + percent + "%"); + + System.out.println("Single square wheel thoughts: " + new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 1).Opinion().getReason()); + } +} diff --git a/Examples/java/pointer/Makefile b/Examples/java/pointer/Makefile index 968c92c6c..4babc683d 100644 --- a/Examples/java/pointer/Makefile +++ b/Examples/java/pointer/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/pointer/example.i b/Examples/java/pointer/example.i index a8ac79499..ed1c2fcc3 100644 --- a/Examples/java/pointer/example.i +++ b/Examples/java/pointer/example.i @@ -24,7 +24,3 @@ extern void sub(int *INPUT, int *INPUT, int *OUTPUT); %apply int *OUTPUT { int *r }; extern int divide(int n, int d, int *r); - - - - diff --git a/Examples/java/reference/Makefile b/Examples/java/reference/Makefile index 14c301703..c76e09262 100644 --- a/Examples/java/reference/Makefile +++ b/Examples/java/reference/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/reference/example.cxx b/Examples/java/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/java/reference/example.cxx +++ b/Examples/java/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/java/reference/example.h b/Examples/java/reference/example.h index 4915adb1b..bcfcfb72f 100644 --- a/Examples/java/reference/example.h +++ b/Examples/java/reference/example.h @@ -4,8 +4,8 @@ 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) { }; + 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 *print(); }; @@ -20,7 +20,3 @@ public: Vector &operator[](int); int size(); }; - - - - diff --git a/Examples/java/reference/example.i b/Examples/java/reference/example.i index 6daa3b1f4..173143d79 100644 --- a/Examples/java/reference/example.i +++ b/Examples/java/reference/example.i @@ -29,7 +29,7 @@ public: VectorArray(int maxsize); ~VectorArray(); int size(); - + /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { @@ -40,7 +40,3 @@ public: } } }; - - - - diff --git a/Examples/java/simple/Makefile b/Examples/java/simple/Makefile index 968c92c6c..4babc683d 100644 --- a/Examples/java/simple/Makefile +++ b/Examples/java/simple/Makefile @@ -1,18 +1,20 @@ 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 SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/simple/example.dsp b/Examples/java/simple/example.dsp index 8e1f8415e..551866fd6 100644 --- a/Examples/java/simple/example.dsp +++ b/Examples/java/simple/example.dsp @@ -132,7 +132,7 @@ InputName=example echo JAVA_INCLUDE: %JAVA_INCLUDE% echo JAVA_BIN: %JAVA_BIN% echo on - ..\..\..\swig.exe -java $(InputPath) + ..\..\..\swig.exe -java "$(InputPath)" # End Custom Build @@ -147,7 +147,7 @@ InputName=example echo JAVA_INCLUDE: %JAVA_INCLUDE% echo JAVA_BIN: %JAVA_BIN% echo on - ..\..\..\swig.exe -java $(InputPath) + ..\..\..\swig.exe -java "$(InputPath)" # End Custom Build diff --git a/Examples/java/template/Makefile b/Examples/java/template/Makefile index 2b3d35c6a..ddc2157a6 100644 --- a/Examples/java/template/Makefile +++ b/Examples/java/template/Makefile @@ -1,18 +1,20 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i SWIGOPT = +JAVASRCS = *.java -all:: java +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run -java:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - javac *.java + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile -clean:: - $(MAKE) -f $(TOP)/Makefile java_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/template/index.html b/Examples/java/template/index.html index f4408e568..31dba6d8e 100644 --- a/Examples/java/template/index.html +++ b/Examples/java/template/index.html @@ -16,7 +16,7 @@ This example illustrates how C++ templates can be used from Java using SWIG.

    The C++ Code

    -Lets take a templated function and a templated class as follows: +Let's take a templated function and a templated class as follows:
    diff --git a/Examples/java/typemap/Makefile b/Examples/java/typemap/Makefile
    index 92afbd4d0..b43a7d152 100644
    --- a/Examples/java/typemap/Makefile
    +++ b/Examples/java/typemap/Makefile
    @@ -1,18 +1,20 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     SWIGOPT    =
    +JAVASRCS   = *.java
     
    -all::	java
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run
     
    -java::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
    -	javac *.java
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile java_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean
    diff --git a/Examples/java/variables/Makefile b/Examples/java/variables/Makefile
    index 968c92c6c..4babc683d 100644
    --- a/Examples/java/variables/Makefile
    +++ b/Examples/java/variables/Makefile
    @@ -1,18 +1,20 @@
     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
     SWIGOPT    =
    +JAVASRCS   = *.java
     
    -all::	java
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run
     
    -java::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
    -	javac *.java
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile java_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean
    diff --git a/Examples/java/variables/example.c b/Examples/java/variables/example.c
    index aa4ffe9b3..85685fe72 100644
    --- a/Examples/java/variables/example.c
    +++ b/Examples/java/variables/example.c
    @@ -51,10 +51,10 @@ void print_vars() {
       printf("dvar      = %g\n", dvar);
       printf("cvar      = %c\n", cvar);
       printf("strvar    = %s\n", strvar ? strvar : "(null)");
    -  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
    -  printf("iptrvar   = %p\n", iptrvar);
    +  printf("cstrvar   = %s\n", cstrvar);
    +  printf("iptrvar   = %p\n", (void *)iptrvar);
       printf("name      = %s\n", name);
    -  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
    +  printf("ptptr     = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
       printf("pt        = (%d, %d)\n", pt.x, pt.y);
       printf("status    = %d\n", status);
     }
    diff --git a/Examples/javascript/check.list b/Examples/javascript/check.list
    new file mode 100644
    index 000000000..9707e77d4
    --- /dev/null
    +++ b/Examples/javascript/check.list
    @@ -0,0 +1,13 @@
    +class
    +constant
    +enum
    +exception
    +functor
    +nspace
    +operator
    +overload
    +pointer
    +#reference
    +simple
    +template
    +variables
    diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile
    new file mode 100644
    index 000000000..54a8f7b03
    --- /dev/null
    +++ b/Examples/javascript/class/Makefile
    @@ -0,0 +1,3 @@
    +SRCS = example.cxx
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/class/binding.gyp.in b/Examples/javascript/class/binding.gyp.in
    new file mode 100644
    index 000000000..cb2b45e8f
    --- /dev/null
    +++ b/Examples/javascript/class/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "
    +
    +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/javascript/enum/example.h b/Examples/javascript/enum/example.h
    new file mode 100644
    index 000000000..9119cd9fc
    --- /dev/null
    +++ b/Examples/javascript/enum/example.h
    @@ -0,0 +1,13 @@
    +/* File : example.h */
    +
    +enum color { RED, BLUE, GREEN };
    +
    +class Foo {
    + public:
    +  Foo() { }
    +  enum speed { IMPULSE=10, WARP=20, LUDICROUS=30 };
    +  void enum_test(speed s);
    +};
    +
    +void enum_test(color c, Foo::speed s);
    +
    diff --git a/Examples/javascript/enum/example.i b/Examples/javascript/enum/example.i
    new file mode 100644
    index 000000000..23ee8a822
    --- /dev/null
    +++ b/Examples/javascript/enum/example.i
    @@ -0,0 +1,11 @@
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +/* Let's just grab the original header file here */
    +
    +%include "example.h"
    +
    diff --git a/Examples/javascript/enum/example.js b/Examples/javascript/enum/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/enum/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js
    new file mode 100644
    index 000000000..851d43c4b
    --- /dev/null
    +++ b/Examples/javascript/enum/runme.js
    @@ -0,0 +1,34 @@
    +var example = require("example");
    +
    +// ----- Object creation -----
    +
    +// Print out the value of some enums
    +console.log("*** color ***");
    +console.log("    RED    =" + example.RED);
    +console.log("    BLUE   =" + example.BLUE);
    +console.log("    GREEN  =" + example.GREEN);
    +
    +console.log("\n*** Foo::speed ***");
    +console.log("    Foo_IMPULSE   =" + example.Foo.IMPULSE);
    +console.log("    Foo_WARP      =" + example.Foo.WARP);
    +console.log("    Foo_LUDICROUS =" + example.Foo.LUDICROUS);
    +
    +console.log("\nTesting use of enums with functions\n");
    +
    +example.enum_test(example.RED, example.Foo.IMPULSE);
    +example.enum_test(example.BLUE,  example.Foo.WARP);
    +example.enum_test(example.GREEN, example.Foo.LUDICROUS);
    +example.enum_test(1234,5678);
    +
    +console.log("\nTesting use of enum with class method");
    +f = new example.Foo();
    +
    +f.enum_test(example.Foo.IMPULSE);
    +f.enum_test(example.Foo.WARP);
    +f.enum_test(example.Foo.LUDICROUS);
    +
    +// enum value BLUE of enum color is accessed as property of cconst
    +console.log("example.BLUE= " + example.BLUE);
    +
    +// enum value LUDICROUS of enum Foo::speed is accessed as as property of cconst
    +console.log("example.speed.LUDICROUS= " + example.Foo.LUDICROUS); 
    diff --git a/Examples/javascript/example.mk b/Examples/javascript/example.mk
    new file mode 100644
    index 000000000..3ef012aa8
    --- /dev/null
    +++ b/Examples/javascript/example.mk
    @@ -0,0 +1,36 @@
    +# Note: as a convention an example must be in a child directory of this.
    +# These paths are relative to such an example directory
    +
    +ifneq (, $(ENGINE))
    +	JSENGINE=$(ENGINE)
    +else
    +	JSENGINE=node
    +endif
    +
    +ifneq (, $(V8_VERSION))
    +	JSV8_VERSION=$(V8_VERSION)
    +else
    +	JSV8_VERSION=0x031110
    +endif
    +
    +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_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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_cpp
    +
    +clean:
    +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' javascript_clean
    diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile
    new file mode 100644
    index 000000000..54a8f7b03
    --- /dev/null
    +++ b/Examples/javascript/exception/Makefile
    @@ -0,0 +1,3 @@
    +SRCS = example.cxx
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/exception/binding.gyp.in b/Examples/javascript/exception/binding.gyp.in
    new file mode 100644
    index 000000000..2e97d9757
    --- /dev/null
    +++ b/Examples/javascript/exception/binding.gyp.in
    @@ -0,0 +1,30 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "
    +#ifndef SWIG
    +struct A {
    +};
    +#endif
    +
    +class Exc {
    +public:
    +  Exc(int c, const char *m) {
    +    code = c;
    +    strncpy(msg,m,256);
    +  }
    +  int code;
    +  char msg[256];
    +};
    +
    +#if defined(_MSC_VER)
    +  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
    +#endif
    +
    +class Test {
    +public:
    +  int simple() throw(int) {
    +      throw(37);
    +      return 1;
    +  }
    +  int message() throw(const char *) {
    +      throw("I died.");
    +      return 1;
    +  }
    +  int hosed() throw(Exc) {
    +      throw(Exc(42,"Hosed"));
    +      return 1;
    +  } 
    +  int unknown() throw(A*) {
    +      static A a;
    +      throw &a;
    +      return 1;
    +  }
    +  int multi(int x) throw(int, const char *, Exc) {
    +     if (x == 1) throw(37);
    +     if (x == 2) throw("Bleah!");
    +     if (x == 3) throw(Exc(42,"No-go-diggy-die"));
    +     return 1;
    +  }
    +};
    +
    +#if defined(_MSC_VER)
    +  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
    +#endif
    +
    diff --git a/Examples/javascript/exception/example.i b/Examples/javascript/exception/example.i
    new file mode 100644
    index 000000000..08672c3a8
    --- /dev/null
    +++ b/Examples/javascript/exception/example.i
    @@ -0,0 +1,12 @@
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +%include "std_string.i"
    +
    +/* Let's just grab the original header file here */
    +%include "example.h"
    +
    diff --git a/Examples/javascript/exception/example.js b/Examples/javascript/exception/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/exception/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js
    new file mode 100644
    index 000000000..43ce66d6d
    --- /dev/null
    +++ b/Examples/javascript/exception/runme.js
    @@ -0,0 +1,64 @@
    +var example = require("example");
    +
    +console.log("Trying to catch some exceptions.");
    +t = new example.Test();
    +try{
    +  t.unknown();
    +  throw -1;
    +} catch(error)
    +{
    +  if(error == -1) {
    +    console.log("t.unknown() didn't throw");
    +  } else {
    +    console.log("successfully catched throw in Test::unknown().");
    +  }
    +}
    +
    +try{
    +    t.simple();
    +    throw -1;
    +}
    +catch(error){
    +  if(error == -1) {
    +    console.log("t.simple() did not throw");
    +  } else {
    +    console.log("successfully catched throw in Test::simple().");
    +  }
    +}
    +
    +try{
    +  t.message();
    +  throw -1;
    +} catch(error){
    +  if(error == -1) {
    +    console.log("t.message() did not throw");
    +  } else {
    +    console.log("successfully catched throw in Test::message().");
    +  }
    +}
    +    
    +try{
    +  t.hosed();
    +  throw -1;
    +}
    +catch(error){ 
    +  if(error == -1) {
    +    console.log("t.hosed() did not throw");
    +  } else {
    +    console.log("successfully catched throw in Test::hosed().");
    +  }
    +}
    +
    +for (var i=1; i<4; i++) {
    +  try{
    +      t.multi(i);
    +      throw -1;
    +  }
    +  catch(error){
    +    if(error == -1) {
    +      console.log("t.multi(" + i + ") did not throw");
    +    } else {
    +      console.log("successfully catched throw in Test::multi().");
    +    }
    +  }
    +}    
    diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile
    new file mode 100644
    index 000000000..0402f8d09
    --- /dev/null
    +++ b/Examples/javascript/functor/Makefile
    @@ -0,0 +1,3 @@
    +SRCS =
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/functor/binding.gyp.in b/Examples/javascript/functor/binding.gyp.in
    new file mode 100644
    index 000000000..59779aef4
    --- /dev/null
    +++ b/Examples/javascript/functor/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example_wrap.cxx" ],
    +      "include_dirs": ["$srcdir"]
    +    }
    +  ]
    +}
    diff --git a/Examples/javascript/functor/example.i b/Examples/javascript/functor/example.i
    new file mode 100644
    index 000000000..0450c2124
    --- /dev/null
    +++ b/Examples/javascript/functor/example.i
    @@ -0,0 +1,25 @@
    +/* File : example.i */
    +%module example
    +
    +
    +%inline %{
    +// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514
    +template class Sum {
    +   T res;
    +public:
    +   Sum(T i = 0) : res(i) { }
    +   void operator() (T x) { res += x; }
    +   T result() const { return res; }
    +};
    +
    +%}
    +
    +%rename(call)	*::operator();	// the fn call operator
    +
    +// Instantiate a few versions
    +%template(intSum) Sum;
    +%template(doubleSum) Sum;
    +
    +
    +
    +
    diff --git a/Examples/javascript/functor/example.js b/Examples/javascript/functor/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/functor/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js
    new file mode 100644
    index 000000000..28dc64320
    --- /dev/null
    +++ b/Examples/javascript/functor/runme.js
    @@ -0,0 +1,15 @@
    +var example = require("example");
    +
    +a = new example.intSum(0);
    +b = new example.doubleSum(100.0);
    +
    +// Use the objects.  They should be callable just like a normal
    +// javascript function.
    +
    +for (i=1;i<=100;i++) 
    +    a.call(i);                // Note: function call
    +    b.call(Math.sqrt(i));     // Note: function call
    +
    +console.log(a.result());
    +console.log(b.result());
    +
    diff --git a/Examples/javascript/nspace/Makefile b/Examples/javascript/nspace/Makefile
    new file mode 100644
    index 000000000..0402f8d09
    --- /dev/null
    +++ b/Examples/javascript/nspace/Makefile
    @@ -0,0 +1,3 @@
    +SRCS =
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/nspace/binding.gyp.in b/Examples/javascript/nspace/binding.gyp.in
    new file mode 100644
    index 000000000..59779aef4
    --- /dev/null
    +++ b/Examples/javascript/nspace/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example_wrap.cxx" ],
    +      "include_dirs": ["$srcdir"]
    +    }
    +  ]
    +}
    diff --git a/Examples/javascript/nspace/example.h b/Examples/javascript/nspace/example.h
    new file mode 100644
    index 000000000..53066980a
    --- /dev/null
    +++ b/Examples/javascript/nspace/example.h
    @@ -0,0 +1,23 @@
    +#ifndef _example_guardian_
    +#define _example_guardian_
    +
    +int module_function() { return 7; }
    +int module_variable = 9;
    +
    +namespace MyWorld {
    +  class World {
    +  public:
    +    World() : world_max_count(9) {}
    +    int create_world() { return 17; }
    +    const int world_max_count; // = 9
    +  };
    +  namespace Nested {
    +    class Dweller {
    +      public:
    +        enum Gender { MALE = 0, FEMALE = 1 };
    +        static int count() { return 19; }
    +    };
    +  }
    +}
    +
    +#endif
    diff --git a/Examples/javascript/nspace/example.i b/Examples/javascript/nspace/example.i
    new file mode 100644
    index 000000000..c30f87fec
    --- /dev/null
    +++ b/Examples/javascript/nspace/example.i
    @@ -0,0 +1,10 @@
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +%nspace MyWorld::Nested::Dweller;
    +%nspace MyWorld::World;
    +
    +%include "example.h"
    diff --git a/Examples/javascript/nspace/example.js b/Examples/javascript/nspace/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/nspace/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/nspace/runme.js b/Examples/javascript/nspace/runme.js
    new file mode 100644
    index 000000000..fad73477d
    --- /dev/null
    +++ b/Examples/javascript/nspace/runme.js
    @@ -0,0 +1,50 @@
    +// File: runme.js
    +
    +// This file illustrates class C++ interface generated
    +// by SWIG.
    +
    +var example = require("example");
    +
    +// Calling a module function ( aka global function )
    +if (example.module_function() !== 7) {
    +  throw new Error("example.module_function() should equal 7");
    +}
    +console.log("example.module_function(): " + example.module_function());
    +
    +// Accessing a module (aka global) variable
    +if (example.module_variable !== 9) {
    +  throw new Error("example.module_variable should equal 9");
    +}
    +console.log("example.module_variable: " + example.module_variable);
    +
    +// Creating an instance of the class
    +var w1 = new example.MyWorld.World();
    +console.log("Creating class instance: w1 = new example.MyWorld.World(): " + w1);
    +
    +// Accessing class members
    +if (w1.create_world() !== 17) {
    +  throw new Error("w1.create_world() should equal 17");
    +}
    +console.log("w1.create_world() = " + w1.create_world());
    +
    +if (w1.world_max_count !== 9) {
    +  throw new Error("w1.world_max_count should equal 9");
    +}
    +console.log("w1.world_max_count = " + w1.world_max_count);
    +
    +// Accessing enums from class within namespace
    +if (example.MyWorld.Nested.Dweller.MALE !== 0) {
    +  throw new Error("example.MyWorld.Nested.Dweller.MALE should equal 0");
    +}
    +console.log("Accessing enums: ex.MyWorld.Nested.Dweller.MALE = " + example.MyWorld.Nested.Dweller.MALE);
    +
    +if (example.MyWorld.Nested.Dweller.FEMALE !== 1) {
    +  throw new Error("example.MyWorld.Nested.Dweller.FEMALE should equal 1");
    +}
    +console.log("Accessing enums: ex.MyWorld.Nested.Dweller.FEMALE = " + example.MyWorld.Nested.Dweller.FEMALE);
    +
    +// Accessing static member function
    +if (example.MyWorld.Nested.Dweller.count() !== 19) {
    +  throw new Error("example.MyWorld.Nested.Dweller.count() should equal 19");
    +}
    +console.log("Accessing static member function: ex.MyWorld.Nested.Dweller.count() = " + example.MyWorld.Nested.Dweller.count());
    diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile
    new file mode 100644
    index 000000000..0402f8d09
    --- /dev/null
    +++ b/Examples/javascript/operator/Makefile
    @@ -0,0 +1,3 @@
    +SRCS =
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/operator/binding.gyp.in b/Examples/javascript/operator/binding.gyp.in
    new file mode 100644
    index 000000000..59779aef4
    --- /dev/null
    +++ b/Examples/javascript/operator/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example_wrap.cxx" ],
    +      "include_dirs": ["$srcdir"]
    +    }
    +  ]
    +}
    diff --git a/Examples/javascript/operator/example.h b/Examples/javascript/operator/example.h
    new file mode 100644
    index 000000000..4da6a2307
    --- /dev/null
    +++ b/Examples/javascript/operator/example.h
    @@ -0,0 +1,36 @@
    +/* File : example.h */
    +#include 
    +
    +class Complex {
    +private:
    +  double rpart, ipart;
    +public:
    +  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
    +  Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
    +  Complex &operator=(const Complex &c) {
    +    rpart = c.rpart;
    +    ipart = c.ipart;
    +    return *this;
    +  }
    +  Complex operator+(const Complex &c) const {
    +    return Complex(rpart+c.rpart, ipart+c.ipart);
    +  }
    +  Complex operator-(const Complex &c) const {
    +    return Complex(rpart-c.rpart, ipart-c.ipart);
    +  }
    +  Complex operator*(const Complex &c) const {
    +    return Complex(rpart*c.rpart - ipart*c.ipart,
    +		   rpart*c.ipart + c.rpart*ipart);
    +  }
    +  Complex operator-() const {
    +    return Complex(-rpart, -ipart);
    +  }
    +  
    +  double re() const { return rpart; }
    +  double im() const { return ipart; }
    +};
    +
    +
    +
    +
    +  
    diff --git a/Examples/javascript/operator/example.i b/Examples/javascript/operator/example.i
    new file mode 100644
    index 000000000..7a1bd45e1
    --- /dev/null
    +++ b/Examples/javascript/operator/example.i
    @@ -0,0 +1,34 @@
    +/* File : example.i */
    +%module example
    +#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ
    +%{
    +#include "example.h"
    +%}
    +
    +/* This header file is a little tough to handle because it has overloaded
    +   operators and constructors.  We're going to try and deal with that here */
    +
    +/* This turns the copy constructor in a function ComplexCopy() that can
    +   be called */
    +
    +%rename(assign) Complex::operator=;
    +%rename(plus) Complex::operator+;
    +%rename(minus) Complex::operator-(const Complex &) const;
    +%rename(uminus) Complex::operator-() const;
    +%rename(times) Complex::operator*;
    +
    +/* Now grab the original header file */
    +%include "example.h"
    +
    +/* An output method that turns a complex into a short string */
    +%extend Complex {
    + char *toString() {
    +   static char temp[512];
    +   sprintf(temp,"(%g,%g)", $self->re(), $self->im());
    +   return temp;
    + }
    + static Complex* copy(const Complex& c) {
    +   return new Complex(c);
    + }
    +};
    +
    diff --git a/Examples/javascript/operator/example.js b/Examples/javascript/operator/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/operator/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js
    new file mode 100644
    index 000000000..f72ca1c28
    --- /dev/null
    +++ b/Examples/javascript/operator/runme.js
    @@ -0,0 +1,25 @@
    +var example = require("example");
    +
    +a = new example.Complex(2,3);
    +b = new example.Complex(-5,10);
    +
    +console.log ("a =" + a);
    +console.log ("b   =" + b);
    +
    +c = a.plus(b);
    +
    +console.log("c   =" + c);
    +console.log("a*b =" + a.times(b));
    +console.log("a-c =" + a.minus(c));
    +
    +e = example.Complex.copy(a.minus(c));
    +console.log("e   =" + e);
    +
    +// Big expression
    +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus());
    +console.log("f   =" + f);
    +
    +
    +
    +
    +
    diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile
    new file mode 100644
    index 000000000..0402f8d09
    --- /dev/null
    +++ b/Examples/javascript/overload/Makefile
    @@ -0,0 +1,3 @@
    +SRCS =
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/overload/binding.gyp.in b/Examples/javascript/overload/binding.gyp.in
    new file mode 100644
    index 000000000..59779aef4
    --- /dev/null
    +++ b/Examples/javascript/overload/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example_wrap.cxx" ],
    +      "include_dirs": ["$srcdir"]
    +    }
    +  ]
    +}
    diff --git a/Examples/javascript/overload/example.h b/Examples/javascript/overload/example.h
    new file mode 100644
    index 000000000..2f112f1e1
    --- /dev/null
    +++ b/Examples/javascript/overload/example.h
    @@ -0,0 +1,28 @@
    +#include 
    +
    +void f() {
    +  std::cout << "Called f()." << std::endl;
    +}
    +
    +void f(int val) {
    +  std::cout << "Called f(int)." << std::endl;
    +}
    +void f(int val1, int val2) {
    +  std::cout << "Called f(int, int)." << std::endl;
    +}
    +
    +void f(const char* s) {
    +  std::cout << "Called f(const char*)." << std::endl;
    +}
    +
    +void f(bool val) {
    +  std::cout << "Called f(bool)." << std::endl;
    +}
    +
    +void f(long val) {
    +  std::cout << "Called f(long)." << std::endl;
    +}
    +
    +void f(double val) {
    +  std::cout << "Called f(double)." << std::endl;
    +}
    diff --git a/Examples/javascript/overload/example.i b/Examples/javascript/overload/example.i
    new file mode 100644
    index 000000000..b86689f8a
    --- /dev/null
    +++ b/Examples/javascript/overload/example.i
    @@ -0,0 +1,16 @@
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +/*
    +  Note: overloading is implemented in a sloppy way currently
    +        i.e., only the number of arguments is taken into conideration
    +        for dispatching.
    +        To solve the problem one has to rename such conflicting methods.
    +*/
    +%rename(f_double) f(double val);
    +
    +%include "example.h"
    diff --git a/Examples/javascript/overload/example.js b/Examples/javascript/overload/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/overload/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js
    new file mode 100644
    index 000000000..1c23e3b6b
    --- /dev/null
    +++ b/Examples/javascript/overload/runme.js
    @@ -0,0 +1,9 @@
    +var example = require("example");
    +
    +example.f();
    +example.f(1);
    +example.f(1, 2);
    +example.f("bla");
    +example.f(false);
    +example.f(11111111111);
    +example.f_double(1.0);
    diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile
    new file mode 100644
    index 000000000..54a8f7b03
    --- /dev/null
    +++ b/Examples/javascript/pointer/Makefile
    @@ -0,0 +1,3 @@
    +SRCS = example.cxx
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/pointer/binding.gyp.in b/Examples/javascript/pointer/binding.gyp.in
    new file mode 100644
    index 000000000..cb2b45e8f
    --- /dev/null
    +++ b/Examples/javascript/pointer/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ " 0) {
    +    g = x;
    +    x = y % x;
    +    y = g;
    +  }
    +  return g;
    +}
    +
    +
    diff --git a/Examples/javascript/simple/example.i b/Examples/javascript/simple/example.i
    new file mode 100644
    index 000000000..24093b9bf
    --- /dev/null
    +++ b/Examples/javascript/simple/example.i
    @@ -0,0 +1,7 @@
    +/* File : example.i */
    +%module example
    +
    +%inline %{
    +extern int    gcd(int x, int y);
    +extern double Foo;
    +%}
    diff --git a/Examples/javascript/simple/example.js b/Examples/javascript/simple/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/simple/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js
    new file mode 100644
    index 000000000..4abff0e2a
    --- /dev/null
    +++ b/Examples/javascript/simple/runme.js
    @@ -0,0 +1,26 @@
    +var example = require("example");
    +
    +/* Call our gcd() function */
    +
    +x = 42;
    +y = 105;
    +g = example.gcd(x,y);
    +console.log("GCD of x and y is=" + g);
    +
    +/* Manipulate the Foo global variable */
    +
    +/* Output its current value */
    +console.log("Global variable Foo=" + example.Foo);
    +
    +/* Change its value */
    +example.Foo = 3.1415926;
    +
    +/* See if the change took effect */
    +console.log("Variable Foo changed to=" + example.Foo);
    +
    +
    +
    +
    + 
    + 
    + 
    diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile
    new file mode 100644
    index 000000000..0402f8d09
    --- /dev/null
    +++ b/Examples/javascript/template/Makefile
    @@ -0,0 +1,3 @@
    +SRCS =
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/template/binding.gyp.in b/Examples/javascript/template/binding.gyp.in
    new file mode 100644
    index 000000000..59779aef4
    --- /dev/null
    +++ b/Examples/javascript/template/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "example_wrap.cxx" ],
    +      "include_dirs": ["$srcdir"]
    +    }
    +  ]
    +}
    diff --git a/Examples/javascript/template/example.h b/Examples/javascript/template/example.h
    new file mode 100644
    index 000000000..7401df650
    --- /dev/null
    +++ b/Examples/javascript/template/example.h
    @@ -0,0 +1,32 @@
    +/* File : example.h */
    +
    +// Some template definitions
    +
    +template T max(T a, T b) { return  a>b ? a : b; }
    +
    +template class vector {
    +  T *v;
    +  int sz;
    + public:
    +  vector(int _sz) {
    +    v = new T[_sz];
    +    sz = _sz;
    +  }
    +  T &get(int index) {
    +    return v[index];
    +  }
    +  void set(int index, T &val) {
    +    v[index] = val;
    +  }
    +#ifdef SWIG
    +  %extend {
    +    T getitem(int index) {
    +      return $self->get(index);
    +    }
    +    void setitem(int index, T val) {
    +      $self->set(index,val);
    +    }
    +  }
    +#endif
    +};
    +
    diff --git a/Examples/javascript/template/example.i b/Examples/javascript/template/example.i
    new file mode 100644
    index 000000000..8f94c4da1
    --- /dev/null
    +++ b/Examples/javascript/template/example.i
    @@ -0,0 +1,17 @@
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +/* Let's just grab the original header file here */
    +%include "example.h"
    +
    +/* Now instantiate some specific template declarations */
    +
    +%template(maxint) max;
    +%template(maxdouble) max;
    +%template(vecint) vector;
    +%template(vecdouble) vector;
    +
    diff --git a/Examples/javascript/template/example.js b/Examples/javascript/template/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/template/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js
    new file mode 100644
    index 000000000..6a29fa77c
    --- /dev/null
    +++ b/Examples/javascript/template/runme.js
    @@ -0,0 +1,30 @@
    +var example = require("example");
    +
    +//Call some templated functions
    +console.log(example.maxint(3,7));
    +console.log(example.maxdouble(3.14,2.18));
    +
    +// Create some class
    +
    +iv = new example.vecint(100);
    +dv = new example.vecdouble(1000);
    +
    +for(i=0;i<100;i++)
    +      iv.setitem(i,2*i);
    +
    +for(i=0;i<1000;i++)
    +      dv.setitem(i, 1.0/(i+1));
    +
    +sum = 0;
    +for(i=0;i<100;i++)
    +      sum = sum + iv.getitem(i);
    +
    +console.log(sum);
    +
    +sum = 0.0;
    +for(i=0;i<1000;i++)
    +      sum = sum + dv.getitem(i);
    +console.log(sum);
    +
    +delete iv;
    +delete dv;
    diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile
    new file mode 100644
    index 000000000..54a8f7b03
    --- /dev/null
    +++ b/Examples/javascript/variables/Makefile
    @@ -0,0 +1,3 @@
    +SRCS = example.cxx
    +
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/javascript/variables/binding.gyp.in b/Examples/javascript/variables/binding.gyp.in
    new file mode 100644
    index 000000000..cb2b45e8f
    --- /dev/null
    +++ b/Examples/javascript/variables/binding.gyp.in
    @@ -0,0 +1,9 @@
    +{
    +  "targets": [
    +    {
    +      "target_name": "example",
    +      "sources": [ "
    +#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;
    +#ifdef __cplusplus // Note: for v8 this must be linkable with g++, without extern cstrvar is mangled
    +extern const char cstrvar[] = "Goodbye";
    +#else
    +const char cstrvar[] = "Goodbye";
    +#endif
    +const 
    +int             *iptrvar = 0;
    +char             name[256] = "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      = %s\n", name);
    +  printf("ptptr     = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
    +  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;
    +}
    +
    +/* 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/javascript/variables/example.h b/Examples/javascript/variables/example.h
    new file mode 100644
    index 000000000..0f7e89594
    --- /dev/null
    +++ b/Examples/javascript/variables/example.h
    @@ -0,0 +1,6 @@
    +/* File: example.h */
    +
    +typedef struct {
    +  int x,y;
    +} Point;
    +
    diff --git a/Examples/javascript/variables/example.i b/Examples/javascript/variables/example.i
    new file mode 100644
    index 000000000..591b871ed
    --- /dev/null
    +++ b/Examples/javascript/variables/example.i
    @@ -0,0 +1,49 @@
    +/* File : example.i */
    +%module example
    +%{
    +#include "example.h"
    +%}
    +
    +/* Some global variable declarations */
    +%inline %{
    +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[256];
    +
    +extern Point           *ptptr;
    +extern Point            pt;
    +%}
    +
    +
    +/* Some read-only variables */
    +
    +%immutable;
    +
    +%inline %{
    +extern int  status;
    +extern char path[256];
    +%}
    +
    +%mutable;
    +
    +/* Some helper functions to make it easier to test */
    +%inline %{
    +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/javascript/variables/example.js b/Examples/javascript/variables/example.js
    new file mode 100644
    index 000000000..2e7f83a06
    --- /dev/null
    +++ b/Examples/javascript/variables/example.js
    @@ -0,0 +1 @@
    +module.exports = require("build/Release/example");
    diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js
    new file mode 100644
    index 000000000..a2b5f791c
    --- /dev/null
    +++ b/Examples/javascript/variables/runme.js
    @@ -0,0 +1,68 @@
    +var example = require("example");
    +
    +// Try to set the values of some global variables
    +example.ivar   =  42;
    +example.svar   = -31000;
    +example.lvar   =  65537;
    +example.uivar  =  123456;
    +example.usvar  =  61000;
    +example.ulvar  =  654321;
    +example.scvar  =  -13;
    +example.ucvar  =  251;
    +example.cvar   =  "S";
    +example.fvar   =  3.14159;
    +example.dvar   =  2.1828;
    +example.strvar =  "Hello World";
    +example.iptrvar= example.new_int(37);
    +example.ptptr  = example.new_Point(37,42);
    +example.name   = "Bill";
    +
    +// Now console.log out the values of the variables
    +console.log("Variables (values printed from Javascript)");
    +console.log("ivar      = " + example.ivar);
    +console.log("svar      = " + example.svar);
    +console.log("lvar      = " + example.lvar);
    +console.log("uivar     = " + example.uivar);
    +console.log("usvar     = " + example.usvar);
    +console.log("ulvar     = " + example.ulvar);
    +console.log("scvar     = " + example.scvar);
    +console.log("ucvar     = " + example.ucvar);
    +console.log("fvar      = " + example.fvar);
    +console.log("dvar      = " + example.dvar);
    +console.log("cvar      = " + example.cvar);
    +console.log("strvar    = " + example.strvar);
    +console.log("cstrvar   = " + example.cstrvar);
    +console.log("iptrvar   = " + example.iptrvar);
    +console.log("name      = " + example.name);
    +console.log("ptptr     = " + example.ptptr + ": " + example.Point_print(example.ptptr));
    +console.log("pt        = " + example.pt + ": " + example.Point_print(example.pt));
    +
    +
    +console.log("\nVariables (values printed from C)");
    +
    +example.print_vars();
    +
    +console.log("\nNow I'm going to try and modify some read only variables");
    +
    +console.log("Tring to set 'path'");
    +try{
    +    example.path = "Whoa!";
    +    console.log("Hey, what's going on?!?! This shouldn't work");
    +}
    +catch(e){
    +    console.log("Good.");
    +}
    +
    +console.log("Trying to set 'status'");
    +try{
    +    example.status = 0;
    +    console.log("Hey, what's going on?!?! This shouldn't work");
    +} catch(e){
    +    console.log("Good.");
    +}
    +
    +console.log("\nI'm going to try and update a structure variable.");
    +example.pt = example.ptptr;
    +console.log("The new value is: ");
    +example.pt_print();
    +console.log("You should see the value: " + example.Point_print(example.ptptr));
    diff --git a/Examples/lua/arrays/Makefile b/Examples/lua/arrays/Makefile
    index bb9cf0b3b..70de9c453 100644
    --- a/Examples/lua/arrays/Makefile
    +++ b/Examples/lua/arrays/Makefile
    @@ -1,18 +1,22 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    -
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       = example.c
    +TARGET     = example
    +INTERFACE  = example.i
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/arrays/example.c b/Examples/lua/arrays/example.c
    index 56c7b19d9..da1bd755a 100644
    --- a/Examples/lua/arrays/example.c
    +++ b/Examples/lua/arrays/example.c
    @@ -1,25 +1,25 @@
    -/* File : example.c */
    -
    -#include 
    -
    -/* we are using the qsort function, which needs a helper function to sort */
    -int compare_int(const void * a, const void * b)
    -{
    -  return ( *(int*)a - *(int*)b );
    -}
    -
    -void sort_int(int* arr, int len)
    -{
    -  qsort(arr, len, sizeof(int), compare_int);
    -}
    -
    -// ditto doubles
    -int compare_double(const void * a, const void * b)
    -{
    -  return (int)( *(double*)a - *(double*)b );
    -}
    -
    -void sort_double(double* arr, int len)
    -{
    -  qsort(arr, len, sizeof(double), compare_double);
    -}
    +/* File : example.c */
    +
    +#include 
    +
    +/* we are using the qsort function, which needs a helper function to sort */
    +int compare_int(const void * a, const void * b)
    +{
    +  return ( *(int*)a - *(int*)b );
    +}
    +
    +void sort_int(int* arr, int len)
    +{
    +  qsort(arr, len, sizeof(int), compare_int);
    +}
    +
    +/* ditto doubles */
    +int compare_double(const void * a, const void * b)
    +{
    +  return (int)( *(double*)a - *(double*)b );
    +}
    +
    +void sort_double(double* arr, int len)
    +{
    +  qsort(arr, len, sizeof(double), compare_double);
    +}
    diff --git a/Examples/lua/arrays/example.i b/Examples/lua/arrays/example.i
    index 197a5a21b..3d5b60dc6 100644
    --- a/Examples/lua/arrays/example.i
    +++ b/Examples/lua/arrays/example.i
    @@ -1,42 +1,42 @@
    -/* File : example.i */
    -%module example
    -
    -/* in this file there are two sorting functions
    -and three different ways to wrap them.
    -
    -See the lua code for how they are called
    -*/
    -
    -%include     // array helpers
    -
    -// this declares a batch of function for manipulating C integer arrays
    -%array_functions(int,int)
    -
    -// 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
    -%luacode {
    -function example.sort_int2(t)
    - local len=table.maxn(t) -- the len
    - 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
    - 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
    - end
    - example.delete_int(arr) -- must delete it
    -end
    -}
    -
    -// this way uses the SWIG-Lua typemaps to do the conversion for us
    -// the %apply command states to apply this wherever the argument signature matches
    -%include 
    -%apply (double *INOUT,int) {(double* arr,int len)};
    -
    -%inline %{
    -extern void sort_int(int* arr, int len);
    -extern void sort_double(double* arr, int len);
    -%}
    \ No newline at end of file
    +/* File : example.i */
    +%module example
    +
    +/* in this file there are two sorting functions
    +and three different ways to wrap them.
    +
    +See the lua code for how they are called
    +*/
    +
    +%include     // array helpers
    +
    +// this declares a batch of function for manipulating C integer arrays
    +%array_functions(int,int)
    +
    +// 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
    +%luacode {
    +function example.sort_int2(t)
    + local len=table.maxn(t) -- the len
    + 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
    + 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
    + end
    + example.delete_int(arr) -- must delete it
    +end
    +}
    +
    +// this way uses the SWIG-Lua typemaps to do the conversion for us
    +// the %apply command states to apply this wherever the argument signature matches
    +%include 
    +%apply (double *INOUT,int) {(double* arr,int len)};
    +
    +%inline %{
    +extern void sort_int(int* arr, int len);
    +extern void sort_double(double* arr, int len);
    +%}
    diff --git a/Examples/lua/arrays/runme.lua b/Examples/lua/arrays/runme.lua
    index b0f5cfc96..d0aa99813 100644
    --- a/Examples/lua/arrays/runme.lua
    +++ b/Examples/lua/arrays/runme.lua
    @@ -1,74 +1,74 @@
    ----- importing ----
    -if string.sub(_VERSION,1,7)=='Lua 5.0' then
    -	-- lua5.0 doesnt have a nice way to do this
    -	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    -	assert(lib)()
    -else
    -	-- lua 5.1 does
    -	require('example')
    -end
    -
    --- a helper to print a Lua table
    -function print_table(t)
    -    print(table.concat(t,","))
    -end
    -
    --- a helper to print a C array
    -function print_array(arr,len)
    -    for i=0,len-1 do
    -        io.write(example.int_getitem(arr,i),",")
    -    end
    -    io.write("\n")
    -end
    -
    -math.randomseed(0)  -- init random
    -
    -
    ---[[ version 1: passing a C array to the code
    -lets test call sort_int()
    -this requires a C array, so is the hardest to use]]
    -ARRAY_SIZE=10
    -arr=example.new_int(ARRAY_SIZE)
    -for i=0,ARRAY_SIZE-1 do
    -    example.int_setitem(arr,i,math.random(1000))
    -end
    -print "unsorted"
    -print_array(arr,ARRAY_SIZE)
    -example.sort_int(arr,ARRAY_SIZE)
    -print "sorted"
    -print_array(arr,ARRAY_SIZE)
    -example.delete_int(arr) -- must delete it
    -print ""
    -
    ---[[ version 2: using %luacode to write a helper
    -a simpler way is to use a %luacode
    -which is a lua function added into the module
    -this can do the conversion for us
    -so we can just add a lua table directly
    -(what we do is move the lua code into the module instead)
    -]]
    -t={}
    -for i=1,ARRAY_SIZE do
    -    t[i]=math.random(1000)
    -end
    -print "unsorted"
    -print_table(t)
    -example.sort_int2(t) -- calls lua helper which then calls C
    -print "sorted"
    -print_table(t)
    -print ""
    -
    ---[[ version 3: use a typemap
    -this is the best way
    -it uses the SWIG-Lua typemaps to do the work
    -one item of note: the typemap creates a copy, rather than edit-in-place]]
    -t={}
    -for i=1,ARRAY_SIZE do
    -    t[i]=math.random(1000)/10
    -end
    -print "unsorted"
    -print_table(t)
    -t=example.sort_double(t) -- replace t with the result
    -print "sorted"
    -print_table(t)
    -
    +---- importing ----
    +if string.sub(_VERSION,1,7)=='Lua 5.0' then
    +	-- lua5.0 doesnt have a nice way to do this
    +	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    +	assert(lib)()
    +else
    +	-- lua 5.1 does
    +	require('example')
    +end
    +
    +-- a helper to print a Lua table
    +function print_table(t)
    +    print(table.concat(t,","))
    +end
    +
    +-- a helper to print a C array
    +function print_array(arr,len)
    +    for i=0,len-1 do
    +        io.write(example.int_getitem(arr,i),",")
    +    end
    +    io.write("\n")
    +end
    +
    +math.randomseed(0)  -- init random
    +
    +
    +--[[ version 1: passing a C array to the code
    +let's test call sort_int()
    +this requires a C array, so is the hardest to use]]
    +ARRAY_SIZE=10
    +arr=example.new_int(ARRAY_SIZE)
    +for i=0,ARRAY_SIZE-1 do
    +    example.int_setitem(arr,i,math.random(1000))
    +end
    +print "unsorted"
    +print_array(arr,ARRAY_SIZE)
    +example.sort_int(arr,ARRAY_SIZE)
    +print "sorted"
    +print_array(arr,ARRAY_SIZE)
    +example.delete_int(arr) -- must delete it
    +print ""
    +
    +--[[ version 2: using %luacode to write a helper
    +a simpler way is to use a %luacode
    +which is a lua function added into the module
    +this can do the conversion for us
    +so we can just add a lua table directly
    +(what we do is move the lua code into the module instead)
    +]]
    +t={}
    +for i=1,ARRAY_SIZE do
    +    t[i]=math.random(1000)
    +end
    +print "unsorted"
    +print_table(t)
    +example.sort_int2(t) -- calls lua helper which then calls C
    +print "sorted"
    +print_table(t)
    +print ""
    +
    +--[[ version 3: use a typemap
    +this is the best way
    +it uses the SWIG-Lua typemaps to do the work
    +one item of note: the typemap creates a copy, rather than edit-in-place]]
    +t={}
    +for i=1,ARRAY_SIZE do
    +    t[i]=math.random(1000)/10
    +end
    +print "unsorted"
    +print_table(t)
    +t=example.sort_double(t) -- replace t with the result
    +print "sorted"
    +print_table(t)
    +
    diff --git a/Examples/lua/check.list b/Examples/lua/check.list
    index 6862e4478..87dfdcd08 100644
    --- a/Examples/lua/check.list
    +++ b/Examples/lua/check.list
    @@ -11,6 +11,7 @@ funcptr3
     functest
     functor
     import
    +nspace
     owner
     pointer
     simple
    diff --git a/Examples/lua/class/Makefile b/Examples/lua/class/Makefile
    index 44888f66f..dd78fdbe9 100644
    --- a/Examples/lua/class/Makefile
    +++ b/Examples/lua/class/Makefile
    @@ -1,19 +1,23 @@
     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
     LIBS       = -lm
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/class/example.cxx b/Examples/lua/class/example.cxx
    index 1e8e203dd..046304519 100644
    --- a/Examples/lua/class/example.cxx
    +++ b/Examples/lua/class/example.cxx
    @@ -1,4 +1,4 @@
    -/* File : example.c */
    +/* File : example.cxx */
     
     #include "example.h"
     #define M_PI 3.14159265358979323846
    @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) {
     
     int Shape::nshapes = 0;
     
    -double Circle::area(void) {
    +double Circle::area() {
       return M_PI*radius*radius;
     }
     
    -double Circle::perimeter(void) {
    +double Circle::perimeter() {
       return 2*M_PI*radius;
     }
     
    -double Square::area(void) {
    +double Square::area() {
       return width*width;
     }
     
    -double Square::perimeter(void) {
    +double Square::perimeter() {
       return 4*width;
     }
    diff --git a/Examples/lua/class/example.h b/Examples/lua/class/example.h
    index 46d901361..0dff185b2 100644
    --- a/Examples/lua/class/example.h
    +++ b/Examples/lua/class/example.h
    @@ -7,11 +7,11 @@ public:
       }
       virtual ~Shape() {
         nshapes--;
    -  };
    -  double  x, y;   
    +  }
    +  double  x, y;
       void    move(double dx, double dy);
    -  virtual double area(void) = 0;
    -  virtual double perimeter(void) = 0;
    +  virtual double area() = 0;
    +  virtual double perimeter() = 0;
       static  int nshapes;
     };
     
    @@ -19,21 +19,16 @@ class Circle : public Shape {
     private:
       double radius;
     public:
    -  Circle(double r) : radius(r) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    +  Circle(double r) : radius(r) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
     
     class Square : public Shape {
     private:
       double width;
     public:
    -  Square(double w) : width(w) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    +  Square(double w) : width(w) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
    -
    -
    -
    -
    -  
    diff --git a/Examples/lua/class/example.i b/Examples/lua/class/example.i
    index 75700b305..fbdf7249f 100644
    --- a/Examples/lua/class/example.i
    +++ b/Examples/lua/class/example.i
    @@ -7,4 +7,3 @@
     
     /* Let's just grab the original header file here */
     %include "example.h"
    -
    diff --git a/Examples/lua/class/runme.lua b/Examples/lua/class/runme.lua
    index 2c3ad8ced..5d140defe 100644
    --- a/Examples/lua/class/runme.lua
    +++ b/Examples/lua/class/runme.lua
    @@ -53,7 +53,6 @@ print("\nGuess I'll clean up now")
     -- Note: this invokes the virtual destructor
     c=nil
     s=nil
    -s = 3
     
     -- call gc to make sure they are collected
     collectgarbage()
    diff --git a/Examples/lua/constants/Makefile b/Examples/lua/constants/Makefile
    index 4204545b8..979dc7d45 100644
    --- a/Examples/lua/constants/Makefile
    +++ b/Examples/lua/constants/Makefile
    @@ -1,19 +1,23 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    =
     TARGET     = example
     INTERFACE  = example.i
    -LIBS       = 
    +LIBS       =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/dual/Makefile b/Examples/lua/dual/Makefile
    index b4e28f331..53b28b645 100644
    --- a/Examples/lua/dual/Makefile
    +++ b/Examples/lua/dual/Makefile
    @@ -1,21 +1,27 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
     TARGET     = dual
    -CXXSRCS    = example2_wrap.cxx
    +GENCXXSRCS = example2_wrap.cxx
     INTERFACE  = dual.i
     LUA_INTERP = dual.cpp
     
     # This is a little different to normal as we need to static link two modules and a custom interpreter
     # We need the external runtime, then swig examples2, and build the module as normal
    -all::
    -	$(SWIG) -lua -external-runtime
    -	$(SWIG) -c++ -lua $(SWIGOPT) example2.i
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run
    +
    +build:
    +	$(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::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -	rm -f swigluarun.h
    -
    -check: all
    -
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    +	rm -f swigluarun.h $(TARGET)
    diff --git a/Examples/lua/dual/dual.cpp b/Examples/lua/dual/dual.cpp
    index d2a9ecaa9..2108a7275 100644
    --- a/Examples/lua/dual/dual.cpp
    +++ b/Examples/lua/dual/dual.cpp
    @@ -1,7 +1,7 @@
     /*
    -dual.cpp a test for multiple modules and multiple intrepreters staticly linked together.
    +dual.cpp a test for multiple modules and multiple interpreters statically linked together.
     
    -Earlier version of lua bindings for SWIG would fail if staticly linked.
    +Earlier version of lua bindings for SWIG would fail if statically linked.
     
     What is happening is as follows:
     example.i declares a type Foo
    @@ -28,7 +28,7 @@ both Foo and Bar.
     #include 
     #include 
     
    -// the 2 libraries which are wrappered via SWIG
    +// the 2 libraries which are wrapped via SWIG
     extern "C" int luaopen_example(lua_State*L);
     extern "C" int luaopen_example2(lua_State*L);
     
    @@ -36,19 +36,23 @@ extern "C" int luaopen_example2(lua_State*L);
     #define DEBUG2(X,Y) {printf(X,Y);fflush(stdout);}
     #define DEBUG3(X,Y,Z) {printf(X,Y,Z);fflush(stdout);}
     
    +#if LUA_VERSION_NUM > 501
    +#define lua_open luaL_newstate
    +#endif
    +
     void testModule(lua_State *L)
     {
       swig_type_info *pTypeInfo=0,*pTypeInfo2=0;
       swig_module_info *pModule=0;
       pModule=SWIG_GetModule(L);
    -  DEBUG2("  SWIG_GetModule() returns %p\n",pModule)
    +  DEBUG2("  SWIG_GetModule() returns %p\n", (void *)pModule)
       if(pModule==0) return;
       pTypeInfo = SWIG_TypeQuery(L,"Foo *");
       DEBUG2("  Type (Foo*) is %s\n",pTypeInfo==0?"unknown":"known");
    -  DEBUG3("    Module %p typeinfo(Foo*) %p\n",pModule,pTypeInfo);
    +  DEBUG3("    Module %p typeinfo(Foo*) %p\n", (void *)pModule, (void *)pTypeInfo);
       pTypeInfo2 = SWIG_TypeQuery(L,"Bar *");
       DEBUG2("  Type (Bar*) is %s\n",pTypeInfo2==0?"unknown":"known");
    -  DEBUG3("    Module %p typeinfo(Bar*) %p\n",pModule,pTypeInfo2);
    +  DEBUG3("    Module %p typeinfo(Bar*) %p\n", (void *)pModule, (void *)pTypeInfo2);
     }
     
     int main(int argc,char* argv[])
    diff --git a/Examples/lua/embed/Makefile b/Examples/lua/embed/Makefile
    index 51d0e6180..7f4054492 100644
    --- a/Examples/lua/embed/Makefile
    +++ b/Examples/lua/embed/Makefile
    @@ -1,18 +1,22 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
     TARGET     = embed
    -SRCS      = example.c
    +SRCS       = example.c
     INTERFACE  = example.i
     LUA_INTERP = embed.c
    +LIBS       = -lm
     
     # this is a little different to normal as we have our own special interpreter
     # which we want to static link
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +build:
    +	$(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:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    +	rm -f $(TARGET)
    diff --git a/Examples/lua/embed/embed.c b/Examples/lua/embed/embed.c
    index 55ea099be..1f10cc8e8 100644
    --- a/Examples/lua/embed/embed.c
    +++ b/Examples/lua/embed/embed.c
    @@ -1,85 +1,94 @@
    -/* embed.c a simple test for an embeded interpreter
    - 
    -The idea is that we wrapper a few simple function (example.c)
    -and write our own app to call it.
    - 
    -What it will do is load the wrappered lib, load runme.lua and then call some functions.
    -To make life easier, all the printf's have either [C] or [Lua] at the start
    -so you can see where they are coming from.
    - 
    -We will be using the luaL_dostring()/lua_dostring() function to call into lua 
    - 
    -*/
    -
    -#include 
    -#include 
    -
    -#include 
    -#include 
    -#include 
    -
    -/* the SWIG wrappered library */
    -extern int luaopen_example(lua_State*L);
    -
    -/* a really simple way of calling lua from C
    - just give it a lua state & a string to execute
    -Unfortunately lua keeps changing its API's.
    -In lua 5.0.X its lua_dostring()
    -In lua 5.1.X its luaL_dostring()
    -so we have a few extra compiles
    -*/
    -int dostring(lua_State *L, char* str) {
    -  int ok;
    -#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501))
    -
    -  ok=luaL_dostring(L,str);	/* looks like this is lua 5.1.X or later, good */
    -#else
    -
    -  ok=lua_dostring(L,str);	/* might be lua 5.0.x, using lua_dostring */
    -#endif
    -
    -  if (ok!=0)
    -    printf("[C] ERROR in dostring: %s\n",lua_tostring(L,-1));
    -  return ok;
    -}
    -
    -
    -int main(int argc,char* argv[]) {
    -  lua_State *L;
    -  int ok;
    -  printf("[C] Welcome to the simple embedded lua example\n");
    -  printf("[C] We are in C\n");
    -  printf("[C] opening a lua state & loading the libraries\n");
    -  L=lua_open();
    -  luaopen_base(L);
    -  luaopen_string(L);
    -  luaopen_math(L);
    -  printf("[C] now loading the SWIG wrappered library\n");
    -  luaopen_example(L);
    -  printf("[C] all looks ok\n");
    -  printf("\n");
    -  printf("[C] lets load the file 'runme.lua'\n");
    -  printf("[C] any lua code in this file will be executed\n");
    -  if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {
    -    printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
    -    exit(3);
    -  }
    -  printf("[C] We are now back in C, all looks ok\n");
    -  printf("\n");
    -  printf("[C] lets call the function 'do_tests()'\n");
    -  ok=dostring(L,"do_tests()");
    -  printf("[C] We are back in C, the dostring() function returned %d\n",ok);
    -  printf("\n");
    -  printf("[C] Lets call lua again, but create an error\n");
    -  ok=dostring(L,"no_such_function()");
    -  printf("[C] We are back in C, the dostring() function returned %d\n",ok);
    -  printf("[C] it should also have returned 1 and printed an error message\n");
    -  printf("\n");
    -  printf("[C] Lets call lua again, calling the greeting function\n");
    -  ok=dostring(L,"call_greeting()");
    -  printf("[C] This was C=>Lua=>C (getting a bit complex)\n");
    -  printf("\n");
    -  printf("[C] all finished, closing the lua state\n");
    -  lua_close(L);
    -  return 0;
    -}
    +/* embed.c a simple test for an embedded interpreter
    + 
    +The idea is that we wrapper a few simple function (example.c)
    +and write our own app to call it.
    + 
    +What it will do is load the wrapped lib, load runme.lua and then call some functions.
    +To make life easier, all the printf's have either [C] or [Lua] at the start
    +so you can see where they are coming from.
    + 
    +We will be using the luaL_dostring()/lua_dostring() function to call into lua 
    + 
    +*/
    +
    +#include 
    +#include 
    +#include 
    +
    +#include 
    +#include 
    +#include 
    +
    +#if LUA_VERSION_NUM > 501
    +#define lua_open luaL_newstate
    +#endif
    +
    +/* the SWIG wrappered library */
    +extern int luaopen_example(lua_State*L);
    +
    +/* a really simple way of calling lua from C
    + just give it a lua state & a string to execute
    +Unfortunately lua keeps changing its API's.
    +In lua 5.0.X it's lua_dostring()
    +In lua 5.1.X it's luaL_dostring()
    +so we have a few extra compiles
    +*/
    +int dostring(lua_State *L, char* str) {
    +  int ok;
    +#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501))
    +
    +  ok=luaL_dostring(L,str);	/* looks like this is lua 5.1.X or later, good */
    +#else
    +
    +  ok=lua_dostring(L,str);	/* might be lua 5.0.x, using lua_dostring */
    +#endif
    +
    +  if (ok!=0)
    +    printf("[C] ERROR in dostring: %s\n",lua_tostring(L,-1));
    +  return ok;
    +}
    +
    +
    +int main(int argc,char* argv[]) {
    +  lua_State *L;
    +  int ok;
    +  printf("[C] Welcome to the simple embedded lua example\n");
    +  printf("[C] We are in C\n");
    +  printf("[C] opening a lua state & loading the libraries\n");
    +  L=lua_open();
    +  luaopen_base(L);
    +  luaopen_string(L);
    +  luaopen_math(L);
    +  printf("[C] now loading the SWIG wrapped library\n");
    +  luaopen_example(L);
    +  printf("[C] all looks ok\n");
    +  printf("\n");
    +  if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) {
    +    printf("[C] ERROR: no lua file given on command line\n");
    +    exit(3);
    +  }
    +  printf("[C] let's load the file '%s'\n", argv[1]);
    +  printf("[C] any lua code in this file will be executed\n");
    +  if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) {
    +    printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
    +    exit(3);
    +  }
    +  printf("[C] We are now back in C, all looks ok\n");
    +  printf("\n");
    +  printf("[C] let's call the function 'do_tests()'\n");
    +  ok=dostring(L,"do_tests()");
    +  printf("[C] We are back in C, the dostring() function returned %d\n",ok);
    +  printf("\n");
    +  printf("[C] Let's call lua again, but create an error\n");
    +  ok=dostring(L,"no_such_function()");
    +  printf("[C] We are back in C, the dostring() function returned %d\n",ok);
    +  printf("[C] it should also have returned 1 and printed an error message\n");
    +  printf("\n");
    +  printf("[C] Let's call lua again, calling the greeting function\n");
    +  ok=dostring(L,"call_greeting()");
    +  printf("[C] This was C=>Lua=>C (getting a bit complex)\n");
    +  printf("\n");
    +  printf("[C] all finished, closing the lua state\n");
    +  lua_close(L);
    +  return 0;
    +}
    diff --git a/Examples/lua/embed/example.c b/Examples/lua/embed/example.c
    index c6c6d7ba1..efd13f662 100644
    --- a/Examples/lua/embed/example.c
    +++ b/Examples/lua/embed/example.c
    @@ -1,22 +1,22 @@
    -/* File : example.c */
    -
    -#include 
    -
    -/* A global variable */
    -double Foo = 3.0;
    -
    -/* Compute the greatest common divisor of positive integers */
    -int gcd(int x, int y) {
    -  int g;
    -  g = y;
    -  while (x > 0) {
    -    g = x;
    -    x = y % x;
    -    y = g;
    -  }
    -  return g;
    -}
    -
    -void greeting() {
    -  printf("Hello from the C function 'greeting'\n");
    -}
    +/* File : example.c */
    +
    +#include 
    +
    +/* A global variable */
    +double Foo = 3.0;
    +
    +/* Compute the greatest common divisor of positive integers */
    +int gcd(int x, int y) {
    +  int g;
    +  g = y;
    +  while (x > 0) {
    +    g = x;
    +    x = y % x;
    +    y = g;
    +  }
    +  return g;
    +}
    +
    +void greeting() {
    +  printf("Hello from the C function 'greeting'\n");
    +}
    diff --git a/Examples/lua/embed/runme.lua b/Examples/lua/embed/runme.lua
    index e02fd1d55..a75f74000 100644
    --- a/Examples/lua/embed/runme.lua
    +++ b/Examples/lua/embed/runme.lua
    @@ -1,7 +1,7 @@
     print "[lua] This is runme.lua"
    --- test program for embeded lua
    --- we do not need to load the library, as it was already in the intrepreter
    --- but lets check anyway
    +-- test program for embedded lua
    +-- we do not need to load the library, as it was already in the interpreter
    +-- but let's check anyway
     assert(type(example)=='table',"Don't appear to have loaded the example module")
     
     -- a test function to run the tests
    diff --git a/Examples/lua/embed2/Makefile b/Examples/lua/embed2/Makefile
    index 5f267d94d..28d9682b4 100644
    --- a/Examples/lua/embed2/Makefile
    +++ b/Examples/lua/embed2/Makefile
    @@ -1,18 +1,22 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
     TARGET     = embed2
    -SRCS      = example.c
    +SRCS       = example.c
     INTERFACE  = example.i
     LUA_INTERP = embed2.c
    +LIBS       = -lm
     
     # this is a little different to normal as we have our own special interpreter
     # which we want to static link
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +build:
    +	$(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:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    +	rm -f $(TARGET)
    diff --git a/Examples/lua/embed2/embed2.c b/Examples/lua/embed2/embed2.c
    index dac527eb4..0ce9f8f7f 100644
    --- a/Examples/lua/embed2/embed2.c
    +++ b/Examples/lua/embed2/embed2.c
    @@ -1,233 +1,240 @@
    -/* embed2.c some more test for an embeded interpreter
    - 
    -This will go a bit further as it will pass values to and from the lua code.
    -It uses less of the SWIG code, and more of the raw lua API's
    - 
    -What it will do is load the wrappered lib, load runme.lua and then call some functions.
    -To make life easier, all the printf's have either [C] or [Lua] at the start
    -so you can see where they are coming from.
    - 
    -We will be using the luaL_dostring()/lua_dostring() function to call into lua 
    - 
    -*/
    -
    -/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
    -#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
    -# define _CRT_SECURE_NO_DEPRECATE
    -#endif
    -
    -/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
    -#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
    -# define _SCL_SECURE_NO_DEPRECATE
    -#endif
    -
    -
    -#include 
    -#include 
    -
    -#include 
    -#include 
    -#include 
    -#include 
    -#include 
    -
    -
    -/* the SWIG wrappered library */
    -extern int luaopen_example(lua_State*L);
    -
    -/* This is an example of how to call the Lua function
    -    int add(int,int) 
    -  its very tedious, but gives you an idea of the issues involded.
    -  (look below for a better idea)
    -*/
    -int call_add(lua_State *L,int a,int b,int* res) {
    -  int top;
    -  /* ok, here we go:
    -  push a, push b, call 'add' check & return res
    -  */
    -  top=lua_gettop(L);  /* for later */
    -  lua_pushstring(L, "add");                                  /* function name */
    -  lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */
    -  if (!lua_isfunction(L,-1)) {
    -    printf("[C] error: cannot find function 'add'\n");
    -    lua_settop(L,top);  // reset
    -    return 0;
    -  }
    -  lua_pushnumber(L,a);
    -  lua_pushnumber(L,b);
    -  if (lua_pcall(L, 2, 1, 0) != 0)  /* call function with 2 arguments and 1 result */
    -  {
    -    printf("[C] error running function `add': %s\n",lua_tostring(L, -1));
    -    lua_settop(L,top);  // reset
    -    return 0;
    -  }
    -  // check results
    -  if (!lua_isnumber(L,-1)) {
    -    printf("[C] error: returned value is not a number\n");
    -    lua_settop(L,top);  // reset
    -    return 0;
    -  }
    -  *res=(int)lua_tonumber(L,-1);
    -  lua_settop(L,top);  /* reset stack */
    -  return 1;   // ok
    -}
    -
    -/* This is a variargs call function for calling from C into Lua.
    -Original Code from Programming in Lua (PIL) by Roberto Ierusalimschy
    -ISBN 85-903798-1-7 
    -http://www.lua.org/pil/25.3.html
    -This has been modified slightly to make it compile, and its still a bit rough.
    -But it gives the idea of how to make it work.
    -*/
    -int call_va (lua_State *L,const char *func, const char *sig, ...) {
    -  va_list vl;
    -  int narg, nres;  /* number of arguments and results */
    -  int top;
    -  top=lua_gettop(L);  /* for later */
    -
    -  va_start(vl, sig);
    -  lua_getglobal(L, func);  /* get function */
    -
    -  /* push arguments */
    -  narg = 0;
    -  while (*sig) {  /* push arguments */
    -    switch (*sig++) {
    -
    -    case 'd':  /* double argument */
    -      lua_pushnumber(L, va_arg(vl, double));
    -      break;
    -
    -    case 'i':  /* int argument */
    -      lua_pushnumber(L, va_arg(vl, int));
    -      break;
    -
    -    case 's':  /* string argument */
    -      lua_pushstring(L, va_arg(vl, char *));
    -      break;
    -
    -    case '>':
    -      goto endwhile;
    -
    -    default:
    -      printf("invalid option (%c)\n", *(sig - 1));
    -      goto fail;
    -    }
    -    narg++;
    -    /* do we need this?*/
    -    /* luaL_checkstack(L, 1, "too many arguments"); */
    -  }
    -endwhile:
    -
    -  /* do the call */
    -  nres = (int)strlen(sig);  /* number of expected results */
    -  if (lua_pcall(L, narg, nres, 0) != 0)  /* do the call */
    -  {
    -    printf("error running function `%s': %s\n",func, lua_tostring(L, -1));
    -    goto fail;
    -  }
    -
    -  /* retrieve results */
    -  nres = -nres;  /* stack index of first result */
    -  while (*sig) {  /* get results */
    -    switch (*sig++) {
    -
    -    case 'd':  /* double result */
    -      if (!lua_isnumber(L, nres)) {
    -        printf("wrong result type\n");
    -        goto fail;
    -      }
    -      *va_arg(vl, double *) = lua_tonumber(L, nres);
    -      break;
    -
    -    case 'i':  /* int result */
    -      if (!lua_isnumber(L, nres)) {
    -        printf("wrong result type\n");
    -        goto fail;
    -      }
    -      *va_arg(vl, int *) = (int)lua_tonumber(L, nres);
    -      break;
    -
    -    case 's':  /* string result */
    -      if (!lua_isstring(L, nres)) {
    -        printf("wrong result type\n");
    -        goto fail;
    -      }
    -      strcpy(va_arg(vl, char *),lua_tostring(L, nres));/* WARNING possible buffer overflow */
    -      break;
    -
    -    default: {
    -        printf("invalid option (%c)", *(sig - 1));
    -        goto fail;
    -      }
    -    }
    -    nres++;
    -  }
    -  va_end(vl);
    -
    -  lua_settop(L,top);  /* reset stack */
    -  return 1; /* ok */
    -fail:
    -  lua_settop(L,top);  /* reset stack */
    -  return 0;   /* error */
    -}
    -
    -int main(int argc,char* argv[]) {
    -  lua_State *L;
    -  int ok;
    -  int res;
    -  char str[80];
    -  printf("[C] Welcome to the simple embedded Lua example v2\n");
    -  printf("[C] We are in C\n");
    -  printf("[C] opening a Lua state & loading the libraries\n");
    -  L=lua_open();
    -  luaopen_base(L);
    -  luaopen_string(L);
    -  luaopen_math(L);
    -  printf("[C] now loading the SWIG wrappered library\n");
    -  luaopen_example(L);
    -  printf("[C] all looks ok\n");
    -  printf("\n");
    -  printf("[C] lets load the file 'runme.lua'\n");
    -  printf("[C] any lua code in this file will be executed\n");
    -  if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {
    -    printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
    -    exit(3);
    -  }
    -  printf("[C] We are now back in C, all looks ok\n");
    -  printf("\n");
    -  printf("[C] lets call the Lua function 'add(1,1)'\n");
    -  printf("[C] using the C function 'call_add'\n");
    -  ok=call_add(L,1,1,&res);
    -  printf("[C] the function returned %d with value %d\n",ok,res);
    -  printf("\n");
    -  printf("[C] lets do this rather easier\n");
    -  printf("[C] we will call the same Lua function using a generic C function 'call_va'\n");
    -  ok=call_va(L,"add","ii>i",1,1,&res);
    -  printf("[C] the function returned %d with value %d\n",ok,res);
    -  printf("\n");
    -  printf("[C] we will now use the same generic C function to call 'append(\"cat\",\"dog\")'\n");
    -  ok=call_va(L,"append","ss>s","cat","dog",str);
    -  printf("[C] the function returned %d with value %s\n",ok,str);
    -  printf("\n");
    -  printf("[C] we can also make some bad calls to ensure the code doesn't fail\n");
    -  printf("[C] calling adds(1,2)\n");
    -  ok=call_va(L,"adds","ii>i",1,2,&res);
    -  printf("[C] the function returned %d with value %d\n",ok,res);
    -  printf("[C] calling add(1,'fred')\n");
    -  ok=call_va(L,"add","is>i",1,"fred",&res);
    -  printf("[C] the function returned %d with value %d\n",ok,res);
    -  printf("\n");
    -  printf("[C] Note: no protection if you mess up the va-args, this is C\n");
    -  printf("\n");
    -  printf("[C] Finally we will call the wrappered gcd function gdc(6,9):\n");
    -  printf("[C] This will pass the values to Lua, then call the wrappered function\n");
    -  printf("    Which will get the values from Lua, call the C code \n");
    -  printf("    and return the value to Lua and eventually back to C\n");
    -  printf("[C] Certainly not the best way to do it :-)\n");
    -  ok=call_va(L,"gcd","ii>i",6,9,&res);
    -  printf("[C] the function returned %d with value %d\n",ok,res);
    -  printf("\n");
    -  printf("[C] all finished, closing the lua state\n");
    -  lua_close(L);
    -  return 0;
    -}
    +/* embed2.c some more tests for an embedded interpreter
    + 
    +This will go a bit further as it will pass values to and from the lua code.
    +It uses less of the SWIG code, and more of the raw lua API's
    + 
    +What it will do is load the wrapped lib, load runme.lua and then call some functions.
    +To make life easier, all the printf's have either [C] or [Lua] at the start
    +so you can see where they are coming from.
    + 
    +We will be using the luaL_dostring()/lua_dostring() function to call into lua 
    + 
    +*/
    +
    +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
    +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
    +# define _CRT_SECURE_NO_DEPRECATE
    +#endif
    +
    +/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
    +#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
    +# define _SCL_SECURE_NO_DEPRECATE
    +#endif
    +
    +
    +#include 
    +#include 
    +#include 
    +
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +
    +#if LUA_VERSION_NUM > 501
    +#define lua_open luaL_newstate
    +#endif
    +
    +/* the SWIG wrapped library */
    +extern int luaopen_example(lua_State*L);
    +
    +/* This is an example of how to call the Lua function
    +    int add(int,int) 
    +  its very tedious, but gives you an idea of the issues involved.
    +  (look below for a better idea)
    +*/
    +int call_add(lua_State *L,int a,int b,int* res) {
    +  int top;
    +  /* ok, here we go:
    +  push a, push b, call 'add' check & return res
    +  */
    +  top=lua_gettop(L);  /* for later */
    +  lua_getglobal(L, "add");               /* function to be called */
    +  if (!lua_isfunction(L,-1)) {
    +    printf("[C] error: cannot find function 'add'\n");
    +    lua_settop(L,top);
    +    return 0;
    +  }
    +  lua_pushnumber(L,a);
    +  lua_pushnumber(L,b);
    +  if (lua_pcall(L, 2, 1, 0) != 0)  /* call function with 2 arguments and 1 result */
    +  {
    +    printf("[C] error running function `add': %s\n",lua_tostring(L, -1));
    +    lua_settop(L,top);
    +    return 0;
    +  }
    +  /* check results */
    +  if (!lua_isnumber(L,-1)) {
    +    printf("[C] error: returned value is not a number\n");
    +    lua_settop(L,top);
    +    return 0;
    +  }
    +  *res=(int)lua_tonumber(L,-1);
    +  lua_settop(L,top);  /* reset stack */
    +  return 1;
    +}
    +
    +/* This is a variargs call function for calling from C into Lua.
    +Original Code from Programming in Lua (PIL) by Roberto Ierusalimschy
    +ISBN 85-903798-1-7 
    +http://www.lua.org/pil/25.3.html
    +This has been modified slightly to make it compile, and it's still a bit rough.
    +But it gives the idea of how to make it work.
    +*/
    +int call_va (lua_State *L,const char *func, const char *sig, ...) {
    +  va_list vl;
    +  int narg, nres;  /* number of arguments and results */
    +  int top;
    +  top=lua_gettop(L);  /* for later */
    +
    +  va_start(vl, sig);
    +  lua_getglobal(L, func);  /* get function */
    +
    +  /* push arguments */
    +  narg = 0;
    +  while (*sig) {  /* push arguments */
    +    switch (*sig++) {
    +
    +    case 'd':  /* double argument */
    +      lua_pushnumber(L, va_arg(vl, double));
    +      break;
    +
    +    case 'i':  /* int argument */
    +      lua_pushnumber(L, va_arg(vl, int));
    +      break;
    +
    +    case 's':  /* string argument */
    +      lua_pushstring(L, va_arg(vl, char *));
    +      break;
    +
    +    case '>':
    +      goto endwhile;
    +
    +    default:
    +      printf("invalid option (%c)\n", *(sig - 1));
    +      goto fail;
    +    }
    +    narg++;
    +    /* do we need this?*/
    +    /* luaL_checkstack(L, 1, "too many arguments"); */
    +  }
    +endwhile:
    +
    +  /* do the call */
    +  nres = (int)strlen(sig);  /* number of expected results */
    +  if (lua_pcall(L, narg, nres, 0) != 0)  /* do the call */
    +  {
    +    printf("error running function `%s': %s\n",func, lua_tostring(L, -1));
    +    goto fail;
    +  }
    +
    +  /* retrieve results */
    +  nres = -nres;  /* stack index of first result */
    +  while (*sig) {  /* get results */
    +    switch (*sig++) {
    +
    +    case 'd':  /* double result */
    +      if (!lua_isnumber(L, nres)) {
    +        printf("wrong result type\n");
    +        goto fail;
    +      }
    +      *va_arg(vl, double *) = lua_tonumber(L, nres);
    +      break;
    +
    +    case 'i':  /* int result */
    +      if (!lua_isnumber(L, nres)) {
    +        printf("wrong result type\n");
    +        goto fail;
    +      }
    +      *va_arg(vl, int *) = (int)lua_tonumber(L, nres);
    +      break;
    +
    +    case 's':  /* string result */
    +      if (!lua_isstring(L, nres)) {
    +        printf("wrong result type\n");
    +        goto fail;
    +      }
    +      strcpy(va_arg(vl, char *),lua_tostring(L, nres));/* WARNING possible buffer overflow */
    +      break;
    +
    +    default: {
    +        printf("invalid option (%c)", *(sig - 1));
    +        goto fail;
    +      }
    +    }
    +    nres++;
    +  }
    +  va_end(vl);
    +
    +  lua_settop(L,top);  /* reset stack */
    +  return 1; /* ok */
    +fail:
    +  lua_settop(L,top);  /* reset stack */
    +  return 0;   /* error */
    +}
    +
    +int main(int argc,char* argv[]) {
    +  lua_State *L;
    +  int ok;
    +  int res;
    +  char str[80];
    +  printf("[C] Welcome to the simple embedded Lua example v2\n");
    +  printf("[C] We are in C\n");
    +  printf("[C] opening a Lua state & loading the libraries\n");
    +  L=lua_open();
    +  luaopen_base(L);
    +  luaopen_string(L);
    +  luaopen_math(L);
    +  printf("[C] now loading the SWIG wrappered library\n");
    +  luaopen_example(L);
    +  printf("[C] all looks ok\n");
    +  printf("\n");
    +  if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) {
    +    printf("[C] ERROR: no lua file given on command line\n");
    +    exit(3);
    +  }
    +  printf("[C] let's load the file '%s'\n", argv[1]);
    +  printf("[C] any lua code in this file will be executed\n");
    +  if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) {
    +    printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
    +    exit(3);
    +  }
    +  printf("[C] We are now back in C, all looks ok\n");
    +  printf("\n");
    +  printf("[C] let's call the Lua function 'add(1,1)'\n");
    +  printf("[C] using the C function 'call_add'\n");
    +  ok=call_add(L,1,1,&res);
    +  printf("[C] the function returned %d with value %d\n",ok,res);
    +  printf("\n");
    +  printf("[C] let's do this rather easier\n");
    +  printf("[C] we will call the same Lua function using a generic C function 'call_va'\n");
    +  ok=call_va(L,"add","ii>i",1,1,&res);
    +  printf("[C] the function returned %d with value %d\n",ok,res);
    +  printf("\n");
    +  printf("[C] we will now use the same generic C function to call 'append(\"cat\",\"dog\")'\n");
    +  ok=call_va(L,"append","ss>s","cat","dog",str);
    +  printf("[C] the function returned %d with value %s\n",ok,str);
    +  printf("\n");
    +  printf("[C] we can also make some bad calls to ensure the code doesn't fail\n");
    +  printf("[C] calling adds(1,2)\n");
    +  ok=call_va(L,"adds","ii>i",1,2,&res);
    +  printf("[C] the function returned %d with value %d\n",ok,res);
    +  printf("[C] calling add(1,'fred')\n");
    +  ok=call_va(L,"add","is>i",1,"fred",&res);
    +  printf("[C] the function returned %d with value %d\n",ok,res);
    +  printf("\n");
    +  printf("[C] Note: no protection if you mess up the va-args, this is C\n");
    +  printf("\n");
    +  printf("[C] Finally we will call the wrappered gcd function gdc(6,9):\n");
    +  printf("[C] This will pass the values to Lua, then call the wrappered function\n");
    +  printf("    Which will get the values from Lua, call the C code \n");
    +  printf("    and return the value to Lua and eventually back to C\n");
    +  printf("[C] Certainly not the best way to do it :-)\n");
    +  ok=call_va(L,"gcd","ii>i",6,9,&res);
    +  printf("[C] the function returned %d with value %d\n",ok,res);
    +  printf("\n");
    +  printf("[C] all finished, closing the lua state\n");
    +  lua_close(L);
    +  return 0;
    +}
    diff --git a/Examples/lua/embed2/example.c b/Examples/lua/embed2/example.c
    index c6c6d7ba1..efd13f662 100644
    --- a/Examples/lua/embed2/example.c
    +++ b/Examples/lua/embed2/example.c
    @@ -1,22 +1,22 @@
    -/* File : example.c */
    -
    -#include 
    -
    -/* A global variable */
    -double Foo = 3.0;
    -
    -/* Compute the greatest common divisor of positive integers */
    -int gcd(int x, int y) {
    -  int g;
    -  g = y;
    -  while (x > 0) {
    -    g = x;
    -    x = y % x;
    -    y = g;
    -  }
    -  return g;
    -}
    -
    -void greeting() {
    -  printf("Hello from the C function 'greeting'\n");
    -}
    +/* File : example.c */
    +
    +#include 
    +
    +/* A global variable */
    +double Foo = 3.0;
    +
    +/* Compute the greatest common divisor of positive integers */
    +int gcd(int x, int y) {
    +  int g;
    +  g = y;
    +  while (x > 0) {
    +    g = x;
    +    x = y % x;
    +    y = g;
    +  }
    +  return g;
    +}
    +
    +void greeting() {
    +  printf("Hello from the C function 'greeting'\n");
    +}
    diff --git a/Examples/lua/embed2/runme.lua b/Examples/lua/embed2/runme.lua
    index 73af9c5f2..6e93164c0 100644
    --- a/Examples/lua/embed2/runme.lua
    +++ b/Examples/lua/embed2/runme.lua
    @@ -1,27 +1,27 @@
     print "[lua] This is runme.lua"
    --- test program for embeded lua
    --- we do not need to load the library, as it was already in the intrepreter
    --- but lets check anyway
    +-- test program for embedded lua
    +-- we do not need to load the library, as it was already in the interpreter
    +-- but let's check anyway
     assert(type(example)=='table',"Don't appear to have loaded the example module")
    -
    --- note: we will copy the functions from example table into global
    --- this will help us later
    -for k,v in pairs(example) do _G[k]=v end
     
    --- our add function
    +-- note: we will copy the functions from example table into global
    +-- this will help us later
    +for k,v in pairs(example) do _G[k]=v end
    +
    +-- our add function
     -- we will be calling this from C
    -function add(a,b)
    -    print("[lua] this is function add(",a,b,")")
    -    c=a+b
    -    print("[lua] returning",c)
    -    return c
    +function add(a,b)
    +    print("[lua] this is function add(",a,b,")")
    +    c=a+b
    +    print("[lua] returning",c)
    +    return c
     end
     
    -function append(a,b)
    -    print("[lua] this is function append(",a,b,")")
    -    c=a..b
    -    print("[lua] returning",c)
    -    return c
    +function append(a,b)
    +    print("[lua] this is function append(",a,b,")")
    +    c=a..b
    +    print("[lua] returning",c)
    +    return c
     end
     
     
    diff --git a/Examples/lua/embed3/Makefile b/Examples/lua/embed3/Makefile
    index def3528a5..d8e7c7385 100644
    --- a/Examples/lua/embed3/Makefile
    +++ b/Examples/lua/embed3/Makefile
    @@ -1,20 +1,25 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
     TARGET     = embed3
    -SRCS      = example.cpp
    +SRCS       = example.cpp
     INTERFACE  = example.i
     LUA_INTERP = embed3.cpp
     
     # this is a little different to normal as we have our own special interpreter
     # which we want to static link
     # we also need the external runtime, so we can get access to certain internals of SWIG
    -all::
    -	$(SWIG) -c++ -lua $(SWIGOPT) -external-runtime swigluarun.h
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run
    +
    +build:
    +	$(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::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    -
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    +	rm -f swigluarun.h $(TARGET)
    diff --git a/Examples/lua/embed3/embed3.cpp b/Examples/lua/embed3/embed3.cpp
    index e5e0e0a7d..9be49add3 100644
    --- a/Examples/lua/embed3/embed3.cpp
    +++ b/Examples/lua/embed3/embed3.cpp
    @@ -1,4 +1,4 @@
    -/* embed3.cpp A C++ embeded interpreter
    +/* embed3.cpp A C++ embedded interpreter
      
     This will register a C++ class with Lua, and then call a Lua function
     passing C++ objects to this function.
    @@ -26,15 +26,19 @@ extern "C" {
     #include 
     #include 
     }
    -
    -/* The SWIG external runtime is generated by using.
    -swig -lua -externalruntime swigluarun.h
    -It contains useful function used by SWIG in its wrappering
    -SWIG_TypeQuery() SWIG_NewPointerObj()
    +
    +#if LUA_VERSION_NUM > 501
    +#define lua_open luaL_newstate
    +#endif
    +
    +/* The SWIG external runtime is generated by using.
    +swig -lua -externalruntime swigluarun.h
    +It contains useful function used by SWIG in its wrapper
    +SWIG_TypeQuery() SWIG_NewPointerObj()
     */
     #include "swigluarun.h"   // the SWIG external runtime
     
    -/* the SWIG wrappered library */
    +/* the SWIG wrapped library */
     extern "C" int luaopen_example(lua_State*L);
     
     // the code itself
    @@ -65,8 +69,7 @@ int call_onEvent(lua_State *L, Event e) {
       push a, push b, call 'add' check & return res
       */
       top = lua_gettop(L);  /* for later */
    -  lua_pushstring(L, "onEvent");                                  /* function name */
    -  lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */
    +  lua_getglobal(L, "onEvent");               /* function to be called */
       if (!lua_isfunction(L, -1)) {
         printf("[C++] error: cannot find function 'OnEvent'\n");
         lua_settop(L, top);  // reset
    @@ -97,10 +100,10 @@ int main(int argc, char* argv[]) {
       luaopen_example(L);
       printf("[C++] all looks ok\n");
       printf("\n");
    -  printf("[C++] lets create an Engine and pass a pointer to Lua\n");
    +  printf("[C++] let's create an Engine and pass a pointer to Lua\n");
       Engine engine;
       /* this code will pass a pointer into lua, but C++ still owns the object
    -  this is a little tedious, to do, but lets do it
    +  this is a little tedious, to do, but let's do it
       we need to pass the pointer (obviously), the type name 
       and a flag which states if Lua should delete the pointer once its finished with it
       The type name is a class name string which is registered with SWIG
    @@ -110,16 +113,20 @@ int main(int argc, char* argv[]) {
       push_pointer(L,&engine,"Engine *",0);
       lua_setglobal(L, "pEngine");  // set as global variable
     
    -  printf("[C++] now lets load the file 'runme.lua'\n");
    +  if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) {
    +    printf("[C++] ERROR: no lua file given on command line\n");
    +    exit(3);
    +  }
    +  printf("[C++] now let's load the file '%s'\n", argv[1]);
       printf("[C++] any lua code in this file will be executed\n");
    -  if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {
    -    printf("[C++] ERROR: cannot run lua file: %s", lua_tostring(L, -1));
    +  if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) {
    +    printf("[C++] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
         exit(3);
       }
       printf("[C++] We are now back in C++, all looks ok\n");
       printf("\n");
     
    -  printf("[C++] Lets call the Lua function onEvent(e)\n");
    +  printf("[C++] Let's call the Lua function onEvent(e)\n");
       printf("[C++] We will give it different events, as we wish\n");
       printf("[C++] Starting with STARTUP\n");
       Event ev;
    diff --git a/Examples/lua/embed3/example.h b/Examples/lua/embed3/example.h
    index 41c13e9c1..df189e34b 100644
    --- a/Examples/lua/embed3/example.h
    +++ b/Examples/lua/embed3/example.h
    @@ -13,7 +13,7 @@ public:
     };
     
     
    -/* We also want to pass some events to Lua, so lets have a few classes
    +/* We also want to pass some events to Lua, so let's have a few classes
     to do this.
     */
     class Event
    diff --git a/Examples/lua/embed3/example.i b/Examples/lua/embed3/example.i
    index 032805c0e..950d2549d 100644
    --- a/Examples/lua/embed3/example.i
    +++ b/Examples/lua/embed3/example.i
    @@ -1,8 +1,8 @@
    -/* File : example.i */
    -%module example
    -
    -%{
    -#include "example.h"
    -%}
    -
    -%include "example.h"
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +%include "example.h"
    diff --git a/Examples/lua/embed3/runme.lua b/Examples/lua/embed3/runme.lua
    index 3a44bd2fc..8d5b1eada 100644
    --- a/Examples/lua/embed3/runme.lua
    +++ b/Examples/lua/embed3/runme.lua
    @@ -1,7 +1,7 @@
     print "[lua] This is runme.lua"
    --- test program for embeded lua
    --- we do not need to load the library, as it was already in the intrepreter
    --- but lets check anyway
    +-- test program for embedded lua
    +-- we do not need to load the library, as it was already in the interpreter
    +-- but let's check anyway
     
     assert(type(example)=='table',"Don't appear to have loaded the example module. Do not run this file directly, run the embed3 executable")
     
    @@ -13,12 +13,12 @@ else
     end
     
     
    --- the embed program expects a function void onEvent(Event)
    +-- the embedded program expects a function void onEvent(Event)
     -- this is it
     
     function onEvent(e)
         print("[Lua] onEvent with event",e.mType)
    -    -- lets do something with the Engine
    +    -- let's do something with the Engine
         -- nothing clever, but ...
         if e.mType==example.Event_STARTUP then
             pEngine:start()
    diff --git a/Examples/lua/exception/Makefile b/Examples/lua/exception/Makefile
    index 8657f1922..a476f0b91 100644
    --- a/Examples/lua/exception/Makefile
    +++ b/Examples/lua/exception/Makefile
    @@ -1,19 +1,23 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    =
    +TARGET     = example
    +INTERFACE  = example.i
    +LIBS       = -lm
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/exception/example.h b/Examples/lua/exception/example.h
    index 5148a5962..251ef1132 100644
    --- a/Examples/lua/exception/example.h
    +++ b/Examples/lua/exception/example.h
    @@ -1,53 +1,53 @@
    -/* File : example.h */
    -
    -#include 
    -#ifndef SWIG
    -struct A {
    -};
    -#endif
    -
    -class Exc {
    -public:
    -  Exc(int c, const char *m) {
    -    code = c;
    -    strncpy(msg,m,256);
    -  }
    -  int code;
    -  char msg[256];
    -};
    -
    -#if defined(_MSC_VER)
    -  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
    -#endif
    -
    -class Test {
    -public:
    -  int simple() throw(int&) {
    -      throw(37);
    -      return 1;
    -  }
    -  int message() throw(const char *) {
    -      throw("I died.");
    -      return 1;
    -  }
    -  int hosed() throw(Exc) {
    -      throw(Exc(42,"Hosed"));
    -      return 1;
    -  } 
    -  int unknown() throw(A*) {
    -      static A a;
    -      throw &a;
    -      return 1;
    -  }
    -  int multi(int x) throw(int, const char *, Exc) {
    -     if (x == 1) throw(37);
    -     if (x == 2) throw("Bleah!");
    -     if (x == 3) throw(Exc(42,"No-go-diggy-die"));
    -     return 1;
    -  }
    -};
    -
    -#if defined(_MSC_VER)
    -  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
    -#endif
    -
    +/* File : example.h */
    +
    +#include 
    +#ifndef SWIG
    +struct A {
    +};
    +#endif
    +
    +class Exc {
    +public:
    +  Exc(int c, const char *m) {
    +    code = c;
    +    strncpy(msg,m,256);
    +  }
    +  int code;
    +  char msg[256];
    +};
    +
    +#if defined(_MSC_VER)
    +  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
    +#endif
    +
    +class Test {
    +public:
    +  int simple() throw(int&) {
    +      throw(37);
    +      return 1;
    +  }
    +  int message() throw(const char *) {
    +      throw("I died.");
    +      return 1;
    +  }
    +  int hosed() throw(Exc) {
    +      throw(Exc(42,"Hosed"));
    +      return 1;
    +  } 
    +  int unknown() throw(A*) {
    +      static A a;
    +      throw &a;
    +      return 1;
    +  }
    +  int multi(int x) throw(int, const char *, Exc) {
    +     if (x == 1) throw(37);
    +     if (x == 2) throw("Bleah!");
    +     if (x == 3) throw(Exc(42,"No-go-diggy-die"));
    +     return 1;
    +  }
    +};
    +
    +#if defined(_MSC_VER)
    +  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
    +#endif
    +
    diff --git a/Examples/lua/exception/example.i b/Examples/lua/exception/example.i
    index 09cd9e812..6187f8eff 100644
    --- a/Examples/lua/exception/example.i
    +++ b/Examples/lua/exception/example.i
    @@ -1,17 +1,17 @@
    -/* File : example.i */
    -%module example
    -
    -%{
    -#include "example.h"
    -%}
    -
    -%include "std_string.i"
    -
    -// we want to return Exc objects to the interpreter
    -// therefore we add this typemap
    -// note: only works if Exc is copyable
    -%apply SWIGTYPE EXCEPTION_BY_VAL {Exc};
    -
    -/* Let's just grab the original header file here */
    -%include "example.h"
    -
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +%include "std_string.i"
    +
    +// we want to return Exc objects to the interpreter
    +// therefore we add this typemap
    +// note: only works if Exc is copyable
    +%apply SWIGTYPE EXCEPTION_BY_VAL {Exc};
    +
    +/* Let's just grab the original header file here */
    +%include "example.h"
    +
    diff --git a/Examples/lua/exception/runme.lua b/Examples/lua/exception/runme.lua
    index 39b2d6da8..a798efca7 100644
    --- a/Examples/lua/exception/runme.lua
    +++ b/Examples/lua/exception/runme.lua
    @@ -1,96 +1,96 @@
    --- file: example.lua
    -
    ----- importing ----
    -if string.sub(_VERSION,1,7)=='Lua 5.0' then
    -	-- lua5.0 doesnt have a nice way to do this
    -	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    -	assert(lib)()
    -else
    -	-- lua 5.1 does
    -	require('example')
    -end
    -
    --- throw a lot of exceptions:
    --- you must catch exceptions using pcall and then checking the result
    -
    -t = example.Test()
    -
    -print "calling t:unknown()"
    -ok,res=pcall(function() t:unknown() end)
    -if ok then 
    -    print "  that worked! Funny"
    -else
    -    print("  call failed with error:",res)
    -end
    -
    -print "calling t:simple()"
    -ok,res=pcall(function() t:simple() end)
    -if ok then 
    -    print "  that worked! Funny"
    -else
    -    print("  call failed with error:",res)
    -end
    -
    -print "calling t:message()"
    -ok,res=pcall(function() t:message() end)
    -if ok then 
    -    print "  that worked! Funny"
    -else
    -    print("  call failed with error:",res)
    -end
    -
    -print "calling t:hosed()"
    -ok,res=pcall(function() t:hosed() end)
    -if ok then 
    -    print "  that worked! Funny"
    -else
    -    print("  call failed with error:",res.code,res.msg)
    -end
    -
    --- this is a rather strange way to perform the multiple catch of exceptions
    -print "calling t:mutli()"
    -for i=1,3 do
    -    ok,res=pcall(function() t:multi(i) end)
    -    if ok then
    -        print "  that worked! Funny"
    -    else
    -        if swig_type(res)=="Exc *" then
    -            print("  call failed with Exc exception:",res.code,res.msg)
    -        else
    -            print("  call failed with error:",res)
    -        end
    -    end
    -end
    -
    --- this is a bit crazy, but it shows obtaining of the stacktrace
    -function a() 
    -    b() 
    -end
    -function b() 
    -    t:message()
    -end
    -print [[
    -Now lets call function a()
    - which calls b() 
    - which calls into C++
    - which will throw an exception!]]
    -ok,res=pcall(a)
    -if ok then 
    -    print "  that worked! Funny"
    -else
    -    print("  call failed with error:",res)
    -end
    -print "Now lets do the same using xpcall(a,debug.traceback)"
    -ok,res=xpcall(a,debug.traceback)
    -if ok then 
    -    print "  that worked! Funny"
    -else
    -    print("  call failed with error:",res)
    -end
    -print "As you can see, the xpcall gives a nice stacktrace to work with"
    -
    -
    -ok,res=pcall(a)
    -print(ok,res)
    -ok,res=xpcall(a,debug.traceback)
    -print(ok,res)
    +-- file: example.lua
    +
    +---- importing ----
    +if string.sub(_VERSION,1,7)=='Lua 5.0' then
    +	-- lua5.0 doesnt have a nice way to do this
    +	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    +	assert(lib)()
    +else
    +	-- lua 5.1 does
    +	require('example')
    +end
    +
    +-- throw a lot of exceptions:
    +-- you must catch exceptions using pcall and then checking the result
    +
    +t = example.Test()
    +
    +print "calling t:unknown()"
    +ok,res=pcall(function() t:unknown() end)
    +if ok then 
    +    print "  that worked! Funny"
    +else
    +    print("  call failed with error:",res)
    +end
    +
    +print "calling t:simple()"
    +ok,res=pcall(function() t:simple() end)
    +if ok then 
    +    print "  that worked! Funny"
    +else
    +    print("  call failed with error:",res)
    +end
    +
    +print "calling t:message()"
    +ok,res=pcall(function() t:message() end)
    +if ok then 
    +    print "  that worked! Funny"
    +else
    +    print("  call failed with error:",res)
    +end
    +
    +print "calling t:hosed()"
    +ok,res=pcall(function() t:hosed() end)
    +if ok then 
    +    print "  that worked! Funny"
    +else
    +    print("  call failed with error:",res.code,res.msg)
    +end
    +
    +-- this is a rather strange way to perform the multiple catch of exceptions
    +print "calling t:mutli()"
    +for i=1,3 do
    +    ok,res=pcall(function() t:multi(i) end)
    +    if ok then
    +        print "  that worked! Funny"
    +    else
    +        if swig_type(res)=="Exc *" then
    +            print("  call failed with Exc exception:",res.code,res.msg)
    +        else
    +            print("  call failed with error:",res)
    +        end
    +    end
    +end
    +
    +-- this is a bit crazy, but it shows obtaining of the stacktrace
    +function a() 
    +    b() 
    +end
    +function b() 
    +    t:message()
    +end
    +print [[
    +Now let's call function a()
    + which calls b() 
    + which calls into C++
    + which will throw an exception!]]
    +ok,res=pcall(a)
    +if ok then 
    +    print "  that worked! Funny"
    +else
    +    print("  call failed with error:",res)
    +end
    +print "Now let's do the same using xpcall(a,debug.traceback)"
    +ok,res=xpcall(a,debug.traceback)
    +if ok then 
    +    print "  that worked! Funny"
    +else
    +    print("  call failed with error:",res)
    +end
    +print "As you can see, the xpcall gives a nice stacktrace to work with"
    +
    +
    +ok,res=pcall(a)
    +print(ok,res)
    +ok,res=xpcall(a,debug.traceback)
    +print(ok,res)
    diff --git a/Examples/lua/funcptr3/Makefile b/Examples/lua/funcptr3/Makefile
    index ac0fff43e..fb363cbe9 100644
    --- a/Examples/lua/funcptr3/Makefile
    +++ b/Examples/lua/funcptr3/Makefile
    @@ -1,19 +1,23 @@
     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
    -LIBS       = 
    +LIBS       =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/functest/Makefile b/Examples/lua/functest/Makefile
    index ac0fff43e..fb363cbe9 100644
    --- a/Examples/lua/functest/Makefile
    +++ b/Examples/lua/functest/Makefile
    @@ -1,19 +1,23 @@
     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
    -LIBS       = 
    +LIBS       =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/functest/example.i b/Examples/lua/functest/example.i
    index 631e0602d..9bb64cbf5 100644
    --- a/Examples/lua/functest/example.i
    +++ b/Examples/lua/functest/example.i
    @@ -1,13 +1,12 @@
     /* File : example.i */
     %module example
     
    -%include "typemaps.i" // you must have this for the typemaps for ptrs
    -// basic function testing
    -//
    +%include "typemaps.i"
    +
     %inline %{
    -extern int add1(int x, int y);              // return x+y -- basic function test
    -extern void add2(int x, int *INPUT, int *OUTPUT); // *z = x+*y  -- argin and argout test
    -extern int add3(int x, int y, int *OUTPUT);    // return x+y, *z=x-y -- returning 2 values
    -extern void add4(int x, int *INOUT);        // *y += x    -- INOUT dual purpose variable
    +extern int add1(int x, int y);              /* return x+y -- basic function test */
    +extern void add2(int x, int *INPUT, int *OUTPUT); /* *z = x+*y  -- argin and argout test */
    +extern int add3(int x, int y, int *OUTPUT);    /* return x+y, *z=x-y -- returning 2 values */
    +extern void add4(int x, int *INOUT);        /* *y += x    -- INOUT dual purpose variable */
     %}
     
    diff --git a/Examples/lua/functor/Makefile b/Examples/lua/functor/Makefile
    index 432bfbef3..1bc860a70 100644
    --- a/Examples/lua/functor/Makefile
    +++ b/Examples/lua/functor/Makefile
    @@ -1,20 +1,24 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    =
     TARGET     = example
     INTERFACE  = example.i
     LIBS       = -lm
    -SWIGOPT    = 
    +SWIGOPT    =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/import.lua b/Examples/lua/import.lua
    index b2a40b017..4a0f0d3da 100644
    --- a/Examples/lua/import.lua
    +++ b/Examples/lua/import.lua
    @@ -1,7 +1,7 @@
     -- import
     -- the lua 5.0 loading mechanism is rather poor & relies upon the loadlib() fn
     -- the lua 5.1 loading mechanism is simplicity itself
    --- for now we need a bridge which will use the correct verion
    +-- for now we need a bridge which will use the correct version
     
     function import_5_0(module)
     	-- imports the file into the program
    @@ -10,7 +10,7 @@ function import_5_0(module)
     	-- and look for the fn 'Example_Init()' (note the capitalisation)
     	if rawget(_G,module)~=nil then return end -- module appears to be loaded
     		
    -	-- capitialising the first letter
    +	-- capitalising the first letter
     	local c=string.upper(string.sub(module,1,1))
     	local fnname=c..string.sub(module,2).."_Init"
     	
    @@ -26,7 +26,7 @@ function import_5_0(module)
     	end
     	assert(lib,"error loading module:"..module)
     	
    -	lib() -- execute the function: initalising the lib
    +	lib() -- execute the function: initialising the lib
     	local m=rawget(_G,module)	-- gets the module object
     	assert(m~=nil,"no module table found")
     end
    @@ -39,4 +39,4 @@ if string.sub(_VERSION,1,7)=='Lua 5.0' then
     	import=import_5_0
     else
     	import=import_5_1
    -end
    \ No newline at end of file
    +end
    diff --git a/Examples/lua/import/Makefile b/Examples/lua/import/Makefile
    index 8f692d175..ff73702c4 100644
    --- a/Examples/lua/import/Makefile
    +++ b/Examples/lua/import/Makefile
    @@ -1,19 +1,25 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
     SWIGOPT    =
     LIBS       =
    - 
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
    -	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' lua_cpp
    -	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
    -	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' lua_cpp
    -	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
    -	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' lua_cpp
    -	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
    -	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' lua_cpp
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
     
    -check: all
    +build:
    +	$(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/import/base.h b/Examples/lua/import/base.h
    index fec0f329c..ff6fecdd3 100644
    --- a/Examples/lua/import/base.h
    +++ b/Examples/lua/import/base.h
    @@ -1,7 +1,7 @@
     class Base {
      public:
    -     Base() { };
    -     virtual ~Base() { };
    +     Base() { }
    +     virtual ~Base() { }
          virtual const char * A() const {
              return "Base::A";
          }
    diff --git a/Examples/lua/nspace/Makefile b/Examples/lua/nspace/Makefile
    new file mode 100644
    index 000000000..fdedebca1
    --- /dev/null
    +++ b/Examples/lua/nspace/Makefile
    @@ -0,0 +1,22 @@
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    =
    +TARGET     = example
    +INTERFACE  = example.i
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/nspace/example.h b/Examples/lua/nspace/example.h
    new file mode 100644
    index 000000000..53066980a
    --- /dev/null
    +++ b/Examples/lua/nspace/example.h
    @@ -0,0 +1,23 @@
    +#ifndef _example_guardian_
    +#define _example_guardian_
    +
    +int module_function() { return 7; }
    +int module_variable = 9;
    +
    +namespace MyWorld {
    +  class World {
    +  public:
    +    World() : world_max_count(9) {}
    +    int create_world() { return 17; }
    +    const int world_max_count; // = 9
    +  };
    +  namespace Nested {
    +    class Dweller {
    +      public:
    +        enum Gender { MALE = 0, FEMALE = 1 };
    +        static int count() { return 19; }
    +    };
    +  }
    +}
    +
    +#endif
    diff --git a/Examples/lua/nspace/example.i b/Examples/lua/nspace/example.i
    new file mode 100644
    index 000000000..c30f87fec
    --- /dev/null
    +++ b/Examples/lua/nspace/example.i
    @@ -0,0 +1,10 @@
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +%nspace MyWorld::Nested::Dweller;
    +%nspace MyWorld::World;
    +
    +%include "example.h"
    diff --git a/Examples/lua/nspace/runme.lua b/Examples/lua/nspace/runme.lua
    new file mode 100644
    index 000000000..876814052
    --- /dev/null
    +++ b/Examples/lua/nspace/runme.lua
    @@ -0,0 +1,46 @@
    +-- file: runme.lua
    +
    +-- This file illustrates class C++ interface generated
    +-- by SWIG.
    +
    +---- importing ----
    +if string.sub(_VERSION,1,7)=='Lua 5.0' then
    +	-- lua5.0 doesnt have a nice way to do this
    +	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    +	assert(lib)()
    +else
    +	-- lua 5.1 does
    +	require('example')
    +end
    +
    +ex = example
    +
    +-- Calling a module function ( aka global function )
    +assert( ex.module_function() == 7 )
    +print("example.module_function(): ", ex.module_function())
    +
    +-- Accessing a module (aka global) variable
    +assert( ex.module_variable == 9 )
    +print("example.module_variable: ", ex.module_variable)
    +
    +-- Creating an instance of the class
    +w1 = ex.MyWorld.World()
    +print("Creating class instance: w1 = ex.MyWorld.World(): ", w1)
    +
    +-- Accessing class members 
    +assert( ex.MyWorld.World():create_world() == 17 )
    +print( "w1:create_world() = ", w1:create_world() )
    +assert( w1:create_world() == 17 )
    +print( "w1:world_max_count = ", w1.world_max_count )
    +assert( w1.world_max_count == 9 )
    +
    +-- Accessing enums from class within namespace
    +print( "Accessing enums: ex.MyWorld.Nested.Dweller.MALE = ", ex.MyWorld.Nested.Dweller.MALE )
    +assert( ex.MyWorld.Nested.Dweller.MALE == 0 )
    +print( "Accessing enums: ex.MyWorld.Nested.Dweller.FEMALE = ", ex.MyWorld.Nested.Dweller.FEMALE )
    +assert( ex.MyWorld.Nested.Dweller.FEMALE == 1 )
    +
    +-- Accessing static member function
    +print( "Accessing static member function: ex.MyWorld.Nested.Dweller.count() = ", ex.MyWorld.Nested.Dweller.count() )
    +assert( ex.MyWorld.Nested.Dweller.count() == 19 )
    +
    diff --git a/Examples/lua/owner/Makefile b/Examples/lua/owner/Makefile
    index 1fe68ec7f..dd78fdbe9 100644
    --- a/Examples/lua/owner/Makefile
    +++ b/Examples/lua/owner/Makefile
    @@ -1,19 +1,23 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = example.cxx
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    = example.cxx
    +TARGET     = example
    +INTERFACE  = example.i
    +LIBS       = -lm
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/owner/example.cxx b/Examples/lua/owner/example.cxx
    index d6caeef15..c2c073d79 100644
    --- a/Examples/lua/owner/example.cxx
    +++ b/Examples/lua/owner/example.cxx
    @@ -1,69 +1,72 @@
    -/* File : example.c */
    -
    -#include "example.h"
    -#include 
    -
    -#define M_PI 3.14159265358979323846
    -
    -/* Move the shape to a new location */
    -void Shape::move(double dx, double dy) {
    -  x += dx;
    -  y += dy;
    -}
    -
    -int Shape::nshapes = 0;
    -
    -double Circle::area(void) {
    -  return M_PI*radius*radius;
    -}
    -
    -double Circle::perimeter(void) {
    -  return 2*M_PI*radius;
    -}
    -
    -double Square::area(void) {
    -  return width*width;
    -}
    -
    -double Square::perimeter(void) {
    -  return 4*width;
    -}
    -
    -Circle* createCircle(double w)
    -{
    -    return new Circle(w);
    -}
    -
    -Square* createSquare(double w)
    -{
    -    return new Square(w);
    -}
    -
    -ShapeOwner::ShapeOwner() {printf("  ShapeOwner(%p)\n",this);}
    -ShapeOwner::~ShapeOwner()
    -{
    -    printf("  ~ShapeOwner(%p)\n",this);
    -    for(unsigned i=0;i= static_cast(shapes.size()))
    -        return NULL;
    -    return shapes[idx];
    -}
    -
    -Shape* ShapeOwner::remove(int idx) // this method returns memory which must be deleted
    -{
    -    if (idx < 0 || idx >= static_cast(shapes.size()))
    -        return NULL;
    -    Shape* ptr=shapes[idx];
    -    shapes.erase(shapes.begin()+idx);
    -    return ptr;
    -}
    +/* File : example.c */
    +
    +#include "example.h"
    +#include 
    +
    +#define M_PI 3.14159265358979323846
    +
    +/* Move the shape to a new location */
    +void Shape::move(double dx, double dy) {
    +  x += dx;
    +  y += dy;
    +}
    +
    +int Shape::nshapes = 0;
    +
    +double Circle::area(void) {
    +  return M_PI*radius*radius;
    +}
    +
    +double Circle::perimeter(void) {
    +  return 2*M_PI*radius;
    +}
    +
    +double Square::area(void) {
    +  return width*width;
    +}
    +
    +double Square::perimeter(void) {
    +  return 4*width;
    +}
    +
    +Circle* createCircle(double w)
    +{
    +    return new Circle(w);
    +}
    +
    +Square* createSquare(double w)
    +{
    +    return new Square(w);
    +}
    +
    +ShapeOwner::ShapeOwner() {
    +  printf("  ShapeOwner(%p)\n", (void *)this);
    +}
    +
    +ShapeOwner::~ShapeOwner()
    +{
    +  printf("  ~ShapeOwner(%p)\n", (void *)this);
    +  for(unsigned i=0;i= static_cast(shapes.size()))
    +        return NULL;
    +    return shapes[idx];
    +}
    +
    +Shape* ShapeOwner::remove(int idx) // this method returns memory which must be deleted
    +{
    +    if (idx < 0 || idx >= static_cast(shapes.size()))
    +        return NULL;
    +    Shape* ptr=shapes[idx];
    +    shapes.erase(shapes.begin()+idx);
    +    return ptr;
    +}
    diff --git a/Examples/lua/owner/example.h b/Examples/lua/owner/example.h
    index b00568025..9101c6330 100644
    --- a/Examples/lua/owner/example.h
    +++ b/Examples/lua/owner/example.h
    @@ -1,54 +1,54 @@
    -/* 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;
    -};
    -
    -class Circle : public Shape {
    -private:
    -  double radius;
    -public:
    -  Circle(double r) : radius(r) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    -};
    -
    -class Square : public Shape {
    -private:
    -  double width;
    -public:
    -  Square(double w) : width(w) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    -};
    -
    -
    -Circle* createCircle(double w); // this method creates a new object
    -Square* createSquare(double w); // this method creates a new object
    -
    -class ShapeOwner {
    -private:
    -    std::vector shapes;
    -    ShapeOwner(const ShapeOwner&); // no copying
    -    ShapeOwner& operator=(const ShapeOwner&); // no copying
    -public:
    -    ShapeOwner();
    -    ~ShapeOwner();
    -    void add(Shape* ptr); // this method takes ownership of the object
    -    Shape* get(int idx); // this pointer is still owned by the class (assessor)
    -    Shape* remove(int idx); // this method returns memory which must be deleted
    -};
    -
    -  
    +/* 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;
    +};
    +
    +class Circle : public Shape {
    +private:
    +  double radius;
    +public:
    +  Circle(double r) : radius(r) { }
    +  virtual double area(void);
    +  virtual double perimeter(void);
    +};
    +
    +class Square : public Shape {
    +private:
    +  double width;
    +public:
    +  Square(double w) : width(w) { }
    +  virtual double area(void);
    +  virtual double perimeter(void);
    +};
    +
    +
    +Circle* createCircle(double w); // this method creates a new object
    +Square* createSquare(double w); // this method creates a new object
    +
    +class ShapeOwner {
    +private:
    +    std::vector shapes;
    +    ShapeOwner(const ShapeOwner&); // no copying
    +    ShapeOwner& operator=(const ShapeOwner&); // no copying
    +public:
    +    ShapeOwner();
    +    ~ShapeOwner();
    +    void add(Shape* ptr); // this method takes ownership of the object
    +    Shape* get(int idx); // this pointer is still owned by the class (assessor)
    +    Shape* remove(int idx); // this method returns memory which must be deleted
    +};
    +
    +  
    diff --git a/Examples/lua/owner/example.i b/Examples/lua/owner/example.i
    index 4e7c331bc..1dfac4a09 100644
    --- a/Examples/lua/owner/example.i
    +++ b/Examples/lua/owner/example.i
    @@ -1,32 +1,32 @@
    -/* File : example.i */
    -%module example
    -
    -%{
    -#include "example.h"
    -%}
    -
    -// before we grab the header file, we must warn SWIG about some of these functions.
    -
    -// these functions create data, so must be managed
    -%newobject createCircle;
    -%newobject createSquare;
    -
    -// this method returns as pointer which must be managed
    -%newobject ShapeOwner::remove;
    -
    -// you cannot use %delobject on ShapeOwner::add()
    -// as this disowns the ShapeOwner, not the Shape (oops)
    -//%delobject ShapeOwner::add(Shape*); DO NOT USE
    -
    -// either you can use a new function (such as this)
    -/*%delobject add_Shape;
    -%inline %{
    -void add_Shape(Shape* s,ShapeOwner* own){own->add(s);}
    -%}*/
    -
    -// or a better solution is a typemap
    -%apply SWIGTYPE *DISOWN {Shape* ptr};
    -
    -// now we can grab the header file
    -%include "example.h"
    -
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +// before we grab the header file, we must warn SWIG about some of these functions.
    +
    +// these functions create data, so must be managed
    +%newobject createCircle;
    +%newobject createSquare;
    +
    +// this method returns as pointer which must be managed
    +%newobject ShapeOwner::remove;
    +
    +// you cannot use %delobject on ShapeOwner::add()
    +// as this disowns the ShapeOwner, not the Shape (oops)
    +//%delobject ShapeOwner::add(Shape*); DO NOT USE
    +
    +// either you can use a new function (such as this)
    +/*%delobject add_Shape;
    +%inline %{
    +void add_Shape(Shape* s,ShapeOwner* own){own->add(s);}
    +%}*/
    +
    +// or a better solution is a typemap
    +%apply SWIGTYPE *DISOWN {Shape* ptr};
    +
    +// now we can grab the header file
    +%include "example.h"
    +
    diff --git a/Examples/lua/owner/runme.lua b/Examples/lua/owner/runme.lua
    index d2d8a9c6f..847645448 100644
    --- a/Examples/lua/owner/runme.lua
    +++ b/Examples/lua/owner/runme.lua
    @@ -1,104 +1,104 @@
    --- Operator overloading example
    ----- importing ----
    -if string.sub(_VERSION,1,7)=='Lua 5.0' then
    -	-- lua5.0 doesnt have a nice way to do this
    -	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    -	assert(lib)()
    -else
    -	-- lua 5.1 does
    -	require('example')
    -end
    -
    -print "ok, lets test Lua's ownership of C++ objects"
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    -
    -print "\nLets make a couple"
    -a=example.Square(10)
    -b=example.Circle(1)
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 2)")
    -
    -print "\nNote lets use the createX functions"
    -c=example.createCircle(5)
    -d=example.createSquare(3)
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 4)")
    -
    -print "\nWe will run the garbage collector & see if they are till here"
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 4)")
    -
    -print "\nLets get rid of them all, collect garbage & see if they are till here"
    -a,b,c,d=nil,nil,nil,nil
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    -
    -print "\nLets start putting stuff into the ShapeOwner"
    -print "The ShapeOwner now owns the shapes, but Lua still has pointers to them"
    -o=example.ShapeOwner()
    -a=example.Square(10)
    -b=example.Circle(1)
    -o:add(a)
    -o:add(b)
    -o:add(example.createSquare(5))
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    -
    -print "\nWe will nil our references,run the garbage collector & see if they are till here"
    -print "they should be, as the ShapeOwner owns them"
    -a,b=nil,nil
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    -
    -print "\nWe will access them and check that they are still valid"
    -a=o:get(0)
    -b=o:get(1)
    -print(" Area's are",a:area(),b:area(),o:get(2):area())
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    -
    -print "\nWe will remove one from the C++ owner & pass its ownership to Lua,"
    -print " then check that they are still unchanged"
    -a,b=nil,nil
    -a=o:remove(0) -- a now owns it
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    -
    -print "\nDelete the ShapeOwner (this should destroy two shapes),"
    -print " but we have one left in Lua"
    -o=nil
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 1)")
    -
    -print "\nFinal tidy up "
    -a=nil
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    -
    -
    -print "Final test, we will create some Shapes & pass them around like mad"
    -print "If there is any memory leak, you will see it in the memory usage"
    -io.flush()
    -sh={}
    --- make some objects
    -for i=0,10 do
    -    a=example.Circle(i)
    -    b=example.Square(i)
    -    sh[a]=true
    -    sh[b]=true
    -end
    -o=example.ShapeOwner()
    -for i=0,10000 do
    -    for k,_ in pairs(sh) do
    -        o:add(k)
    -    end
    -    sh={}   -- clear it
    -    while true do
    -        a=o:remove(0)
    -        if a==nil then break end
    -        sh[a]=true
    -    end        
    -    if i%100==0 then collectgarbage() end
    -end
    -print "done"
    -o,sh=nil,nil
    -collectgarbage()
    -print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    -print "thats all folks!"
    \ No newline at end of file
    +-- Operator overloading example
    +---- importing ----
    +if string.sub(_VERSION,1,7)=='Lua 5.0' then
    +	-- lua5.0 doesnt have a nice way to do this
    +	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    +	assert(lib)()
    +else
    +	-- lua 5.1 does
    +	require('example')
    +end
    +
    +print "ok, let's test Lua's ownership of C++ objects"
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    +
    +print "\nLet's make a couple"
    +a=example.Square(10)
    +b=example.Circle(1)
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 2)")
    +
    +print "\nNote let's use the createX functions"
    +c=example.createCircle(5)
    +d=example.createSquare(3)
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 4)")
    +
    +print "\nWe will run the garbage collector & see if they are till here"
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 4)")
    +
    +print "\nLet's get rid of them all, collect garbage & see if they are till here"
    +a,b,c,d=nil,nil,nil,nil
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    +
    +print "\nLet's start putting stuff into the ShapeOwner"
    +print "The ShapeOwner now owns the shapes, but Lua still has pointers to them"
    +o=example.ShapeOwner()
    +a=example.Square(10)
    +b=example.Circle(1)
    +o:add(a)
    +o:add(b)
    +o:add(example.createSquare(5))
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    +
    +print "\nWe will nil our references,run the garbage collector & see if they are still here"
    +print "they should be, as the ShapeOwner owns them"
    +a,b=nil,nil
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    +
    +print "\nWe will access them and check that they are still valid"
    +a=o:get(0)
    +b=o:get(1)
    +print(" Area's are",a:area(),b:area(),o:get(2):area())
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    +
    +print "\nWe will remove one from the C++ owner & pass its ownership to Lua,"
    +print " then check that they are still unchanged"
    +a,b=nil,nil
    +a=o:remove(0) -- a now owns it
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")
    +
    +print "\nDelete the ShapeOwner (this should destroy two shapes),"
    +print " but we have one left in Lua"
    +o=nil
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 1)")
    +
    +print "\nFinal tidy up "
    +a=nil
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    +
    +
    +print "Final test, we will create some Shapes & pass them around like mad"
    +print "If there is any memory leak, you will see it in the memory usage"
    +io.flush()
    +sh={}
    +-- make some objects
    +for i=0,10 do
    +    a=example.Circle(i)
    +    b=example.Square(i)
    +    sh[a]=true
    +    sh[b]=true
    +end
    +o=example.ShapeOwner()
    +for i=0,10000 do
    +    for k,_ in pairs(sh) do
    +        o:add(k)
    +    end
    +    sh={}   -- clear it
    +    while true do
    +        a=o:remove(0)
    +        if a==nil then break end
    +        sh[a]=true
    +    end        
    +    if i%100==0 then collectgarbage() end
    +end
    +print "done"
    +o,sh=nil,nil
    +collectgarbage()
    +print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")
    +print "that's all folks!"
    diff --git a/Examples/lua/pointer/Makefile b/Examples/lua/pointer/Makefile
    index ac0fff43e..fb363cbe9 100644
    --- a/Examples/lua/pointer/Makefile
    +++ b/Examples/lua/pointer/Makefile
    @@ -1,19 +1,23 @@
     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
    -LIBS       = 
    +LIBS       =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/simple/Makefile b/Examples/lua/simple/Makefile
    index f181818a6..70de9c453 100644
    --- a/Examples/lua/simple/Makefile
    +++ b/Examples/lua/simple/Makefile
    @@ -1,18 +1,22 @@
     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
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/variables/Makefile b/Examples/lua/variables/Makefile
    index f181818a6..70de9c453 100644
    --- a/Examples/lua/variables/Makefile
    +++ b/Examples/lua/variables/Makefile
    @@ -1,18 +1,22 @@
     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
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run
    +
    +build:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
    +	SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
     	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile lua_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean
    diff --git a/Examples/lua/variables/example.c b/Examples/lua/variables/example.c
    index aa4ffe9b3..85685fe72 100644
    --- a/Examples/lua/variables/example.c
    +++ b/Examples/lua/variables/example.c
    @@ -51,10 +51,10 @@ void print_vars() {
       printf("dvar      = %g\n", dvar);
       printf("cvar      = %c\n", cvar);
       printf("strvar    = %s\n", strvar ? strvar : "(null)");
    -  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
    -  printf("iptrvar   = %p\n", iptrvar);
    +  printf("cstrvar   = %s\n", cstrvar);
    +  printf("iptrvar   = %p\n", (void *)iptrvar);
       printf("name      = %s\n", name);
    -  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
    +  printf("ptptr     = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
       printf("pt        = (%d, %d)\n", pt.x, pt.y);
       printf("status    = %d\n", status);
     }
    diff --git a/Examples/modula3/class/Makefile b/Examples/modula3/class/Makefile
    index bf929a061..b25f636c3 100644
    --- a/Examples/modula3/class/Makefile
    +++ b/Examples/modula3/class/Makefile
    @@ -1,16 +1,19 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     PLATFORM   = LINUXLIBC6
     INTERFACE  = example.i
     SWIGOPT    = -c++
     MODULA3SRCS = *.[im]3
     
    -all::	modula3
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run
     
    -modula3::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(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
    @@ -19,7 +22,5 @@ modula3::
     	ln -sf ../example.h src/example.h
     	cm3
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile modula3_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean
    diff --git a/Examples/modula3/class/example.cxx b/Examples/modula3/class/example.cxx
    index 1e8e203dd..046304519 100644
    --- a/Examples/modula3/class/example.cxx
    +++ b/Examples/modula3/class/example.cxx
    @@ -1,4 +1,4 @@
    -/* File : example.c */
    +/* File : example.cxx */
     
     #include "example.h"
     #define M_PI 3.14159265358979323846
    @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) {
     
     int Shape::nshapes = 0;
     
    -double Circle::area(void) {
    +double Circle::area() {
       return M_PI*radius*radius;
     }
     
    -double Circle::perimeter(void) {
    +double Circle::perimeter() {
       return 2*M_PI*radius;
     }
     
    -double Square::area(void) {
    +double Square::area() {
       return width*width;
     }
     
    -double Square::perimeter(void) {
    +double Square::perimeter() {
       return 4*width;
     }
    diff --git a/Examples/modula3/class/example.h b/Examples/modula3/class/example.h
    index 9c1f47995..0dff185b2 100644
    --- a/Examples/modula3/class/example.h
    +++ b/Examples/modula3/class/example.h
    @@ -1,44 +1,34 @@
     /* File : example.h */
     
    -class Shape
    -{
    +class Shape {
     public:
    -  Shape ()
    -  {
    +  Shape() {
         nshapes++;
       }
    -  virtual ~ Shape ()
    -  {
    +  virtual ~Shape() {
         nshapes--;
    -  };
    -  double x, y;
    -  void move (double dx, double dy);
    -  virtual double area (void) const = 0;
    -  virtual double perimeter (void) const = 0;
    -protected:
    -  static int 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
    -{
    +class Circle : public Shape {
     private:
       double radius;
     public:
    -    Circle (double r):radius (r)
    -  {
    -  };
    -  virtual double area (void) const;
    -  virtual double perimeter (void) const;
    +  Circle(double r) : radius(r) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
     
    -class Square:public Shape
    -{
    +class Square : public Shape {
     private:
       double width;
     public:
    -    Square (double w):width (w)
    -  {
    -  };
    -  virtual double area (void) const;
    -  virtual double perimeter (void) const;
    +  Square(double w) : width(w) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
    diff --git a/Examples/modula3/enum/Makefile b/Examples/modula3/enum/Makefile
    index b5bf8f672..2c5c9b0a5 100644
    --- a/Examples/modula3/enum/Makefile
    +++ b/Examples/modula3/enum/Makefile
    @@ -1,26 +1,27 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     CONSTNUMERIC = example_const
     SWIGOPT      = -c++
     MODULA3SRCS  = *.[im]3
     
    -all::	modula3
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run
     
    -modula3::
    -	$(SWIG) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h
    +build:
    +	$(SWIGEXE) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h
     	$(CXX) -Wall $(CONSTNUMERIC).c -o $(CONSTNUMERIC)
     	$(CONSTNUMERIC) >$(CONSTNUMERIC).i
     
    -	$(MAKE) -f $(TOP)/Makefile 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/
     	cm3
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile modula3_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean
    diff --git a/Examples/modula3/exception/Makefile b/Examples/modula3/exception/Makefile
    index 2518a2203..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
    @@ -7,17 +8,17 @@ SWIGOPT    =
     MODULA3SRCS = *.[im]3
     MODULA3FLAGS= -o runme
     
    -all::	modula3
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run
     
    -modula3::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(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 MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile
    +#	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile
     	m3ppinplace $(MODULA3SRCS)
     	mv m3makefile $(MODULA3SRCS) src/
     	cm3
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile modula3_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean
    diff --git a/Examples/modula3/reference/Makefile b/Examples/modula3/reference/Makefile
    index b31577a58..eaceceb1f 100644
    --- a/Examples/modula3/reference/Makefile
    +++ b/Examples/modula3/reference/Makefile
    @@ -1,21 +1,22 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     SWIGOPT    = -c++
     MODULA3SRCS = *.[im]3
     
    -all::	modula3
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run
     
    -modula3::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(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/
     	cm3
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile modula3_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean
    diff --git a/Examples/modula3/reference/example.cxx b/Examples/modula3/reference/example.cxx
    index 649b0169c..9dbaed2ee 100644
    --- a/Examples/modula3/reference/example.cxx
    +++ b/Examples/modula3/reference/example.cxx
    @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) {
     
     char *Vector::print() {
       static char temp[512];
    -  sprintf(temp,"Vector %x (%g,%g,%g)", (int)this, x,y,z);
    +  sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z);
       return temp;
     }
     
    diff --git a/Examples/modula3/reference/example.h b/Examples/modula3/reference/example.h
    index 0a9cd447f..7b4ba8fb8 100644
    --- a/Examples/modula3/reference/example.h
    +++ b/Examples/modula3/reference/example.h
    @@ -4,8 +4,8 @@ struct 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) { };
    +  Vector() : x(0), y(0), z(0) { }
    +  Vector(double x, double y, double z) : x(x), y(y), z(z) { }
       Vector operator+(const Vector &b) const;
       char *print();
     };
    diff --git a/Examples/modula3/simple/Makefile b/Examples/modula3/simple/Makefile
    index 834521fa5..3ba35d18b 100644
    --- a/Examples/modula3/simple/Makefile
    +++ b/Examples/modula3/simple/Makefile
    @@ -1,21 +1,22 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     SWIGOPT    =
     MODULA3SRCS = *.[im]3
     
    -all::	modula3
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run
     
    -modula3::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(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/
     	cm3
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile modula3_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean
    diff --git a/Examples/modula3/typemap/Makefile b/Examples/modula3/typemap/Makefile
    index 834521fa5..3ba35d18b 100644
    --- a/Examples/modula3/typemap/Makefile
    +++ b/Examples/modula3/typemap/Makefile
    @@ -1,21 +1,22 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     SWIGOPT    =
     MODULA3SRCS = *.[im]3
     
    -all::	modula3
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run
     
    -modula3::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build:
    +	$(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/
     	cm3
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile modula3_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean
    diff --git a/Examples/mzscheme/check.list b/Examples/mzscheme/check.list
    index ae728ea43..f9e4f11c7 100644
    --- a/Examples/mzscheme/check.list
    +++ b/Examples/mzscheme/check.list
    @@ -1,3 +1,4 @@
     # see top-level Makefile.in
     multimap
     simple
    +std_vector
    diff --git a/Examples/mzscheme/multimap/Makefile b/Examples/mzscheme/multimap/Makefile
    index a3cfb8f3c..713ee43a7 100644
    --- a/Examples/mzscheme/multimap/Makefile
    +++ b/Examples/mzscheme/multimap/Makefile
    @@ -1,13 +1,17 @@
     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
    -SWIGOPT    = 
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' mzscheme
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile mzscheme_clean
    +SWIGOPT    =
     
    -check: all
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run
    +
    +build:
    +	$(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/multimap/example.scm b/Examples/mzscheme/multimap/runme.scm
    similarity index 89%
    rename from Examples/mzscheme/multimap/example.scm
    rename to Examples/mzscheme/multimap/runme.scm
    index ac9f64283..f1e626f43 100644
    --- a/Examples/mzscheme/multimap/example.scm
    +++ b/Examples/mzscheme/multimap/runme.scm
    @@ -1,4 +1,4 @@
    -;; run with mzscheme -r example.scm
    +;; run with mzscheme -r runme.scm
     
     (load-extension "example.so")
     
    @@ -24,4 +24,4 @@
     (newline)
     
     (display (capitalize "hello world"))
    -(newline)
    \ No newline at end of file
    +(newline)
    diff --git a/Examples/mzscheme/simple/Makefile b/Examples/mzscheme/simple/Makefile
    index a3cfb8f3c..713ee43a7 100644
    --- a/Examples/mzscheme/simple/Makefile
    +++ b/Examples/mzscheme/simple/Makefile
    @@ -1,13 +1,17 @@
     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
    -SWIGOPT    = 
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' mzscheme
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile mzscheme_clean
    +SWIGOPT    =
     
    -check: all
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run
    +
    +build:
    +	$(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/example.scm b/Examples/mzscheme/simple/runme.scm
    similarity index 92%
    rename from Examples/mzscheme/simple/example.scm
    rename to Examples/mzscheme/simple/runme.scm
    index 8e20345b2..a98e31fd5 100644
    --- a/Examples/mzscheme/simple/example.scm
    +++ b/Examples/mzscheme/simple/runme.scm
    @@ -1,4 +1,4 @@
    -;; run with mzscheme -r example.scm
    +;; run with mzscheme -r runme.scm
     
     (load-extension "example.so")
     
    diff --git a/Examples/mzscheme/std_vector/Makefile b/Examples/mzscheme/std_vector/Makefile
    index e18726981..96f5e80cf 100644
    --- a/Examples/mzscheme/std_vector/Makefile
    +++ b/Examples/mzscheme/std_vector/Makefile
    @@ -1,19 +1,21 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
    -SWIGOPT    = 
    +SWIGOPT    =
     
     GPP        = `which g++`
     MZC        = test -n "/usr/bin/mzc" && /usr/bin/mzc
     
    -all::
    -	$(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACE)
    -	$(MZC) --compiler $(GPP) ++ccf "-I." --cc example_wrap.cxx
    -	$(MZC) --linker $(GPP) --ld $(TARGET).so example_wrap.o 
    -	
    -clean:
    -	$(MAKE) -f $(TOP)/Makefile mzscheme_clean
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run
     
    -check: all
    +build:
    +	$(SWIGEXE) -mzscheme -c++ $(SWIGOPT) $(INTERFACE)
    +	$(MZC) --compiler $(GPP) ++ccf "-I." --cc example_wrap.cxx
    +	$(MZC) --linker $(GPP) --ld $(TARGET).so example_wrap.o
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean
    diff --git a/Examples/mzscheme/std_vector/example.scm b/Examples/mzscheme/std_vector/runme.scm
    similarity index 97%
    rename from Examples/mzscheme/std_vector/example.scm
    rename to Examples/mzscheme/std_vector/runme.scm
    index 0e4ac3f97..67351f128 100644
    --- a/Examples/mzscheme/std_vector/example.scm
    +++ b/Examples/mzscheme/std_vector/runme.scm
    @@ -1,4 +1,4 @@
    -;; run with mzscheme -r example.scm
    +;; run with mzscheme -r runme.scm
     
     (load-extension "example.so")
     
    diff --git a/Examples/ocaml/argout_ref/Makefile b/Examples/ocaml/argout_ref/Makefile
    index 8a260fe30..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
    @@ -7,21 +8,24 @@ MLFILE     = example.ml
     PROGFILE   = example_prog.ml
     OBJS       = example.o
     
    -all:: static 
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean
    diff --git a/Examples/ocaml/contract/Makefile b/Examples/ocaml/contract/Makefile
    index 8e0f2a4fd..c77e6dcc4 100644
    --- a/Examples/ocaml/contract/Makefile
    +++ b/Examples/ocaml/contract/Makefile
    @@ -1,33 +1,38 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     MLFILE     = example.ml
     PROGFILE   = example_prog.ml
    -OBJS       = 
    +OBJS       =
     
    -all:: static 
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -dynamic::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +dynamic:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +toplevel:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean
    diff --git a/Examples/ocaml/scoped_enum/Makefile b/Examples/ocaml/scoped_enum/Makefile
    index 45c5edca4..9655c98e6 100644
    --- a/Examples/ocaml/scoped_enum/Makefile
    +++ b/Examples/ocaml/scoped_enum/Makefile
    @@ -1,33 +1,38 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     MLFILE     = example.ml
     PROGFILE   = example_prog.ml
    -OBJS       = 
    +OBJS       =
     
    -all:: static 
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -dynamic::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +dynamic:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +toplevel:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean
    diff --git a/Examples/ocaml/shapes/Makefile b/Examples/ocaml/shapes/Makefile
    index 31f9934a7..b291d07e8 100644
    --- a/Examples/ocaml/shapes/Makefile
    +++ b/Examples/ocaml/shapes/Makefile
    @@ -1,6 +1,7 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SWIGOPT    = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SWIGOPT    =
     SRCS       = example.c
     TARGET     = example
     INTERFACE  = example.i
    @@ -8,27 +9,31 @@ MLFILE     = example.ml
     PROGFILE   = example_prog.ml
     OBJS       = example.o
     
    -all:: static static_top
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static static_top
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static_top:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean
    diff --git a/Examples/ocaml/simple/Makefile b/Examples/ocaml/simple/Makefile
    index 4b85bf33e..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
    @@ -7,27 +8,31 @@ MLFILE     = example.ml
     PROGFILE   = example_prog.ml
     OBJS       = example.o
     
    -all:: static 
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -dynamic::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +dynamic:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +toplevel:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean
    diff --git a/Examples/ocaml/std_string/Makefile b/Examples/ocaml/std_string/Makefile
    index e5a8017ae..099b1fcee 100644
    --- a/Examples/ocaml/std_string/Makefile
    +++ b/Examples/ocaml/std_string/Makefile
    @@ -1,23 +1,27 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     PROGFILE   = runme.ml
     
    -all default:: static
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean
    diff --git a/Examples/ocaml/std_vector/Makefile b/Examples/ocaml/std_vector/Makefile
    index e5a8017ae..099b1fcee 100644
    --- a/Examples/ocaml/std_vector/Makefile
    +++ b/Examples/ocaml/std_vector/Makefile
    @@ -1,23 +1,27 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     PROGFILE   = runme.ml
     
    -all default:: static
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean
    diff --git a/Examples/ocaml/stl/Makefile b/Examples/ocaml/stl/Makefile
    index fa4333ec0..912dd9f8d 100644
    --- a/Examples/ocaml/stl/Makefile
    +++ b/Examples/ocaml/stl/Makefile
    @@ -1,33 +1,39 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     PROGFILE   = runme.ml
     
    -all default:: static
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +director:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +toplevel:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean
    diff --git a/Examples/ocaml/string_from_ptr/Makefile b/Examples/ocaml/string_from_ptr/Makefile
    index 350d9734c..f9b027802 100644
    --- a/Examples/ocaml/string_from_ptr/Makefile
    +++ b/Examples/ocaml/string_from_ptr/Makefile
    @@ -1,34 +1,39 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
     SWIGOPT    = -c++
    -SRCS       = 
    +SRCS       =
     TARGET     = example
     INTERFACE  = foolib.i
     MLFILE     = foolib.ml
     PROGFILE   = example_prog.ml
    -OBJS       = 
    +OBJS       =
     
    -all:: static static_top
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static static_top
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +static_top:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean
    diff --git a/Examples/ocaml/strings_test/Makefile b/Examples/ocaml/strings_test/Makefile
    index 8d1f96edf..24e2e6cca 100644
    --- a/Examples/ocaml/strings_test/Makefile
    +++ b/Examples/ocaml/strings_test/Makefile
    @@ -1,28 +1,33 @@
     TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = 
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +SRCS       =
     TARGET     = example
     INTERFACE  = example.i
     PROGFILE   = runme.ml
     
    -all default:: static top
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run
     
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +build: static top
    +
    +static:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +dynamic:
    +	$(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \
    +top:
    +	$(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
     
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
    -
    -check: all
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean
    diff --git a/Examples/octave/callback/Makefile b/Examples/octave/callback/Makefile
    index 21fb21137..3b746de2f 100644
    --- a/Examples/octave/callback/Makefile
    +++ b/Examples/octave/callback/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = example.cxx
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS = example.cxx
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/callback/example.cxx b/Examples/octave/callback/example.cxx
    index 450d75608..893a956f4 100644
    --- a/Examples/octave/callback/example.cxx
    +++ b/Examples/octave/callback/example.cxx
    @@ -1,4 +1,3 @@
     /* File : example.cxx */
     
     #include "example.h"
    -
    diff --git a/Examples/octave/callback/example.h b/Examples/octave/callback/example.h
    index 1a0e8c432..74ddad954 100644
    --- a/Examples/octave/callback/example.h
    +++ b/Examples/octave/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/octave/callback/example.i b/Examples/octave/callback/example.i
    index 90beda01a..333127a9d 100644
    --- a/Examples/octave/callback/example.i
    +++ b/Examples/octave/callback/example.i
    @@ -1,13 +1,13 @@
     /* File : example.i */
    -%module(directors="1") example
    +%module(directors="1") swigexample
    +
    +%feature("autodoc", 1);
    +
     %{
     #include "example.h"
     %}
     
    -%include "std_string.i"
    -
     /* turn on director wrapping Callback */
     %feature("director") Callback;
     
     %include "example.h"
    -
    diff --git a/Examples/octave/callback/runme.m b/Examples/octave/callback/runme.m
    index b87925e3d..103985358 100644
    --- a/Examples/octave/callback/runme.m
    +++ b/Examples/octave/callback/runme.m
    @@ -2,14 +2,13 @@
     
     # This file illustrates the cross language polymorphism using directors.
     
    -example 
    +swigexample
     
    -OctCallback=@() subclass(example.Callback(), \
    -			 'run',@(self) printf("OctCallback.run()\n"));
    +OctCallback=@() subclass(swigexample.Callback(),"run",@(self) printf("OctCallback.run()\n"));
     
     # Create an Caller instance
     
    -caller = example.Caller();
    +caller = swigexample.Caller();
     
     # Add a simple C++ callback (caller owns the callback, so
     # we disown it first)
    @@ -17,7 +16,7 @@ caller = example.Caller();
     printf("Adding and calling a normal C++ callback\n");
     printf("----------------------------------------\n");
     
    -callback = example.Callback().__disown();
    +callback = swigexample.Callback().__disown();
     caller.setCallback(callback);
     caller.call();
     caller.delCallback();
    @@ -43,7 +42,7 @@ caller.call();
     caller.delCallback();
     
     # careful-- using callback here may cause problems; octave_swig_type still
    -# exists, but is holding a destroyed object (the C++ example.Callback).
    +# exists, but is holding a destroyed object (the C++ swigexample.Callback).
     # to manually drop the octave-side reference, you can use
     clear callback;
     
    @@ -60,4 +59,3 @@ a.Callback.run();
     # All done.
     
     printf("octave exit\n");
    -
    diff --git a/Examples/octave/class/Makefile b/Examples/octave/class/Makefile
    index 21fb21137..3b746de2f 100644
    --- a/Examples/octave/class/Makefile
    +++ b/Examples/octave/class/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = example.cxx
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS = example.cxx
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/class/example.cxx b/Examples/octave/class/example.cxx
    index 1e8e203dd..046304519 100644
    --- a/Examples/octave/class/example.cxx
    +++ b/Examples/octave/class/example.cxx
    @@ -1,4 +1,4 @@
    -/* File : example.c */
    +/* File : example.cxx */
     
     #include "example.h"
     #define M_PI 3.14159265358979323846
    @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) {
     
     int Shape::nshapes = 0;
     
    -double Circle::area(void) {
    +double Circle::area() {
       return M_PI*radius*radius;
     }
     
    -double Circle::perimeter(void) {
    +double Circle::perimeter() {
       return 2*M_PI*radius;
     }
     
    -double Square::area(void) {
    +double Square::area() {
       return width*width;
     }
     
    -double Square::perimeter(void) {
    +double Square::perimeter() {
       return 4*width;
     }
    diff --git a/Examples/octave/class/example.h b/Examples/octave/class/example.h
    index 46d901361..0dff185b2 100644
    --- a/Examples/octave/class/example.h
    +++ b/Examples/octave/class/example.h
    @@ -7,11 +7,11 @@ public:
       }
       virtual ~Shape() {
         nshapes--;
    -  };
    -  double  x, y;   
    +  }
    +  double  x, y;
       void    move(double dx, double dy);
    -  virtual double area(void) = 0;
    -  virtual double perimeter(void) = 0;
    +  virtual double area() = 0;
    +  virtual double perimeter() = 0;
       static  int nshapes;
     };
     
    @@ -19,21 +19,16 @@ class Circle : public Shape {
     private:
       double radius;
     public:
    -  Circle(double r) : radius(r) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    +  Circle(double r) : radius(r) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
     
     class Square : public Shape {
     private:
       double width;
     public:
    -  Square(double w) : width(w) { };
    -  virtual double area(void);
    -  virtual double perimeter(void);
    +  Square(double w) : width(w) { }
    +  virtual double area();
    +  virtual double perimeter();
     };
    -
    -
    -
    -
    -  
    diff --git a/Examples/octave/class/example.i b/Examples/octave/class/example.i
    index 75700b305..52e9fd3bf 100644
    --- a/Examples/octave/class/example.i
    +++ b/Examples/octave/class/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %{
     #include "example.h"
    @@ -7,4 +9,3 @@
     
     /* Let's just grab the original header file here */
     %include "example.h"
    -
    diff --git a/Examples/octave/class/runme.m b/Examples/octave/class/runme.m
    index c833a701b..04221b4bb 100644
    --- a/Examples/octave/class/runme.m
    +++ b/Examples/octave/class/runme.m
    @@ -3,17 +3,17 @@
     # This file illustrates the proxy class C++ interface generated
     # by SWIG.
     
    -example 
    +swigexample
     
     # ----- Object creation -----
     
     printf("Creating some objects:\n");
    -c = example.Circle(10)
    -s = example.Square(10)
    +c = swigexample.Circle(10)
    +s = swigexample.Square(10)
     
     # ----- Access a static member -----
     
    -printf("\nA total of %i shapes were created\n", example.Shape.nshapes);
    +printf("\nA total of %i shapes were created\n", swigexample.Shape.nshapes);
     
     # ----- Member data access -----
     
    @@ -46,7 +46,5 @@ printf("\nGuess I'll clean up now\n");
     clear c
     clear s
     
    -printf("%i shapes remain\n", example.Shape.nshapes);
    +printf("%i shapes remain\n", swigexample.Shape.nshapes);
     printf("Goodbye\n");
    -
    -
    diff --git a/Examples/octave/constants/Makefile b/Examples/octave/constants/Makefile
    index 3156eae84..acf4d0575 100644
    --- a/Examples/octave/constants/Makefile
    +++ b/Examples/octave/constants/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/constants/example.i b/Examples/octave/constants/example.i
    index 4f7b1a4d7..ab42a6b21 100644
    --- a/Examples/octave/constants/example.i
    +++ b/Examples/octave/constants/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     /* A few preprocessor macros */
     
    @@ -23,5 +25,3 @@
     
     %constant int iconst = 37;
     %constant double fconst = 3.14;
    -
    -
    diff --git a/Examples/octave/constants/runme.m b/Examples/octave/constants/runme.m
    index 322858734..c6ed24535 100644
    --- a/Examples/octave/constants/runme.m
    +++ b/Examples/octave/constants/runme.m
    @@ -1,29 +1,25 @@
     # file: runme.m
     
    -example 
    +swigexample
     
    -printf("ICONST  = %i (should be 42)\n", example.ICONST);
    -printf("FCONST  = %f (should be 2.1828)\n", example.FCONST);
    -printf("CCONST  = %s (should be 'x')\n", example.CCONST);
    -printf("CCONST2 = %s (this should be on a new line)\n", example.CCONST2);
    -printf("SCONST  = %s (should be 'Hello World')\n", example.SCONST);
    -printf("SCONST2 = %s (should be '\"Hello World\"')\n", example.SCONST2);
    -printf("EXPR    = %f (should be 48.5484)\n", example.EXPR);
    -printf("iconst  = %i (should be 37)\n", example.iconst);
    -printf("fconst  = %f (should be 3.14)\n", example.fconst);
    +printf("ICONST  = %i (should be 42)\n", swigexample.ICONST);
    +printf("FCONST  = %f (should be 2.1828)\n", swigexample.FCONST);
    +printf("CCONST  = %s (should be 'x')\n", swigexample.CCONST);
    +printf("CCONST2 = %s (this should be on a new line)\n", swigexample.CCONST2);
    +printf("SCONST  = %s (should be 'Hello World')\n", swigexample.SCONST);
    +printf("SCONST2 = %s (should be '\"Hello World\"')\n", swigexample.SCONST2);
    +printf("EXPR    = %f (should be 48.5484)\n", swigexample.EXPR);
    +printf("iconst  = %i (should be 37)\n", swigexample.iconst);
    +printf("fconst  = %f (should be 3.14)\n", swigexample.fconst);
     
     try
    -    printf("EXTERN = %s (Arg! This shouldn't printf(anything)\n", example.EXTERN);
    +    printf("EXTERN = %s (Arg! This shouldn't printf(anything)\n", swigexample.EXTERN);
     catch
         printf("EXTERN isn't defined (good)\n");
     end_try_catch
     
     try
    -    printf("FOO    = %i (Arg! This shouldn't printf(anything)\n", example.FOO);
    +    printf("FOO    = %i (Arg! This shouldn't printf(anything)\n", swigexample.FOO);
     catch
         printf("FOO isn't defined (good)\n");
     end_try_catch
    -
    -
    -
    -
    diff --git a/Examples/octave/contract/Makefile b/Examples/octave/contract/Makefile
    index 464b74122..413b64bbd 100644
    --- a/Examples/octave/contract/Makefile
    +++ b/Examples/octave/contract/Makefile
    @@ -1,20 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    +SRCS = example.c
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/contract/example.c b/Examples/octave/contract/example.c
    index 1a644543f..fbdc054cd 100644
    --- a/Examples/octave/contract/example.c
    +++ b/Examples/octave/contract/example.c
    @@ -19,5 +19,3 @@ int fact(int n) {
       if (n <= 0) return 1;
       return n*fact(n-1);
     }
    -
    -
    diff --git a/Examples/octave/contract/example.i b/Examples/octave/contract/example.i
    index 8fd1a80af..8976607b2 100644
    --- a/Examples/octave/contract/example.i
    +++ b/Examples/octave/contract/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %contract gcd(int x, int y) {
     require:
    diff --git a/Examples/octave/contract/runme.m b/Examples/octave/contract/runme.m
    index 62b72320b..fa36bbe10 100644
    --- a/Examples/octave/contract/runme.m
    +++ b/Examples/octave/contract/runme.m
    @@ -1,22 +1,21 @@
     # file: runme.m
     
    -example 
    +swigexample
     
     # Call our gcd() function
     
     x = 42;
     y = 105;
    -g = example.gcd(x,y);
    +g = swigexample.gcd(x,y);
     printf("The gcd of %d and %d is %d\n",x,y,g);
     
     # Manipulate the Foo global variable
     
     # Output its current value
    -printf("Foo = %f\n", example.cvar.Foo);
    +printf("Foo = %f\n", swigexample.cvar.Foo);
     
     # Change its value
    -example.cvar.Foo = 3.1415926;
    +swigexample.cvar.Foo = 3.1415926;
     
     # See if the change took effect
    -printf("Foo = %f\n", example.cvar.Foo);
    -
    +printf("Foo = %f\n", swigexample.cvar.Foo);
    diff --git a/Examples/octave/enum/Makefile b/Examples/octave/enum/Makefile
    index 21fb21137..3b746de2f 100644
    --- a/Examples/octave/enum/Makefile
    +++ b/Examples/octave/enum/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = example.cxx
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS = example.cxx
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/enum/example.h b/Examples/octave/enum/example.h
    index 525d62afc..490d502e8 100644
    --- a/Examples/octave/enum/example.h
    +++ b/Examples/octave/enum/example.h
    @@ -10,4 +10,3 @@ class Foo {
     };
     
     void enum_test(color c, Foo::speed s);
    -
    diff --git a/Examples/octave/enum/example.i b/Examples/octave/enum/example.i
    index 23ee8a822..084bab06b 100644
    --- a/Examples/octave/enum/example.i
    +++ b/Examples/octave/enum/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %{
     #include "example.h"
    @@ -8,4 +10,3 @@
     /* Let's just grab the original header file here */
     
     %include "example.h"
    -
    diff --git a/Examples/octave/enum/runme.m b/Examples/octave/enum/runme.m
    index a749e81db..0108135b2 100644
    --- a/Examples/octave/enum/runme.m
    +++ b/Examples/octave/enum/runme.m
    @@ -1,32 +1,30 @@
     # file: runme.m
     
    -example
    +swigexample
     
     # ----- Object creation -----
     
     # Print out the value of some enums
     printf("*** color ***\n");
    -printf("    RED    = %i\n", example.RED);
    -printf("    BLUE   = %i\n", example.BLUE);
    -printf("    GREEN  = %i\n", example.GREEN);
    +printf("    RED    = %i\n", swigexample.RED);
    +printf("    BLUE   = %i\n", swigexample.BLUE);
    +printf("    GREEN  = %i\n", swigexample.GREEN);
     
     printf("\n*** Foo::speed ***\n");
    -printf("    Foo_IMPULSE   = %i\n", example.Foo_IMPULSE);
    -printf("    Foo_WARP      = %i\n", example.Foo_WARP);
    -printf("    Foo_LUDICROUS = %i\n", example.Foo_LUDICROUS);
    +printf("    Foo_IMPULSE   = %i\n", swigexample.Foo_IMPULSE);
    +printf("    Foo_WARP      = %i\n", swigexample.Foo_WARP);
    +printf("    Foo_LUDICROUS = %i\n", swigexample.Foo_LUDICROUS);
     
     printf("\nTesting use of enums with functions\n");
     
    -example.enum_test(example.RED, example.Foo_IMPULSE);
    -example.enum_test(example.BLUE,  example.Foo_WARP);
    -example.enum_test(example.GREEN, example.Foo_LUDICROUS);
    -example.enum_test(1234,5678)
    +swigexample.enum_test(swigexample.RED, swigexample.Foo_IMPULSE);
    +swigexample.enum_test(swigexample.BLUE,  swigexample.Foo_WARP);
    +swigexample.enum_test(swigexample.GREEN, swigexample.Foo_LUDICROUS);
    +swigexample.enum_test(1234,5678)
     
     printf("\nTesting use of enum with class method\n");
    -f = example.Foo();
    -
    -f.enum_test(example.Foo_IMPULSE);
    -f.enum_test(example.Foo_WARP);
    -f.enum_test(example.Foo_LUDICROUS);
    -
    +f = swigexample.Foo();
     
    +f.enum_test(swigexample.Foo_IMPULSE);
    +f.enum_test(swigexample.Foo_WARP);
    +f.enum_test(swigexample.Foo_LUDICROUS);
    diff --git a/Examples/octave/example.mk b/Examples/octave/example.mk
    new file mode 100644
    index 000000000..1ab96f038
    --- /dev/null
    +++ b/Examples/octave/example.mk
    @@ -0,0 +1,37 @@
    +# Note: as a convention an example must be in a child directory of this.
    +# These paths are relative to such an example directory
    +
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +TARGET     = swigexample
    +INTERFACE  = example.i
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run
    +
    +build:
    +ifneq (,$(SRCS))
    +	$(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_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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	SWIGOPT='$(SWIGOPT2)' TARGET='$(TARGET2)' INTERFACE='$(INTERFACE)' octave
    +else
    +	$(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
    +
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean
    diff --git a/Examples/octave/extend/Makefile b/Examples/octave/extend/Makefile
    index 21fb21137..3b746de2f 100644
    --- a/Examples/octave/extend/Makefile
    +++ b/Examples/octave/extend/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = example.cxx
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS = example.cxx
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/extend/example.cxx b/Examples/octave/extend/example.cxx
    index 450d75608..893a956f4 100644
    --- a/Examples/octave/extend/example.cxx
    +++ b/Examples/octave/extend/example.cxx
    @@ -1,4 +1,3 @@
     /* File : example.cxx */
     
     #include "example.h"
    -
    diff --git a/Examples/octave/extend/example.h b/Examples/octave/extend/example.h
    index b27ab9711..77a26ec95 100644
    --- a/Examples/octave/extend/example.h
    +++ b/Examples/octave/extend/example.h
    @@ -14,7 +14,7 @@ public:
     	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", this); }
    +	virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); }
     };
     
     
    @@ -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++) {
    @@ -53,4 +53,3 @@ public:
     		std::cout << "~EmployeeList empty." << std::endl;
     	}
     };
    -
    diff --git a/Examples/octave/extend/example.i b/Examples/octave/extend/example.i
    index c8ec32e09..3b9ac53c4 100644
    --- a/Examples/octave/extend/example.i
    +++ b/Examples/octave/extend/example.i
    @@ -1,5 +1,8 @@
     /* File : example.i */
    -%module(directors="1") example
    +%module(directors="1") swigexample
    +
    +%feature("autodoc", 1);
    +
     %{
     #include "example.h"
     %}
    @@ -12,4 +15,3 @@
     %feature("director") Manager;
     
     %include "example.h"
    -
    diff --git a/Examples/octave/extend/runme.m b/Examples/octave/extend/runme.m
    index c64c082c4..4536f2761 100644
    --- a/Examples/octave/extend/runme.m
    +++ b/Examples/octave/extend/runme.m
    @@ -2,12 +2,12 @@
     
     # This file illustrates the cross language polymorphism using directors.
     
    -example 
    +swigexample
     
     
     # CEO class, which overrides Employee::getPosition().
     
    -CEO=@(name) subclass(example.Manager(name),'getPosition',@(self) "CEO");
    +CEO=@(name) subclass(swigexample.Manager(name),'getPosition',@(self) "CEO");
     
     # Create an instance of our employee extension class, CEO. The calls to
     # getName() and getPosition() are standard, the call to getTitle() uses
    @@ -22,7 +22,7 @@ printf("----------------------\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 = example.EmployeeList();
    +list = swigexample.EmployeeList();
     
     # EmployeeList owns its items, so we must surrender ownership of objects
     # we add. This involves first calling the __disown__ method to tell the
    @@ -71,4 +71,3 @@ printf("----------------------\n");
     # All done.
     
     printf("octave exit\n");
    -
    diff --git a/Examples/octave/funcptr/Makefile b/Examples/octave/funcptr/Makefile
    index 464b74122..413b64bbd 100644
    --- a/Examples/octave/funcptr/Makefile
    +++ b/Examples/octave/funcptr/Makefile
    @@ -1,20 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    +SRCS = example.c
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/funcptr/example.h b/Examples/octave/funcptr/example.h
    index 9936e24fc..f95ae2cc9 100644
    --- a/Examples/octave/funcptr/example.h
    +++ b/Examples/octave/funcptr/example.h
    @@ -6,4 +6,3 @@ extern int sub(int,int);
     extern int mul(int,int);
     
     extern int (*funcvar)(int,int);
    -
    diff --git a/Examples/octave/funcptr/example.i b/Examples/octave/funcptr/example.i
    index 8b3bef678..c6fcfe781 100644
    --- a/Examples/octave/funcptr/example.i
    +++ b/Examples/octave/funcptr/example.i
    @@ -1,5 +1,8 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
    +
     %{
     #include "example.h"
     %}
    @@ -13,4 +16,3 @@ extern int  do_op(int a, int b, int (*op)(int, int));
     %constant int (*MUL)(int,int) = mul;
     
     extern int (*funcvar)(int,int);
    -
    diff --git a/Examples/octave/funcptr/runme.m b/Examples/octave/funcptr/runme.m
    index 455311c16..4e2e28fbc 100644
    --- a/Examples/octave/funcptr/runme.m
    +++ b/Examples/octave/funcptr/runme.m
    @@ -1,6 +1,6 @@
     # file: runme.m
     
    -example
    +swigexample
     
     a = 37
     b = 42
    @@ -10,12 +10,11 @@ b = 42
     printf("Trying some C callback functions\n");
     printf("    a        = %i\n", a);
     printf("    b        = %i\n", b);
    -printf("    ADD(a,b) = %i\n", example.do_op(a,b,example.ADD));
    -printf("    SUB(a,b) = %i\n", example.do_op(a,b,example.SUB));
    -printf("    MUL(a,b) = %i\n", example.do_op(a,b,example.MUL));
    +printf("    ADD(a,b) = %i\n", swigexample.do_op(a,b,swigexample.ADD));
    +printf("    SUB(a,b) = %i\n", swigexample.do_op(a,b,swigexample.SUB));
    +printf("    MUL(a,b) = %i\n", swigexample.do_op(a,b,swigexample.MUL));
     
     printf("Here is what the C callback function objects look like in Octave\n");
    -example.ADD
    -example.SUB
    -example.MUL
    -
    +swigexample.ADD
    +swigexample.SUB
    +swigexample.MUL
    diff --git a/Examples/octave/funcptr2/Makefile b/Examples/octave/funcptr2/Makefile
    index 464b74122..413b64bbd 100644
    --- a/Examples/octave/funcptr2/Makefile
    +++ b/Examples/octave/funcptr2/Makefile
    @@ -1,20 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    +SRCS = example.c
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/funcptr2/example.h b/Examples/octave/funcptr2/example.h
    index 9936e24fc..f95ae2cc9 100644
    --- a/Examples/octave/funcptr2/example.h
    +++ b/Examples/octave/funcptr2/example.h
    @@ -6,4 +6,3 @@ extern int sub(int,int);
     extern int mul(int,int);
     
     extern int (*funcvar)(int,int);
    -
    diff --git a/Examples/octave/funcptr2/example.i b/Examples/octave/funcptr2/example.i
    index 681775a3e..bbe50fb8f 100644
    --- a/Examples/octave/funcptr2/example.i
    +++ b/Examples/octave/funcptr2/example.i
    @@ -1,5 +1,8 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
    +
     %{
     #include "example.h"
     %}
    @@ -15,4 +18,3 @@ int mul(int, int);
     %nocallback;
     
     extern int (*funcvar)(int,int);
    -
    diff --git a/Examples/octave/funcptr2/runme.m b/Examples/octave/funcptr2/runme.m
    index 1d3d8f73a..574635ed2 100644
    --- a/Examples/octave/funcptr2/runme.m
    +++ b/Examples/octave/funcptr2/runme.m
    @@ -1,6 +1,6 @@
     # file: runme.m
     
    -example 
    +swigexample
     
     a = 37
     b = 42
    @@ -10,15 +10,15 @@ b = 42
     printf("Trying some C callback functions\n");
     printf("    a        = %i\n", a);
     printf("    b        = %i\n", b);
    -printf("    ADD(a,b) = %i\n", example.do_op(a,b,example.ADD));
    -printf("    SUB(a,b) = %i\n", example.do_op(a,b,example.SUB));
    -printf("    MUL(a,b) = %i\n", example.do_op(a,b,example.MUL));
    +printf("    ADD(a,b) = %i\n", swigexample.do_op(a,b,swigexample.ADD));
    +printf("    SUB(a,b) = %i\n", swigexample.do_op(a,b,swigexample.SUB));
    +printf("    MUL(a,b) = %i\n", swigexample.do_op(a,b,swigexample.MUL));
     
     printf("Here is what the C callback function objects look like in Octave\n");
    -example.ADD
    -example.SUB
    -example.MUL
    +swigexample.ADD
    +swigexample.SUB
    +swigexample.MUL
     
     printf("Call the functions directly...\n");
    -printf("    add(a,b) = %i\n", example.add(a,b));
    -printf("    sub(a,b) = %i\n", example.sub(a,b));
    +printf("    add(a,b) = %i\n", swigexample.add(a,b));
    +printf("    sub(a,b) = %i\n", swigexample.sub(a,b));
    diff --git a/Examples/octave/functor/Makefile b/Examples/octave/functor/Makefile
    index 8f6dfc73e..acf4d0575 100644
    --- a/Examples/octave/functor/Makefile
    +++ b/Examples/octave/functor/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/functor/example.i b/Examples/octave/functor/example.i
    index 2fd38176f..0c21a8ed6 100644
    --- a/Examples/octave/functor/example.i
    +++ b/Examples/octave/functor/example.i
    @@ -1,6 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
     
    +%feature("autodoc", 1);
     
     %inline %{
     // From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514
    @@ -23,7 +24,3 @@ public:
     // Instantiate a few versions
     %template(intSum) Sum;
     %template(doubleSum) Sum;
    -
    -
    -
    -
    diff --git a/Examples/octave/functor/runme.m b/Examples/octave/functor/runme.m
    index 65dabcc91..8b41691c3 100644
    --- a/Examples/octave/functor/runme.m
    +++ b/Examples/octave/functor/runme.m
    @@ -1,8 +1,8 @@
     # Operator overloading example
    -example
    +swigexample
     
    -a = example.intSum(0);
    -b = example.doubleSum(100.0);
    +a = swigexample.intSum(0);
    +b = swigexample.doubleSum(100.0);
     
     # Use the objects.  They should be callable just like a normal
     # python function.
    @@ -14,5 +14,3 @@ endfor
     
     a.result()
     b.result()
    -
    -
    diff --git a/Examples/octave/module_load/Makefile b/Examples/octave/module_load/Makefile
    index 4266ec184..d2cd66e70 100644
    --- a/Examples/octave/module_load/Makefile
    +++ b/Examples/octave/module_load/Makefile
    @@ -1,26 +1,7 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    -OCTSCRIPTS = \
    -	runme_args.m \
    -	runme_gl_func.m \
    -	runme_gl_func_base.m \
    -	runme_nogl_func.m \
    -	runme_nogl_func_base.m
    +SRCS     = example.c
    +TARGET   = swigexample
    +SWIGOPT  = -module swigexample
    +TARGET2  = swigexample2
    +SWIGOPT2 = -module swigexample2 -globals .
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).m
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile OCTSCRIPT="$(OCTSCRIPTS)" octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/module_load/example.i b/Examples/octave/module_load/example.i
    index f5a50444d..bd0e39937 100644
    --- a/Examples/octave/module_load/example.i
    +++ b/Examples/octave/module_load/example.i
    @@ -1,5 +1,8 @@
     /* File : example.i */
    -%module example
    +/* module name given on cmdline */
    +
    +%feature("autodoc", 1);
    +
     %{
     #include "example.h"
     %}
    diff --git a/Examples/octave/module_load/runme.m b/Examples/octave/module_load/runme.m
    new file mode 100644
    index 000000000..30b7badb2
    --- /dev/null
    +++ b/Examples/octave/module_load/runme.m
    @@ -0,0 +1,80 @@
    +# file: runme_args.m
    +
    +# load module
    +clear all;
    +swigexample;
    +assert(cvar.ivar == ifunc);
    +assert(exist("swigexample","var"));
    +clear all
    +swigexample;
    +assert(cvar.ivar == ifunc);
    +assert(exist("swigexample","var"));
    +clear all
    +
    +# load module in a function globally before base context
    +clear all;
    +function testme
    +  swigexample;
    +  assert(cvar.ivar == ifunc);
    +  assert(exist("swigexample","var"));
    +endfunction
    +testme
    +testme
    +swigexample;
    +assert(cvar.ivar == ifunc);
    +assert(exist("swigexample","var"));
    +clear all
    +function testme
    +  swigexample;
    +  assert(cvar.ivar == ifunc);
    +  assert(exist("swigexample","var"));
    +endfunction
    +testme
    +testme
    +swigexample;
    +assert(cvar.ivar == ifunc);
    +assert(exist("swigexample","var"));
    +clear all
    +
    +# load module in a function globally after base context
    +clear all;
    +swigexample;
    +assert(cvar.ivar == ifunc);
    +assert(exist("swigexample","var"));
    +function testme
    +  swigexample;
    +  assert(cvar.ivar == ifunc);
    +  assert(exist("swigexample","var"));
    +endfunction
    +testme
    +testme
    +clear all
    +swigexample;
    +assert(cvar.ivar == ifunc);
    +assert(exist("swigexample","var"));
    +function testme
    +  swigexample;
    +  assert(cvar.ivar == ifunc);
    +  assert(exist("swigexample","var"));
    +endfunction
    +testme
    +testme
    +clear all
    +
    +# octave 3.0.5 randomly crashes on the remaining tests
    +if !swig_octave_prereq(3,2,0)
    +  exit
    +endif
    +
    +# load module with no cvar
    +clear all;
    +swigexample2;
    +assert(swigexample2.ivar == ifunc);
    +assert(exist("swigexample2","var"));
    +assert(!isglobal("cvar"))
    +clear all
    +swigexample2;
    +assert(swigexample2.ivar == ifunc);
    +assert(exist("swigexample2","var"));
    +assert(!isglobal("cvar"))
    +clear all
    diff --git a/Examples/octave/module_load/runme_args.m b/Examples/octave/module_load/runme_args.m
    deleted file mode 100644
    index 716ee31f9..000000000
    --- a/Examples/octave/module_load/runme_args.m
    +++ /dev/null
    @@ -1,48 +0,0 @@
    -# file: runme_args.m
    -
    -# test module loading with arguments
    -
    -##### BEGIN TEST #####
    -# test help
    -example -help
    -assert(!isglobal("example"))
    -
    -# load module with custom cvar
    -example -globals mycvar
    -assert(!isglobal("cvar"))
    -assert(mycvar.ivar == example.ifunc())
    -##### END TEST #####
    -
    -# clearing a module results in a segfault for Octave <= 3.0.*
    -# (tested on Octave 3.0.5), so skip the following test
    -try
    -  vers = cellfun("str2num", strsplit(OCTAVE_VERSION, "."));
    -catch
    -  vers = cellfun("str2num", cellstr(split(OCTAVE_VERSION, ".")));
    -end_try_catch
    -assert(length(vers) >= 2);
    -if vers(1) < 3 || (vers(1) == 3 && vers(2) == 0)
    -  disp("skipping 'clear all' test");
    -  return
    -endif
    -
    -clear all;
    -
    -##### BEGIN TEST #####
    -# test help
    -example -help
    -assert(!isglobal("example"))
    -
    -# load module with custom cvar
    -example -globals mycvar
    -assert(!isglobal("cvar"))
    -assert(mycvar.ivar == example.ifunc())
    -##### END TEST #####
    -
    -clear all;
    -
    -##### BEGIN TEST #####
    -# load module with root-level cvar
    -example -globals .
    -assert(example.ivar == example.ifunc())
    -##### END TEST #####
    diff --git a/Examples/octave/module_load/runme_gl_func.m b/Examples/octave/module_load/runme_gl_func.m
    deleted file mode 100644
    index 1624cdd9a..000000000
    --- a/Examples/octave/module_load/runme_gl_func.m
    +++ /dev/null
    @@ -1,59 +0,0 @@
    -# file: runme_gl_func.m
    -
    -# test whether module can be loaded
    -# in a function (global cvar)
    -
    -1;
    -
    -##### BEGIN TEST #####
    -function func
    -  example
    -  global cvar
    -  assert(cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test that everything works from the base context
    -example
    -global cvar
    -assert(cvar.ivar == example.ifunc())
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -##### END TEST #####
    -
    -# clearing a module results in a segfault for Octave <= 3.0.*
    -# (tested on Octave 3.0.5), so skip the following test
    -try
    -  vers = cellfun("str2num", strsplit(OCTAVE_VERSION, "."));
    -catch
    -  vers = cellfun("str2num", cellstr(split(OCTAVE_VERSION, ".")));
    -end_try_catch
    -assert(length(vers) >= 2);
    -if vers(1) < 3 || (vers(1) == 3 && vers(2) == 0)
    -  disp("skipping 'clear all' test");
    -  return
    -endif
    -
    -clear all;
    -
    -##### BEGIN TEST #####
    -function func
    -  example
    -  global cvar
    -  assert(cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test that everything works from the base context
    -example
    -global cvar
    -assert(cvar.ivar == example.ifunc())
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -##### END TEST #####
    diff --git a/Examples/octave/module_load/runme_gl_func_base.m b/Examples/octave/module_load/runme_gl_func_base.m
    deleted file mode 100644
    index 0e3eb6112..000000000
    --- a/Examples/octave/module_load/runme_gl_func_base.m
    +++ /dev/null
    @@ -1,59 +0,0 @@
    -# file: runme_gl_func_base.m
    -
    -# test whether module can be loaded in a function
    -# before the base context (global cvar)
    -
    -1;
    -
    -##### BEGIN TEST #####
    -function func
    -  example
    -  global cvar
    -  assert(cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -
    -# test that everything works from the base context
    -example
    -global cvar
    -assert(cvar.ivar == example.ifunc())
    -##### END TEST #####
    -
    -# clearing a module results in a segfault for Octave <= 3.0.*
    -# (tested on Octave 3.0.5), so skip the following test
    -try
    -  vers = cellfun("str2num", strsplit(OCTAVE_VERSION, "."));
    -catch
    -  vers = cellfun("str2num", cellstr(split(OCTAVE_VERSION, ".")));
    -end_try_catch
    -assert(length(vers) >= 2);
    -if vers(1) < 3 || (vers(1) == 3 && vers(2) == 0)
    -  disp("skipping 'clear all' test");
    -  return
    -endif
    -
    -clear all;
    -
    -##### BEGIN TEST #####
    -function func
    -  example
    -  global cvar
    -  assert(cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -
    -# test that everything works from the base context
    -example
    -global cvar
    -assert(cvar.ivar == example.ifunc())
    -##### END TEST #####
    diff --git a/Examples/octave/module_load/runme_nogl_func.m b/Examples/octave/module_load/runme_nogl_func.m
    deleted file mode 100644
    index fd8e19f37..000000000
    --- a/Examples/octave/module_load/runme_nogl_func.m
    +++ /dev/null
    @@ -1,55 +0,0 @@
    -# file: runme_nogl_func.m
    -
    -# test whether module can be loaded
    -# in a function (no global cvar)
    -
    -1;
    -
    -##### BEGIN TEST #####
    -function func
    -  example -noglobal
    -  assert(example.cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test that everything works from the base context
    -example -noglobal
    -assert(example.cvar.ivar == example.ifunc())
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -##### END TEST #####
    -
    -# clearing a module results in a segfault for Octave <= 3.0.*
    -# (tested on Octave 3.0.5), so skip the following test
    -try
    -  vers = cellfun("str2num", strsplit(OCTAVE_VERSION, "."));
    -catch
    -  vers = cellfun("str2num", cellstr(split(OCTAVE_VERSION, ".")));
    -end_try_catch
    -assert(length(vers) >= 2);
    -if vers(1) < 3 || (vers(1) == 3 && vers(2) == 0)
    -  disp("skipping 'clear all' test");
    -  return
    -endif
    -
    -clear all;
    -
    -##### BEGIN TEST #####
    -function func
    -  example -noglobal
    -  assert(example.cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test that everything works from the base context
    -example -noglobal
    -assert(example.cvar.ivar == example.ifunc())
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -##### END TEST #####
    diff --git a/Examples/octave/module_load/runme_nogl_func_base.m b/Examples/octave/module_load/runme_nogl_func_base.m
    deleted file mode 100644
    index bb8da9328..000000000
    --- a/Examples/octave/module_load/runme_nogl_func_base.m
    +++ /dev/null
    @@ -1,55 +0,0 @@
    -# file: runme_nogl_func_base.m
    -
    -# test whether module can be loaded in a function
    -# before the base context (no global cvar)
    -
    -1;
    -
    -##### BEGIN TEST #####
    -function func
    -  example -noglobal
    -  assert(example.cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -
    -# test that everything works from the base context
    -example -noglobal
    -assert(example.cvar.ivar == example.ifunc())
    -##### END TEST #####
    -
    -# clearing a module results in a segfault for Octave <= 3.0.*
    -# (tested on Octave 3.0.5), so skip the following test
    -try
    -  vers = cellfun("str2num", strsplit(OCTAVE_VERSION, "."));
    -catch
    -  vers = cellfun("str2num", cellstr(split(OCTAVE_VERSION, ".")));
    -end_try_catch
    -assert(length(vers) >= 2);
    -if vers(1) < 3 || (vers(1) == 3 && vers(2) == 0)
    -  disp("skipping 'clear all' test");
    -  return
    -endif
    -
    -clear all;
    -
    -##### BEGIN TEST #####
    -function func
    -  example -noglobal
    -  assert(example.cvar.ivar == example.ifunc())
    -endfunction
    -
    -# test loading in a function
    -func
    -
    -# test a second time to check everything works
    -func
    -
    -# test that everything works from the base context
    -example -noglobal
    -assert(example.cvar.ivar == example.ifunc())
    -##### END TEST #####
    diff --git a/Examples/octave/operator/Makefile b/Examples/octave/operator/Makefile
    index de818a41a..acf4d0575 100644
    --- a/Examples/octave/operator/Makefile
    +++ b/Examples/octave/operator/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).m
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/operator/example.h b/Examples/octave/operator/example.h
    index a9b69e009..d91adabe8 100644
    --- a/Examples/octave/operator/example.h
    +++ b/Examples/octave/operator/example.h
    @@ -25,7 +25,7 @@ public:
       ComplexVal operator-() const {
         return ComplexVal(-rpart, -ipart);
       }
    -  
    +
       double re() const { return rpart; }
       double im() const { return ipart; }
     };
    diff --git a/Examples/octave/operator/example.i b/Examples/octave/operator/example.i
    index 7b903e69b..937e8d39d 100644
    --- a/Examples/octave/operator/example.i
    +++ b/Examples/octave/operator/example.i
    @@ -1,6 +1,10 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
    +
     #pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ
    +
     %{
     #include "example.h"
     %}
    @@ -22,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 85fd99ad4..83197b410 100644
    --- a/Examples/octave/operator/runme.m
    +++ b/Examples/octave/operator/runme.m
    @@ -1,8 +1,8 @@
     # Operator overloading example
    -example
    +swigexample
     
    -a = example.ComplexVal(2,3);
    -b = example.ComplexVal(-5,10);
    +a = swigexample.ComplexVal(2,3);
    +b = swigexample.ComplexVal(-5,10);
     
     printf("a   = %s\n",disp(a));
     printf("b   = %s\n",disp(b));
    @@ -12,7 +12,7 @@ printf("c   = %s\n",disp(c));
     printf("a*b = %s\n",disp(a*b));
     printf("a-c = %s\n",disp(a-c));
     
    -e = example.ComplexVal(a-c);
    +e = swigexample.ComplexVal(a-c);
     printf("e   = %s\n",disp(e));
     
     # Big expression
    @@ -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/octave/pointer/Makefile b/Examples/octave/pointer/Makefile
    index 464b74122..413b64bbd 100644
    --- a/Examples/octave/pointer/Makefile
    +++ b/Examples/octave/pointer/Makefile
    @@ -1,20 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    +SRCS = example.c
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/pointer/example.i b/Examples/octave/pointer/example.i
    index a8ac79499..8b9e0f134 100644
    --- a/Examples/octave/pointer/example.i
    +++ b/Examples/octave/pointer/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %{
     extern void add(int *, int *, int *);
    @@ -24,7 +26,3 @@ extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
     
     %apply int *OUTPUT { int *r };
     extern int divide(int n, int d, int *r);
    -
    -
    -
    -
    diff --git a/Examples/octave/pointer/runme.m b/Examples/octave/pointer/runme.m
    index c36df7270..a76de67de 100644
    --- a/Examples/octave/pointer/runme.m
    +++ b/Examples/octave/pointer/runme.m
    @@ -1,42 +1,39 @@
     # file: runme.m
     
    -example;
    +swigexample;
     
     # First create some objects using the pointer library.
     printf("Testing the pointer library\n");
    -a = example.new_intp();
    -b = example.new_intp();
    -c = example.new_intp();
    -example.intp_assign(a,37);
    -example.intp_assign(b,42);
    +a = swigexample.new_intp();
    +b = swigexample.new_intp();
    +c = swigexample.new_intp();
    +swigexample.intp_assign(a,37);
    +swigexample.intp_assign(b,42);
     
     a,b,c
     
     # Call the add() function with some pointers
    -example.add(a,b,c);
    +swigexample.add(a,b,c);
     
     # Now get the result
    -r = example.intp_value(c);
    +r = swigexample.intp_value(c);
     printf("     37 + 42 = %i\n",r);
     
     # Clean up the pointers
    -example.delete_intp(a);
    -example.delete_intp(b);
    -example.delete_intp(c);
    +swigexample.delete_intp(a);
    +swigexample.delete_intp(b);
    +swigexample.delete_intp(c);
     
     # Now try the typemap library
     # This should be much easier. Now how it is no longer
     # necessary to manufacture pointers.
     
     printf("Trying the typemap library\n");
    -r = example.sub(37,42);
    +r = swigexample.sub(37,42);
     printf("     37 - 42 = %i\n",r);
     
     # Now try the version with multiple return values
     
     printf("Testing multiple return values\n");
    -[q,r] = example.divide(42,37);
    +[q,r] = swigexample.divide(42,37);
     printf("     42/37 = %d remainder %d\n",q,r);
    -
    -
    -
    diff --git a/Examples/octave/reference/Makefile b/Examples/octave/reference/Makefile
    index 21fb21137..3b746de2f 100644
    --- a/Examples/octave/reference/Makefile
    +++ b/Examples/octave/reference/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = example.cxx
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS = example.cxx
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/reference/example.cxx b/Examples/octave/reference/example.cxx
    index 8a513bf49..632a03a5b 100644
    --- a/Examples/octave/reference/example.cxx
    +++ b/Examples/octave/reference/example.cxx
    @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) {
     
     char *Vector::print() {
       static char temp[512];
    -  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
    +  sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z);
       return temp;
     }
     
    @@ -43,4 +43,3 @@ Vector &VectorArray::operator[](int index) {
     int VectorArray::size() {
       return maxsize;
     }
    -
    diff --git a/Examples/octave/reference/example.h b/Examples/octave/reference/example.h
    index 4915adb1b..bcfcfb72f 100644
    --- a/Examples/octave/reference/example.h
    +++ b/Examples/octave/reference/example.h
    @@ -4,8 +4,8 @@ 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) { };
    +  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 *print();
     };
    @@ -20,7 +20,3 @@ public:
       Vector &operator[](int);
       int size();
     };
    -
    -
    -
    -  
    diff --git a/Examples/octave/reference/example.i b/Examples/octave/reference/example.i
    index 8c95b3213..0aa733451 100644
    --- a/Examples/octave/reference/example.i
    +++ b/Examples/octave/reference/example.i
    @@ -2,7 +2,9 @@
     
     /* This file has a few "typical" uses of C++ references. */
     
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %{
     #include "example.h"
    @@ -31,7 +33,7 @@ public:
       VectorArray(int maxsize);
       ~VectorArray();
       int size();
    -  
    +
       /* This wrapper provides an alternative to the [] operator */
       %extend {
         Vector &get(int index) {
    @@ -42,7 +44,3 @@ public:
         }
       }
     };
    -
    -
    -
    -
    diff --git a/Examples/octave/reference/runme.m b/Examples/octave/reference/runme.m
    index f59c8eb7d..630ee0cd2 100644
    --- a/Examples/octave/reference/runme.m
    +++ b/Examples/octave/reference/runme.m
    @@ -2,13 +2,13 @@
     
     # This file illustrates the manipulation of C++ references in Octave
     
    -example
    +swigexample
     
     # ----- Object creation -----
     
     printf("Creating some objects:\n");
    -a = example.Vector(3,4,5)
    -b = example.Vector(10,11,12)
    +a = swigexample.Vector(3,4,5)
    +b = swigexample.Vector(10,11,12)
     
     printf("    Created %s\n",a.cprint());
     printf("    Created %s\n",b.cprint());
    @@ -17,12 +17,12 @@ printf("    Created %s\n",b.cprint());
     
     # This calls the wrapper we placed around
     #
    -#      operator+(const Vector &a, const Vector &) 
    +#      operator+(const Vector &a, const Vector &)
     #
     # It returns a new allocated object.
     
     printf("Adding a+b\n");
    -c = example.addv(a,b);
    +c = swigexample.addv(a,b);
     printf("    a+b = %s\n", c.cprint());
     
     clear c
    @@ -31,7 +31,7 @@ clear c
     
     # Note: Using the high-level interface here
     printf("Creating an array of vectors\n");
    -va = example.VectorArray(10)
    +va = swigexample.VectorArray(10)
     
     # ----- Set some values in the array -----
     
    @@ -39,7 +39,7 @@ va = example.VectorArray(10)
     va.set(0,a);
     va.set(1,b);
     
    -va.set(2,example.addv(a,b))
    +va.set(2,swigexample.addv(a,b))
     
     # Get some values from the array
     
    @@ -60,4 +60,3 @@ printf("Cleaning up\n");
     clear va
     clear a
     clear b
    -
    diff --git a/Examples/octave/simple/Makefile b/Examples/octave/simple/Makefile
    index 464b74122..413b64bbd 100644
    --- a/Examples/octave/simple/Makefile
    +++ b/Examples/octave/simple/Makefile
    @@ -1,20 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    +SRCS = example.c
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/simple/example.c b/Examples/octave/simple/example.c
    index 1c2af789c..8df41189c 100644
    --- a/Examples/octave/simple/example.c
    +++ b/Examples/octave/simple/example.c
    @@ -14,5 +14,3 @@ int gcd(int x, int y) {
       }
       return g;
     }
    -
    -
    diff --git a/Examples/octave/simple/example.i b/Examples/octave/simple/example.i
    index 24093b9bf..a3006f282 100644
    --- a/Examples/octave/simple/example.i
    +++ b/Examples/octave/simple/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %inline %{
     extern int    gcd(int x, int y);
    diff --git a/Examples/octave/simple/runme.m b/Examples/octave/simple/runme.m
    index 8dc5eaa58..6345df0cf 100644
    --- a/Examples/octave/simple/runme.m
    +++ b/Examples/octave/simple/runme.m
    @@ -1,22 +1,21 @@
     # file: runme.m
     
    -example 
    +swigexample
     
     # Call our gcd() function
     
     x = 42
     y = 105
    -g = example.gcd(x,y)
    +g = swigexample.gcd(x,y)
     printf("The gcd of %d and %d is %d\n",x,y,g);
     
     # Manipulate the Foo global variable
     
     # Output its current value
    -example.cvar.Foo
    +swigexample.cvar.Foo
     
     # Change its value
    -example.cvar.Foo = 3.1415926
    +swigexample.cvar.Foo = 3.1415926
     
     # See if the change took effect
    -printf("Foo = %f\n", example.cvar.Foo);
    -
    +printf("Foo = %f\n", swigexample.cvar.Foo);
    diff --git a/Examples/octave/template/Makefile b/Examples/octave/template/Makefile
    index d64487430..acf4d0575 100644
    --- a/Examples/octave/template/Makefile
    +++ b/Examples/octave/template/Makefile
    @@ -1,22 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -CXXSRCS    = 
    -TARGET     = example
    -INTERFACE  = example.i
    -LIBS       = -lm
    -SWIGOPT    = 
    +CXXSRCS =
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
    -	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/template/example.h b/Examples/octave/template/example.h
    index 7401df650..5eb65dabb 100644
    --- a/Examples/octave/template/example.h
    +++ b/Examples/octave/template/example.h
    @@ -29,4 +29,3 @@ template class vector {
       }
     #endif
     };
    -
    diff --git a/Examples/octave/template/example.i b/Examples/octave/template/example.i
    index 8f94c4da1..3c57f3884 100644
    --- a/Examples/octave/template/example.i
    +++ b/Examples/octave/template/example.i
    @@ -1,5 +1,7 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
     
     %{
     #include "example.h"
    @@ -14,4 +16,3 @@
     %template(maxdouble) max;
     %template(vecint) vector;
     %template(vecdouble) vector;
    -
    diff --git a/Examples/octave/template/runme.m b/Examples/octave/template/runme.m
    index a9891d459..b0abbf22f 100644
    --- a/Examples/octave/template/runme.m
    +++ b/Examples/octave/template/runme.m
    @@ -1,15 +1,15 @@
     # file: runme.m
     
    -example
    +swigexample
     
     # Call some templated functions
    -example.maxint(3,7)
    -example.maxdouble(3.14,2.18)
    +swigexample.maxint(3,7)
    +swigexample.maxdouble(3.14,2.18)
     
     # Create some class
     
    -iv = example.vecint(100)
    -dv = example.vecdouble(1000)
    +iv = swigexample.vecint(100)
    +dv = swigexample.vecdouble(1000)
     
     for i=0:99,
       iv.setitem(i,2*i);
    @@ -33,5 +33,3 @@ sum
     
     clear iv
     clear dv
    -
    -      
    diff --git a/Examples/octave/variables/Makefile b/Examples/octave/variables/Makefile
    index 464b74122..413b64bbd 100644
    --- a/Examples/octave/variables/Makefile
    +++ b/Examples/octave/variables/Makefile
    @@ -1,20 +1,3 @@
    -TOP        = ../..
    -SWIG       = $(TOP)/../preinst-swig
    -SRCS       = example.c
    -TARGET     = example
    -INTERFACE  = example.i
    +SRCS = example.c
     
    -all::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
    -
    -static::
    -	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
    -	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
    -
    -clean::
    -	$(MAKE) -f $(TOP)/Makefile octave_clean
    -	rm -f $(TARGET).py
    -
    -check: all
    -	$(MAKE) -f $(TOP)/Makefile octave_run
    +include $(SRCDIR)../example.mk
    diff --git a/Examples/octave/variables/example.c b/Examples/octave/variables/example.c
    index aa4ffe9b3..a9102a9d5 100644
    --- a/Examples/octave/variables/example.c
    +++ b/Examples/octave/variables/example.c
    @@ -11,7 +11,7 @@
     #include 
     #include "example.h"
     
    -int              ivar = 0;                    
    +int              ivar = 0;
     short            svar = 0;
     long             lvar = 0;
     unsigned int     uivar = 0;
    @@ -51,10 +51,10 @@ void print_vars() {
       printf("dvar      = %g\n", dvar);
       printf("cvar      = %c\n", cvar);
       printf("strvar    = %s\n", strvar ? strvar : "(null)");
    -  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
    -  printf("iptrvar   = %p\n", iptrvar);
    +  printf("cstrvar   = %s\n", cstrvar);
    +  printf("iptrvar   = %p\n", (void *)iptrvar);
       printf("name      = %s\n", name);
    -  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
    +  printf("ptptr     = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
       printf("pt        = (%d, %d)\n", pt.x, pt.y);
       printf("status    = %d\n", status);
     }
    diff --git a/Examples/octave/variables/example.h b/Examples/octave/variables/example.h
    index 0f7e89594..8d95fa1a4 100644
    --- a/Examples/octave/variables/example.h
    +++ b/Examples/octave/variables/example.h
    @@ -3,4 +3,3 @@
     typedef struct {
       int x,y;
     } Point;
    -
    diff --git a/Examples/octave/variables/example.i b/Examples/octave/variables/example.i
    index 639b6c704..9d8b03ec2 100644
    --- a/Examples/octave/variables/example.i
    +++ b/Examples/octave/variables/example.i
    @@ -1,5 +1,8 @@
     /* File : example.i */
    -%module example
    +%module swigexample
    +
    +%feature("autodoc", 1);
    +
     %{
     #include "example.h"
     %}
    @@ -50,4 +53,3 @@ extern Point *new_Point(int x, int y);
     extern char  *Point_print(Point *p);
     extern void  pt_print();
     %}
    -
    diff --git a/Examples/octave/variables/runme.m b/Examples/octave/variables/runme.m
    index db88b18b0..c6788398b 100644
    --- a/Examples/octave/variables/runme.m
    +++ b/Examples/octave/variables/runme.m
    @@ -1,56 +1,56 @@
     # file: runme.m
     
    -example
    +swigexample
     
     # Try to set the values of some global variables
     
    -example.cvar.ivar   =  42;
    -example.cvar.svar   = -31000;
    -example.cvar.lvar   =  65537;
    -example.cvar.uivar  =  123456;
    -example.cvar.usvar  =  61000;
    -example.cvar.ulvar  =  654321;
    -example.cvar.scvar  =  -13;
    -example.cvar.ucvar  =  251;
    -example.cvar.cvar   =  "S";
    -example.cvar.fvar   =  3.14159;
    -example.cvar.dvar   =  2.1828;
    -example.cvar.strvar =  "Hello World";
    -example.cvar.iptrvar= example.new_int(37);
    -example.cvar.ptptr  = example.new_Point(37,42);
    -example.cvar.name   = "Bill";
    +swigexample.cvar.ivar   =  42;
    +swigexample.cvar.svar   = -31000;
    +swigexample.cvar.lvar   =  65537;
    +swigexample.cvar.uivar  =  123456;
    +swigexample.cvar.usvar  =  61000;
    +swigexample.cvar.ulvar  =  654321;
    +swigexample.cvar.scvar  =  -13;
    +swigexample.cvar.ucvar  =  251;
    +swigexample.cvar.cvar   =  "S";
    +swigexample.cvar.fvar   =  3.14159;
    +swigexample.cvar.dvar   =  2.1828;
    +swigexample.cvar.strvar =  "Hello World";
    +swigexample.cvar.iptrvar= swigexample.new_int(37);
    +swigexample.cvar.ptptr  = swigexample.new_Point(37,42);
    +swigexample.cvar.name   = "Bill";
     
     # Now print out the values of the variables
     
     printf("Variables (values printed from Octave)\n");
     
    -printf("ivar      = %i\n", example.cvar.ivar);
    -printf("svar      = %i\n", example.cvar.svar);
    -printf("lvar      = %i\n", example.cvar.lvar);
    -printf("uivar     = %i\n", example.cvar.uivar);
    -printf("usvar     = %i\n", example.cvar.usvar);
    -printf("ulvar     = %i\n", example.cvar.ulvar);
    -printf("scvar     = %i\n", example.cvar.scvar);
    -printf("ucvar     = %i\n", example.cvar.ucvar);
    -printf("fvar      = %i\n", example.cvar.fvar);
    -printf("dvar      = %i\n", example.cvar.dvar);
    -printf("cvar      = %s\n", example.cvar.cvar);
    -printf("strvar    = %s\n", example.cvar.strvar);
    -#printf("cstrvar   = %s\n", example.cvar.cstrvar);
    -example.cvar.iptrvar
    -printf("name      = %i\n", example.cvar.name);
    -printf("ptptr     = %s\n", example.Point_print(example.cvar.ptptr));
    -#printf("pt        = %s\n", example.cvar.Point_print(example.cvar.pt));
    +printf("ivar      = %i\n", swigexample.cvar.ivar);
    +printf("svar      = %i\n", swigexample.cvar.svar);
    +printf("lvar      = %i\n", swigexample.cvar.lvar);
    +printf("uivar     = %i\n", swigexample.cvar.uivar);
    +printf("usvar     = %i\n", swigexample.cvar.usvar);
    +printf("ulvar     = %i\n", swigexample.cvar.ulvar);
    +printf("scvar     = %i\n", swigexample.cvar.scvar);
    +printf("ucvar     = %i\n", swigexample.cvar.ucvar);
    +printf("fvar      = %i\n", swigexample.cvar.fvar);
    +printf("dvar      = %i\n", swigexample.cvar.dvar);
    +printf("cvar      = %s\n", swigexample.cvar.cvar);
    +printf("strvar    = %s\n", swigexample.cvar.strvar);
    +#printf("cstrvar   = %s\n", swigexample.cvar.cstrvar);
    +swigexample.cvar.iptrvar
    +printf("name      = %i\n", swigexample.cvar.name);
    +printf("ptptr     = %s\n", swigexample.Point_print(swigexample.cvar.ptptr));
    +#printf("pt        = %s\n", swigexample.cvar.Point_print(swigexample.cvar.pt));
     
     printf("\nVariables (values printed from C)\n");
     
    -example.print_vars();
    +swigexample.print_vars();
     
     printf("\nNow I'm going to try and modify some read only variables\n");
     
     printf("     Tring to set 'path'\n");
     try
    -    example.cvar.path = "Whoa!";
    +    swigexample.cvar.path = "Whoa!";
         printf("Hey, what's going on?!?! This shouldn't work\n");
     catch
         printf("Good.\n");
    @@ -58,7 +58,7 @@ end_try_catch
     
     printf("     Trying to set 'status'\n");
     try
    -    example.cvar.status = 0;
    +    swigexample.cvar.status = 0;
         printf("Hey, what's going on?!?! This shouldn't work\n");
     catch
         printf("Good.\n");
    @@ -67,9 +67,6 @@ end_try_catch
     
     printf("\nI'm going to try and update a structure variable.\n");
     
    -example.cvar.pt = example.cvar.ptptr;
    -
    -printf("The new value is %s\n", example.Point_print(example.cvar.pt));
    -
    -
    +swigexample.cvar.pt = swigexample.cvar.ptptr;
     
    +printf("The new value is %s\n", swigexample.Point_print(swigexample.cvar.pt));
    diff --git a/Examples/perl5/callback/Makefile b/Examples/perl5/callback/Makefile
    new file mode 100644
    index 000000000..08271768c
    --- /dev/null
    +++ b/Examples/perl5/callback/Makefile
    @@ -0,0 +1,23 @@
    +TOP        = ../..
    +SWIGEXE    = $(TOP)/../swig
    +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
    +CXXSRCS    = example.cxx
    +TARGET     = example
    +INTERFACE  = example.i
    +LIBS       = -lm
    +
    +check: build
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run
    +
    +build:
    +	$(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
    +	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static
    +
    +clean:
    +	$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean
    diff --git a/Examples/perl5/callback/example.cxx b/Examples/perl5/callback/example.cxx
    new file mode 100644
    index 000000000..450d75608
    --- /dev/null
    +++ b/Examples/perl5/callback/example.cxx
    @@ -0,0 +1,4 @@
    +/* File : example.cxx */
    +
    +#include "example.h"
    +
    diff --git a/Examples/perl5/callback/example.h b/Examples/perl5/callback/example.h
    new file mode 100644
    index 000000000..1a0e8c432
    --- /dev/null
    +++ b/Examples/perl5/callback/example.h
    @@ -0,0 +1,23 @@
    +/* File : example.h */
    +
    +#include 
    +#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/perl5/callback/example.i b/Examples/perl5/callback/example.i
    new file mode 100644
    index 000000000..821a9e6b5
    --- /dev/null
    +++ b/Examples/perl5/callback/example.i
    @@ -0,0 +1,15 @@
    +/* File : example.i */
    +%module(directors="1") example
    +%{
    +#include "example.h"
    +%}
    +
    +/* turn on director wrapping Callback */
    +%feature("director") Callback;
    +
    +/* Caller::setCallback(Callback *cb) gives ownership of the cb to the
    + * Caller object.  The wrapper code should understand this. */
    +%apply SWIGTYPE *DISOWN { Callback *cb }; 
    +
    +%include "example.h"
    +
    diff --git a/Examples/perl5/callback/index.html b/Examples/perl5/callback/index.html
    new file mode 100644
    index 000000000..82f5e972a
    --- /dev/null
    +++ b/Examples/perl5/callback/index.html
    @@ -0,0 +1,20 @@
    +
    +
    +SWIG:Examples:perl5:callback
    +
    +
    +
    +
    +
    +SWIG/Examples/perl/callback/
    +
    + +

    Implementing C++ callbacks in Perl

    + +

    +This example illustrates how to use directors to implement C++ callbacks. +

    + +
    + + diff --git a/Examples/perl5/callback/runme.pl b/Examples/perl5/callback/runme.pl new file mode 100644 index 000000000..54d86783a --- /dev/null +++ b/Examples/perl5/callback/runme.pl @@ -0,0 +1,48 @@ +# file: runme.pl + +# This file illustrates the cross language polymorphism using directors. + +use example; + + +{ + package PlCallback; + use base 'example::Callback'; + sub run { + print "PlCallback->run()\n"; + } +} + +# Create an Caller instance + +$caller = example::Caller->new(); + +# Add a simple C++ callback (caller owns the callback, so +# we disown it first by clearing the .thisown flag). + +print "Adding and calling a normal C++ callback\n"; +print "----------------------------------------\n"; + +$callback = example::Callback->new(); +$callback->DISOWN(); +$caller->setCallback($callback); +$caller->call(); +$caller->delCallback(); + +print "\n"; +print "Adding and calling a Perl callback\n"; +print "----------------------------------\n"; + +# Add a Perl callback (caller owns the callback, so we +# disown it first by calling DISOWN). + +$callback = PlCallback->new(); +$callback->DISOWN(); +$caller->setCallback($callback); +$caller->call(); +$caller->delCallback(); + +# All done. + +print "\n"; +print "perl exit\n"; diff --git a/Examples/perl5/check.list b/Examples/perl5/check.list index e15f02e18..dda849311 100644 --- a/Examples/perl5/check.list +++ b/Examples/perl5/check.list @@ -1,7 +1,9 @@ # see top-level Makefile.in +callback class constants constants2 +extend funcptr import java diff --git a/Examples/perl5/class/Makefile b/Examples/perl5/class/Makefile index f53361730..08271768c 100644 --- a/Examples/perl5/class/Makefile +++ b/Examples/perl5/class/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/class/example.cxx b/Examples/perl5/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/perl5/class/example.cxx +++ b/Examples/perl5/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/perl5/class/example.dsp b/Examples/perl5/class/example.dsp index b5ccd1928..3aef4e24e 100644 --- a/Examples/perl5/class/example.dsp +++ b/Examples/perl5/class/example.dsp @@ -126,7 +126,7 @@ InputName=example echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build @@ -141,7 +141,7 @@ InputName=example echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/class/example.h b/Examples/perl5/class/example.h index b0671d583..fd6943541 100644 --- a/Examples/perl5/class/example.h +++ b/Examples/perl5/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,29 +19,24 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; typedef Square TSquare; class CFoo { public: - static Square MakeSquare(void) {return Square(4.0);}; - static TSquare MakeTSquare(void) {return Square(4.0);}; + static Square MakeSquare(void) {return Square(4.0);} + static TSquare MakeTSquare(void) {return Square(4.0);} }; - - - - - diff --git a/Examples/perl5/class/example.i b/Examples/perl5/class/example.i index 23ee8a822..fbdf7249f 100644 --- a/Examples/perl5/class/example.i +++ b/Examples/perl5/class/example.i @@ -6,6 +6,4 @@ %} /* Let's just grab the original header file here */ - %include "example.h" - diff --git a/Examples/perl5/class/index.html b/Examples/perl5/class/index.html index 58a50ad2e..b4f923b5a 100644 --- a/Examples/perl5/class/index.html +++ b/Examples/perl5/class/index.html @@ -32,8 +32,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +44,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +53,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -82,7 +82,7 @@ like this: Note: when creating a C++ extension, you must run SWIG with the -c++ option like this:
    -% swig -c++ -python example.i
    +% swig -c++ -perl example.i
     
    @@ -97,60 +97,45 @@ Click here to see a script that calls the C++ functions f
    -$c = example::new_Circle(10.0);
    +$c = new example::Circle(10.0);
     

    -

  • To access member data, a pair of accessor functions are used. -For example: +
  • You can access member data like so:
    -example::Shape_x_set($c,15);    # Set member data
    -$x = example::Shape_x_get($c);   # Get member data
    -
    -
    - -Note: when accessing member data, the name of the class in which -the data member is defined is used. For example Shape_x_get(). - -

    -

  • To invoke a member function, you simply do this - -
    -
    -print "The area is ", example::Shape_area($c);
    +$c->{x} = 15;    # Set member data
    +$x = $c->{x};    # Get member data
     

    -

  • Type checking knows about the inheritance structure of C++. For example: +
  • To invoke a member function, you simply do this:
    -example::Shape_area($c);       # Works (c is a Shape)
    -example::Circle_area($c);      # Works (c is a Circle)
    -example::Square_area($c);      # Fails (c is definitely not a Square)
    +print "The area is ", $c->area();
     

    -

  • To invoke a destructor, simply do this +
  • To invoke a destructor, simply do this:
    -example::delete_Shape($c);     # Deletes a shape
    +$c->DESTROY();   # Deletes a shape
     

    -

  • Static member variables are wrapped as C global variables. For example: +
  • Static member variables are wrapped like so:
    -$n = $example::Shape_nshapes;     # Get a static data member
    -$example::Shapes_nshapes = 13;   # Set a static data member
    +$n = $example::Shape::nshapes;    # Get a static data member
    +$example::Shapes::nshapes = 13;   # Set a static data member
     
    @@ -159,47 +144,11 @@ $example::Shapes_nshapes = 13; # Set a static data member

    General Comments

      -
    • This low-level interface is not the only way to handle C++ code. Proxy classes -provide a much higher-level interface. - -

      -

    • SWIG *does* know how to properly perform upcasting of objects in an inheritance +
    • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class. -

      -

    • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

      -

        -
      • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
        -
        -void foo(int a);  
        -%name(foo2) void foo(double a, double b);
        -
        -
        - -

        -

      • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
        -
        -%inline %{
        -    Vector *vector_add(Vector *a, Vector *b) {
        -          ... whatever ...
        -    }
        -%}
        -
        -
        - -

        -

      • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). +
      • C++ Namespaces - %nspace isn't yet supported for Perl.
      diff --git a/Examples/perl5/class/runme.pl b/Examples/perl5/class/runme.pl index 076e1437b..e45e2b8ce 100644 --- a/Examples/perl5/class/runme.pl +++ b/Examples/perl5/class/runme.pl @@ -40,7 +40,7 @@ foreach $o ($c,$s) { print " $o\n"; print " area = ", $o->area(), "\n"; print " perimeter = ", $o->perimeter(), "\n"; - } +} # ----- Delete everything ----- diff --git a/Examples/perl5/constants/Makefile b/Examples/perl5/constants/Makefile index 576d2a095..b0dc67806 100644 --- a/Examples/perl5/constants/Makefile +++ b/Examples/perl5/constants/Makefile @@ -1,18 +1,23 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/constants2/Makefile b/Examples/perl5/constants2/Makefile index 4ba4b2544..db676cc4e 100644 --- a/Examples/perl5/constants2/Makefile +++ b/Examples/perl5/constants2/Makefile @@ -1,18 +1,23 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i SWIGOPT = -const -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/extend/Makefile b/Examples/perl5/extend/Makefile new file mode 100644 index 000000000..08271768c --- /dev/null +++ b/Examples/perl5/extend/Makefile @@ -0,0 +1,23 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = -lm + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/extend/example.cxx b/Examples/perl5/extend/example.cxx new file mode 100644 index 000000000..450d75608 --- /dev/null +++ b/Examples/perl5/extend/example.cxx @@ -0,0 +1,4 @@ +/* File : example.cxx */ + +#include "example.h" + diff --git a/Examples/python/swigrun/example.h b/Examples/perl5/extend/example.h similarity index 92% rename from Examples/python/swigrun/example.h rename to Examples/perl5/extend/example.h index 69e6fe4de..ca1aed28f 100644 --- a/Examples/python/swigrun/example.h +++ b/Examples/perl5/extend/example.h @@ -14,7 +14,7 @@ public: 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", this); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; @@ -54,5 +54,3 @@ public: } }; -Manager* convert_to_Manager(PyObject *obj); - diff --git a/Examples/perl5/extend/example.i b/Examples/perl5/extend/example.i new file mode 100644 index 000000000..f5e142b88 --- /dev/null +++ b/Examples/perl5/extend/example.i @@ -0,0 +1,20 @@ +/* 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; + +/* EmployeeList::addEmployee(Employee *p) gives ownership of the + * employee to the EmployeeList object. The wrapper code should + * understand this. */ +%apply SWIGTYPE *DISOWN { Employee *p }; + +%include "example.h" + diff --git a/Examples/perl5/extend/index.html b/Examples/perl5/extend/index.html new file mode 100644 index 000000000..e9d886bcf --- /dev/null +++ b/Examples/perl5/extend/index.html @@ -0,0 +1,19 @@ + + +SWIG:Examples:perl5:extend + + + + + +SWIG/Examples/perl5/extend/ +
      + +

      Extending a simple C++ class

      + +

      +This example illustrates the extending of a C++ class with cross language polymorphism. + +


      + + diff --git a/Examples/perl5/extend/runme.pl b/Examples/perl5/extend/runme.pl new file mode 100644 index 000000000..76ee849a4 --- /dev/null +++ b/Examples/perl5/extend/runme.pl @@ -0,0 +1,79 @@ +# file: runme.pl + +# This file illustrates the cross language polymorphism using directors. + +use example; + + +# CEO class, which overrides Employee::getPosition(). + +{ + package CEO; + use base 'example::Manager'; + sub getPosition { + return "CEO"; + } +} + + +# Create an instance of our employee extension class, CEO. The calls to +# getName() and getPosition() are standard, the call to getTitle() uses +# the director wrappers to call CEO->getPosition. $e = CEO->new("Alice") + +$e = CEO->new("Alice"); +print $e->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 = example::EmployeeList->new(); + +# EmployeeList owns its items, so we must surrender ownership of objects +# we add. This involves calling the DISOWN method to tell the +# C++ director to start reference counting. + +$e->DISOWN(); +$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 Perl. 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, Perl resolved the call +# immediately in CEO, but now Perl 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 Perl 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 Perl destructor runs, and is still +# able to call self.getName() since the underlying C++ object still +# exists. After this destructor runs the remaining C++ destructors run as +# usual to destroy the object. + +undef $list; +print "----------------------\n"; + +# All done. + +print "perl exit\n"; diff --git a/Examples/perl5/funcptr/Makefile b/Examples/perl5/funcptr/Makefile index ce2bbb5b9..dfc01843e 100644 --- a/Examples/perl5/funcptr/Makefile +++ b/Examples/perl5/funcptr/Makefile @@ -1,18 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/import/Makefile b/Examples/perl5/import/Makefile index 60dfdfcee..e9225af25 100644 --- a/Examples/perl5/import/Makefile +++ b/Examples/perl5/import/Makefile @@ -1,20 +1,25 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = -all:: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='baseclass' INTERFACE='base.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' perl5_cpp +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run +build: + $(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 perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/import/bar.dsp b/Examples/perl5/import/bar.dsp index 64786b8f6..a329898ee 100644 --- a/Examples/perl5/import/bar.dsp +++ b/Examples/perl5/import/bar.dsp @@ -118,7 +118,7 @@ InputName=bar echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=bar echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/import/base.dsp b/Examples/perl5/import/base.dsp index 920891cbf..f52f1e956 100644 --- a/Examples/perl5/import/base.dsp +++ b/Examples/perl5/import/base.dsp @@ -118,7 +118,7 @@ InputName=base echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=base echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/import/base.h b/Examples/perl5/import/base.h index 5a266f68c..c0b47956b 100644 --- a/Examples/perl5/import/base.h +++ b/Examples/perl5/import/base.h @@ -2,8 +2,8 @@ class Base { public: - Base() { }; - virtual ~Base() { }; + Base() { } + virtual ~Base() { } virtual void A() { printf("I'm Base::A\n"); } diff --git a/Examples/perl5/import/foo.dsp b/Examples/perl5/import/foo.dsp index d519a5316..e959e9f92 100644 --- a/Examples/perl5/import/foo.dsp +++ b/Examples/perl5/import/foo.dsp @@ -118,7 +118,7 @@ InputName=foo echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=foo echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/import/spam.dsp b/Examples/perl5/import/spam.dsp index e5c8046eb..875efac89 100644 --- a/Examples/perl5/import/spam.dsp +++ b/Examples/perl5/import/spam.dsp @@ -118,7 +118,7 @@ InputName=spam echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=spam echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -c++ -perl5 $(InputPath) + ..\..\..\swig.exe -c++ -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/index.html b/Examples/perl5/index.html index db46023c4..23c8ff658 100644 --- a/Examples/perl5/index.html +++ b/Examples/perl5/index.html @@ -20,6 +20,8 @@ certain C declarations are turned into constants.
    • reference. C++ references.
    • pointer. Simple pointer handling.
    • funcptr. Pointers to functions. +
    • callback. C++ callbacks using directors. +
    • extend. Extending a simple C++ class.

    Compilation Issues

    diff --git a/Examples/perl5/inline/Makefile b/Examples/perl5/inline/Makefile index 4ac085ec3..5c98748c1 100644 --- a/Examples/perl5/inline/Makefile +++ b/Examples/perl5/inline/Makefile @@ -1,7 +1,6 @@ -all: - run: - perl runme.pl + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run clean: - rm -fr _Inline *~ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean + rm -rf _Inline diff --git a/Examples/perl5/java/Makefile b/Examples/perl5/java/Makefile index 882eba70f..7c133235f 100644 --- a/Examples/perl5/java/Makefile +++ b/Examples/perl5/java/Makefile @@ -1,26 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -all:: Example.class - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj" \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: Example.class Example.h + $(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 +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean + rm -f *.class Example.h -clean:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - rm -f *.class Example.h - -check: all - -run: - perl runme.pl - -Example.class: Example.java - gcj -fPIC -C -c -g Example.java - gcjh Example - +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java + gcjh Example.class diff --git a/Examples/perl5/multimap/Makefile b/Examples/perl5/multimap/Makefile index ce2bbb5b9..dfc01843e 100644 --- a/Examples/perl5/multimap/Makefile +++ b/Examples/perl5/multimap/Makefile @@ -1,18 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/multimap/example.dsp b/Examples/perl5/multimap/example.dsp index be8a0070e..21bdf8dca 100644 --- a/Examples/perl5/multimap/example.dsp +++ b/Examples/perl5/multimap/example.dsp @@ -122,7 +122,7 @@ InputName=example echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -perl5 $(InputPath) + ..\..\..\swig.exe -perl5 "$(InputPath)" # End Custom Build @@ -137,7 +137,7 @@ InputName=example echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -perl5 $(InputPath) + ..\..\..\swig.exe -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/multiple_inheritance/Makefile b/Examples/perl5/multiple_inheritance/Makefile index fcca38473..b73356e3e 100644 --- a/Examples/perl5/multiple_inheritance/Makefile +++ b/Examples/perl5/multiple_inheritance/Makefile @@ -1,19 +1,23 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i -LIBS = +LIBS = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/pointer/Makefile b/Examples/perl5/pointer/Makefile index ce2bbb5b9..dfc01843e 100644 --- a/Examples/perl5/pointer/Makefile +++ b/Examples/perl5/pointer/Makefile @@ -1,18 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/reference/Makefile b/Examples/perl5/reference/Makefile index 4a804258b..c4212099e 100644 --- a/Examples/perl5/reference/Makefile +++ b/Examples/perl5/reference/Makefile @@ -1,20 +1,24 @@ 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 LIBS = -lm -SWIGOPT = -noproxy +SWIGOPT = -noproxy -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/reference/example.cxx b/Examples/perl5/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/perl5/reference/example.cxx +++ b/Examples/perl5/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/perl5/reference/example.h b/Examples/perl5/reference/example.h index 4915adb1b..bcfcfb72f 100644 --- a/Examples/perl5/reference/example.h +++ b/Examples/perl5/reference/example.h @@ -4,8 +4,8 @@ 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) { }; + 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 *print(); }; @@ -20,7 +20,3 @@ public: Vector &operator[](int); int size(); }; - - - - diff --git a/Examples/perl5/reference/example.i b/Examples/perl5/reference/example.i index 6daa3b1f4..173143d79 100644 --- a/Examples/perl5/reference/example.i +++ b/Examples/perl5/reference/example.i @@ -29,7 +29,7 @@ public: VectorArray(int maxsize); ~VectorArray(); int size(); - + /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { @@ -40,7 +40,3 @@ public: } } }; - - - - diff --git a/Examples/perl5/simple/Makefile b/Examples/perl5/simple/Makefile index ce2bbb5b9..dfc01843e 100644 --- a/Examples/perl5/simple/Makefile +++ b/Examples/perl5/simple/Makefile @@ -1,18 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/simple/example.dsp b/Examples/perl5/simple/example.dsp index be8a0070e..21bdf8dca 100644 --- a/Examples/perl5/simple/example.dsp +++ b/Examples/perl5/simple/example.dsp @@ -122,7 +122,7 @@ InputName=example echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -perl5 $(InputPath) + ..\..\..\swig.exe -perl5 "$(InputPath)" # End Custom Build @@ -137,7 +137,7 @@ InputName=example echo PERL5_INCLUDE: %PERL5_INCLUDE% echo PERL5_LIB: %PERL5_LIB% echo on - ..\..\..\swig.exe -perl5 $(InputPath) + ..\..\..\swig.exe -perl5 "$(InputPath)" # End Custom Build diff --git a/Examples/perl5/value/Makefile b/Examples/perl5/value/Makefile index ce2bbb5b9..dfc01843e 100644 --- a/Examples/perl5/value/Makefile +++ b/Examples/perl5/value/Makefile @@ -1,18 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/value/example.i b/Examples/perl5/value/example.i index 98fd60ed5..39663c6b8 100644 --- a/Examples/perl5/value/example.i +++ b/Examples/perl5/value/example.i @@ -26,7 +26,7 @@ Vector *new_Vector(double x, double y, double z) { } void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/perl5/variables/Makefile b/Examples/perl5/variables/Makefile index ce2bbb5b9..dfc01843e 100644 --- a/Examples/perl5/variables/Makefile +++ b/Examples/perl5/variables/Makefile @@ -1,18 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/variables/example.c b/Examples/perl5/variables/example.c index aa4ffe9b3..85685fe72 100644 --- a/Examples/perl5/variables/example.c +++ b/Examples/perl5/variables/example.c @@ -51,10 +51,10 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); - printf("iptrvar = %p\n", iptrvar); + printf("cstrvar = %s\n", cstrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/perl5/xmlstring/Makefile b/Examples/perl5/xmlstring/Makefile index 36143fc3a..3b4ba0ea4 100644 --- a/Examples/perl5/xmlstring/Makefile +++ b/Examples/perl5/xmlstring/Makefile @@ -1,23 +1,23 @@ 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 LIBS = -lxerces-c -lxerces-depdom -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile perl5_clean - -check: all - - -run: - perl runme.pl +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/xmlstring/xmlstring.i b/Examples/perl5/xmlstring/xmlstring.i index 3ef53169d..861e1b84d 100644 --- a/Examples/perl5/xmlstring/xmlstring.i +++ b/Examples/perl5/xmlstring/xmlstring.i @@ -93,6 +93,17 @@ SWIG_FromXMLChPtrAndSize(const XMLCh* input, size_t size) } } +%fragment("SWIG_XMLStringNLen","header") { +size_t +SWIG_XMLStringNLen(const XMLCh* s, size_t maxlen) +{ + const XMLCh *p; + for (p = s; maxlen-- && *p; p++) + ; + return p - s; +} +} + %init { if (!SWIG_UTF8Transcoder()) { croak("ERROR: XML::Xerces: INIT: Could not create UTF-8 transcoder"); @@ -106,6 +117,7 @@ SWIG_FromXMLChPtrAndSize(const XMLCh* input, size_t size) SWIG_AsXMLChPtrAndSize, SWIG_FromXMLChPtrAndSize, XERCES_CPP_NAMESPACE::XMLString::stringLen, + SWIG_XMLStringNLen, "", INT_MIN, INT_MAX); diff --git a/Examples/php/callback/Makefile b/Examples/php/callback/Makefile index 42597202b..cbc75774c 100644 --- a/Examples/php/callback/Makefile +++ b/Examples/php/callback/Makefile @@ -1,22 +1,24 @@ 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 LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' php_cpp -static:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/callback/example.i b/Examples/php/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/php/callback/example.i +++ b/Examples/php/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/php/check.list b/Examples/php/check.list index 28c7a619f..fef3feba6 100644 --- a/Examples/php/check.list +++ b/Examples/php/check.list @@ -1,5 +1,5 @@ # see top-level Makefile.in -# (see also top-level configure.in kludge) +# (see also top-level configure.ac kludge) callback class constants diff --git a/Examples/php/class/Makefile b/Examples/php/class/Makefile index 1bc0beaab..02a8668ac 100644 --- a/Examples/php/class/Makefile +++ b/Examples/php/class/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/class/example.cxx b/Examples/php/class/example.cxx index f171f10e9..046304519 100644 --- a/Examples/php/class/example.cxx +++ b/Examples/php/class/example.cxx @@ -1,14 +1,7 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" -#include -#ifndef M_PI -# define M_PI 3.14159265358979323846 -#endif - -int Shape::get_nshapes() { - return nshapes; -} +#define M_PI 3.14159265358979323846 /* Move the shape to a new location */ void Shape::move(double dx, double dy) { @@ -18,22 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -void Circle::set_radius( double r ) { - radius = r; -} - -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/php/class/example.h b/Examples/php/class/example.h index 02eaf7232..0dff185b2 100644 --- a/Examples/php/class/example.h +++ b/Examples/php/class/example.h @@ -10,10 +10,9 @@ public: } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; - static int get_nshapes(); }; class Circle : public Shape { @@ -21,10 +20,8 @@ private: double radius; public: Circle(double r) : radius(r) { } - ~Circle() { } - void set_radius( double r ); - virtual double area(void); - virtual double perimeter(void); + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { @@ -32,7 +29,6 @@ private: double width; public: Square(double w) : width(w) { } - ~Square() { } - virtual double area(void); - virtual double perimeter(void); + virtual double area(); + virtual double perimeter(); }; diff --git a/Examples/php/class/example.i b/Examples/php/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/php/class/example.i +++ b/Examples/php/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/php/class/runme.php b/Examples/php/class/runme.php index 12b686052..99c253b46 100644 --- a/Examples/php/class/runme.php +++ b/Examples/php/class/runme.php @@ -14,7 +14,7 @@ print " Created square\n"; # ----- Access a static member ----- -print "\nA total of " . Shape::get_nshapes() . " shapes were created\n"; +print "\nA total of " . Shape::nshapes() . " shapes were created\n"; # ----- Member data access ----- @@ -54,7 +54,7 @@ $s = NULL; # the square. $o = NULL; -print Shape::get_nshapes() . " shapes remain\n"; +print Shape::nshapes() . " shapes remain\n"; print "Goodbye\n"; ?> diff --git a/Examples/php/constants/Makefile b/Examples/php/constants/Makefile index 23e2675d7..9dbd3842d 100644 --- a/Examples/php/constants/Makefile +++ b/Examples/php/constants/Makefile @@ -1,24 +1,26 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/cpointer/Makefile b/Examples/php/cpointer/Makefile index 0862ce5ec..05679f844 100644 --- a/Examples/php/cpointer/Makefile +++ b/Examples/php/cpointer/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/cpointer/example.c b/Examples/php/cpointer/example.c index 3326dec3e..04dd08df0 100644 --- a/Examples/php/cpointer/example.c +++ b/Examples/php/cpointer/example.c @@ -1,6 +1,6 @@ /* File : example.c */ -void add(double *x, double *y, double *result) { +void add(int *x, int *y, int *result) { *result = *x + *y; } diff --git a/Examples/php/cpointer/example.i b/Examples/php/cpointer/example.i index 52e6df190..c61d92858 100644 --- a/Examples/php/cpointer/example.i +++ b/Examples/php/cpointer/example.i @@ -1,6 +1,11 @@ /* 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 */ diff --git a/Examples/php/disown/Makefile b/Examples/php/disown/Makefile index 1bc0beaab..02a8668ac 100644 --- a/Examples/php/disown/Makefile +++ b/Examples/php/disown/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/disown/example.h b/Examples/php/disown/example.h index 985bc333d..e9f96743f 100644 --- a/Examples/php/disown/example.h +++ b/Examples/php/disown/example.h @@ -9,7 +9,7 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); virtual double area(void) = 0; @@ -22,8 +22,8 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - ~Circle() { }; + Circle(double r) : radius(r) { } + ~Circle() { } void set_radius( double r ); virtual double area(void); virtual double perimeter(void); @@ -33,7 +33,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } ~Square() { } virtual double area(void); virtual double perimeter(void); @@ -44,7 +44,7 @@ private: typedef std::vector::iterator iterator; std::vector shapes; public: - ShapeContainer() : shapes() {}; + ShapeContainer() : shapes() {} ~ShapeContainer(); void addShape( Shape *s ); }; diff --git a/Examples/php/enum/Makefile b/Examples/php/enum/Makefile index 252a72660..95ebf8fc1 100644 --- a/Examples/php/enum/Makefile +++ b/Examples/php/enum/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -noproxy -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/extend/Makefile b/Examples/php/extend/Makefile index 42597202b..cbc75774c 100644 --- a/Examples/php/extend/Makefile +++ b/Examples/php/extend/Makefile @@ -1,22 +1,24 @@ 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 LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_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)' php_cpp -static:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/extend/example.h b/Examples/php/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/php/extend/example.h +++ b/Examples/php/extend/example.h @@ -14,7 +14,7 @@ public: 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", this); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/php/funcptr/Makefile b/Examples/php/funcptr/Makefile index 0862ce5ec..05679f844 100644 --- a/Examples/php/funcptr/Makefile +++ b/Examples/php/funcptr/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/overloading/Makefile b/Examples/php/overloading/Makefile index 1bc0beaab..02a8668ac 100644 --- a/Examples/php/overloading/Makefile +++ b/Examples/php/overloading/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pointer/Makefile b/Examples/php/pointer/Makefile index 0862ce5ec..05679f844 100644 --- a/Examples/php/pointer/Makefile +++ b/Examples/php/pointer/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pointer/example.i b/Examples/php/pointer/example.i index c14b94189..1f0059406 100644 --- a/Examples/php/pointer/example.i +++ b/Examples/php/pointer/example.i @@ -1,6 +1,12 @@ /* 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 */ diff --git a/Examples/php/pointer/runme.php b/Examples/php/pointer/runme.php index 5e86de6a2..e79b23810 100644 --- a/Examples/php/pointer/runme.php +++ b/Examples/php/pointer/runme.php @@ -15,7 +15,7 @@ print " c = $c\n"; # Call the add() function wuth some pointers - add(&$a,&$b,&$c); + add($a,$b,$c); print " $a + $b = $c\n"; diff --git a/Examples/php/pragmas/Makefile b/Examples/php/pragmas/Makefile index 23e2675d7..9dbd3842d 100644 --- a/Examples/php/pragmas/Makefile +++ b/Examples/php/pragmas/Makefile @@ -1,24 +1,26 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SRCS = TARGET = example INTERFACE = example.i LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pragmas/runme.php b/Examples/php/pragmas/runme.php old mode 100755 new mode 100644 diff --git a/Examples/php/proxy/Makefile b/Examples/php/proxy/Makefile index 1bc0beaab..02a8668ac 100644 --- a/Examples/php/proxy/Makefile +++ b/Examples/php/proxy/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/proxy/example.h b/Examples/php/proxy/example.h index 361dff898..0683f07f3 100644 --- a/Examples/php/proxy/example.h +++ b/Examples/php/proxy/example.h @@ -9,7 +9,7 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); virtual double area(void) = 0; @@ -22,8 +22,8 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - ~Circle() { }; + Circle(double r) : radius(r) { } + ~Circle() { } void set_radius( double r ); virtual double area(void); virtual double perimeter(void); @@ -33,7 +33,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } ~Square() { } virtual double area(void); virtual double perimeter(void); diff --git a/Examples/php/reference/Makefile b/Examples/php/reference/Makefile index 1bc0beaab..02a8668ac 100644 --- a/Examples/php/reference/Makefile +++ b/Examples/php/reference/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/reference/example.cxx b/Examples/php/reference/example.cxx index 13e47eade..7ead7fbf6 100644 --- a/Examples/php/reference/example.cxx +++ b/Examples/php/reference/example.cxx @@ -19,23 +19,23 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::as_string() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + 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",this); + printf("VectorArray new: self=%p\n", (void *)this); } VectorArray::~VectorArray() { - printf("VectorArray delete: self=%p\n",this); + printf("VectorArray delete: self=%p\n", (void *)this); delete [] items; } Vector &VectorArray::operator[](int index) { - printf("VectorArray: read[%d] self=%p\n",index,this); + 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); @@ -44,6 +44,6 @@ Vector &VectorArray::operator[](int index) { } int VectorArray::size() { - printf("VectorArray: size %d self=%p\n",maxsize,this); + printf("VectorArray: size %d self=%p\n", maxsize, (void *)this); return maxsize; } diff --git a/Examples/php/reference/example.h b/Examples/php/reference/example.h index 1b88cbf5c..353b88835 100644 --- a/Examples/php/reference/example.h +++ b/Examples/php/reference/example.h @@ -4,8 +4,8 @@ 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) { }; + 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(); }; @@ -20,7 +20,3 @@ public: Vector &operator[](int); int size(); }; - - - - diff --git a/Examples/php/reference/example.i b/Examples/php/reference/example.i index d6122866b..df1459921 100644 --- a/Examples/php/reference/example.i +++ b/Examples/php/reference/example.i @@ -1,10 +1,6 @@ /* File : example.i */ -/* This example has nothing to do with references but the name is used by all - * the other languages so it's hard to rename to something more meaningful. - * - * Mostly it shows how to use %extend. - */ +/* This file has a few "typical" uses of C++ references. */ %module example @@ -33,11 +29,11 @@ public: VectorArray(int maxsize); ~VectorArray(); int size(); - - /* This wrapper provides an alternative to the [] operator */ + + /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { - printf("VectorArray extended get: %p %d\n",$self,index); + printf("VectorArray extended get: %p %d\n", (void *)$self, index); return (*$self)[index]; } void set(int index, Vector &a) { diff --git a/Examples/php/simple/Makefile b/Examples/php/simple/Makefile index 0862ce5ec..05679f844 100644 --- a/Examples/php/simple/Makefile +++ b/Examples/php/simple/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/simple/example.i b/Examples/php/simple/example.i index af4ff08a7..9d4e22aa9 100644 --- a/Examples/php/simple/example.i +++ b/Examples/php/simple/example.i @@ -1,10 +1,8 @@ /* File : example.i */ %module example -%{ - extern double Foo; -%} - +%inline %{ +extern int gcd(int x, int y); extern double Foo; void print_Foo(); -int gcd(int x, int y); +%} diff --git a/Examples/php/simple/runme.php b/Examples/php/simple/runme.php old mode 100755 new mode 100644 diff --git a/Examples/php/sync/Makefile b/Examples/php/sync/Makefile index 1bc0beaab..02a8668ac 100644 --- a/Examples/php/sync/Makefile +++ b/Examples/php/sync/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/sync/example.cxx b/Examples/php/sync/example.cxx index 31ed2021b..0942279b2 100644 --- a/Examples/php/sync/example.cxx +++ b/Examples/php/sync/example.cxx @@ -10,4 +10,4 @@ void Sync::printer(void) { 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/php/value/Makefile b/Examples/php/value/Makefile index 9e69d00a4..674e4368e 100644 --- a/Examples/php/value/Makefile +++ b/Examples/php/value/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -noproxy -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/value/example.i b/Examples/php/value/example.i index 386fa3b84..20a453468 100644 --- a/Examples/php/value/example.i +++ b/Examples/php/value/example.i @@ -11,7 +11,7 @@ %inline %{ void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/php/variables/Makefile b/Examples/php/variables/Makefile index 0862ce5ec..05679f844 100644 --- a/Examples/php/variables/Makefile +++ b/Examples/php/variables/Makefile @@ -1,24 +1,26 @@ 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 LIBS = SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static -clean:: - $(MAKE) -f $(TOP)/Makefile php_clean - rm -f $(TARGET).php - -check: all - $(MAKE) -f $(TOP)/Makefile php_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/variables/example.c b/Examples/php/variables/example.c index 3114c7c5f..d4c6d026d 100644 --- a/Examples/php/variables/example.c +++ b/Examples/php/variables/example.c @@ -51,10 +51,10 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); - printf("iptrvar = %p\n", iptrvar); + 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", ptptr, Point_print( ptptr ) ); + printf("ptptr = %p %s\n", (void *)ptptr, Point_print( ptptr ) ); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/pike/check.list b/Examples/pike/check.list index a8d348bf1..d6c8e2e7b 100644 --- a/Examples/pike/check.list +++ b/Examples/pike/check.list @@ -2,4 +2,6 @@ class constants enum +overload simple +template diff --git a/Examples/pike/class/Makefile b/Examples/pike/class/Makefile index 981ccef6f..e5319dbe2 100644 --- a/Examples/pike/class/Makefile +++ b/Examples/pike/class/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run + +build: + $(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 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: - $(MAKE) -f $(TOP)/Makefile pike_clean - -check: all + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/class/example.cxx b/Examples/pike/class/example.cxx index c7a3194a4..046304519 100644 --- a/Examples/pike/class/example.cxx +++ b/Examples/pike/class/example.cxx @@ -1,46 +1,28 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" - -#include - #define M_PI 3.14159265358979323846 -// Static member initializer -int Shape::nshapes = 0; - -// Constructor -Shape::Shape() { - nshapes++; -} - -// Move the shape to a new location +/* Move the shape to a new location */ void Shape::move(double dx, double dy) { x += dx; y += dy; } -// Destructor -Shape::~Shape() { - nshapes--; -} +int Shape::nshapes = 0; -// Circle area -double Circle::area() const { +double Circle::area() { return M_PI*radius*radius; } -// Circle perimeter -double Circle::perimeter() const { +double Circle::perimeter() { return 2*M_PI*radius; } -// Square area -double Square::area() const { +double Square::area() { return width*width; } -// Square perimeter -double Square::perimeter() const { +double Square::perimeter() { return 4*width; } diff --git a/Examples/pike/class/example.h b/Examples/pike/class/example.h index f74a4fefc..0dff185b2 100644 --- a/Examples/pike/class/example.h +++ b/Examples/pike/class/example.h @@ -2,12 +2,16 @@ class Shape { public: - Shape(); - virtual ~Shape(); - double x, y; + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; void move(double dx, double dy); - virtual double area() const = 0; - virtual double perimeter() const = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -15,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area() const; - virtual double perimeter() const; + 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() const; - virtual double perimeter() const; + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/pike/class/example.i b/Examples/pike/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/pike/class/example.i +++ b/Examples/pike/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/pike/class/runme.pike b/Examples/pike/class/runme.pike old mode 100755 new mode 100644 diff --git a/Examples/pike/constants/Makefile b/Examples/pike/constants/Makefile index 7fa493851..45da7d269 100644 --- a/Examples/pike/constants/Makefile +++ b/Examples/pike/constants/Makefile @@ -1,18 +1,22 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static -clean:: - $(MAKE) -f $(TOP)/Makefile pike_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/constants/runme.pike b/Examples/pike/constants/runme.pike old mode 100755 new mode 100644 diff --git a/Examples/pike/enum/Makefile b/Examples/pike/enum/Makefile index 0ae102156..e5319dbe2 100644 --- a/Examples/pike/enum/Makefile +++ b/Examples/pike/enum/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile pike_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/overload/Makefile b/Examples/pike/overload/Makefile index 60af005b1..5e5fe669b 100644 --- a/Examples/pike/overload/Makefile +++ b/Examples/pike/overload/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lstdc++ -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile pike_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/simple/Makefile b/Examples/pike/simple/Makefile index 544c97b5d..8b49b4ea5 100644 --- a/Examples/pike/simple/Makefile +++ b/Examples/pike/simple/Makefile @@ -1,18 +1,22 @@ 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 -all: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run + +build: + $(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 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: - $(MAKE) -f $(TOP)/Makefile pike_clean - -check: all + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/template/Makefile b/Examples/pike/template/Makefile index b3f012927..513dc3b4b 100644 --- a/Examples/pike/template/Makefile +++ b/Examples/pike/template/Makefile @@ -1,20 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run + +build: + $(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 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: - $(MAKE) -f $(TOP)/Makefile pike_clean - -check: all + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/template/runme.pike b/Examples/pike/template/runme.pike old mode 100755 new mode 100644 diff --git a/Examples/python/callback/Makefile b/Examples/python/callback/Makefile index a29276e58..71926f397 100644 --- a/Examples/python/callback/Makefile +++ b/Examples/python/callback/Makefile @@ -1,22 +1,24 @@ 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 LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' python_cpp -static:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/callback/example.i b/Examples/python/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/python/callback/example.i +++ b/Examples/python/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/python/callback/runme.py b/Examples/python/callback/runme.py index 026e9520b..345a3eb6e 100644 --- a/Examples/python/callback/runme.py +++ b/Examples/python/callback/runme.py @@ -2,14 +2,16 @@ # This file illustrates the cross language polymorphism using directors. -import example +import example class PyCallback(example.Callback): - def __init__(self): - example.Callback.__init__(self) - def run(self): - print "PyCallback.run()" + + def __init__(self): + example.Callback.__init__(self) + + def run(self): + print "PyCallback.run()" # Create an Caller instance @@ -25,7 +27,7 @@ callback = example.Callback() callback.thisown = 0 caller.setCallback(callback) caller.call() -caller.delCallback(); +caller.delCallback() print print "Adding and calling a Python callback" @@ -42,7 +44,7 @@ print print "Adding and calling another Python callback" print "------------------------------------------" -# Lets do the same but use the weak reference this time. +# Let's do the same but use the weak reference this time. callback = PyCallback().__disown__() caller.setCallback(callback) @@ -53,4 +55,3 @@ caller.delCallback() print print "python exit" - diff --git a/Examples/python/check.list b/Examples/python/check.list index 7cfe437f0..a43a5fca0 100644 --- a/Examples/python/check.list +++ b/Examples/python/check.list @@ -13,6 +13,7 @@ funcptr2 functor import import_template +import_packages java #libffi multimap @@ -23,7 +24,6 @@ simple smartptr std_vector std_map -swigrun template varargs variables diff --git a/Examples/python/class/Makefile b/Examples/python/class/Makefile index 74625b992..471e39073 100644 --- a/Examples/python/class/Makefile +++ b/Examples/python/class/Makefile @@ -1,21 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/class/example.cxx b/Examples/python/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/python/class/example.cxx +++ b/Examples/python/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/python/class/example.dsp b/Examples/python/class/example.dsp index fd7bf8c06..95ad8f173 100644 --- a/Examples/python/class/example.dsp +++ b/Examples/python/class/example.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -126,7 +126,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build @@ -141,7 +141,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/class/example.h b/Examples/python/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/python/class/example.h +++ b/Examples/python/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/python/class/example.i b/Examples/python/class/example.i index 0bf3285ca..21b86a346 100644 --- a/Examples/python/class/example.i +++ b/Examples/python/class/example.i @@ -11,4 +11,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/python/class/index.html b/Examples/python/class/index.html index 12c5eded1..2e1baa395 100644 --- a/Examples/python/class/index.html +++ b/Examples/python/class/index.html @@ -12,9 +12,7 @@

    Wrapping a simple C++ class

    -This example illustrates the most primitive form of C++ class wrapping performed -by SWIG. In this case, C++ classes are simply transformed into a collection of -C-style functions that provide access to class members. +This example illustrates wrapping a simple C++ class to give a Python class.

    The C++ Code

    @@ -32,8 +30,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +42,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +51,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -102,51 +100,34 @@ c = example.new_Circle(10.0)
  • -

  • To access member data, a pair of accessor functions are used. +
  • Member variables of the C++ class are wrapped as attributes of the Python class. For example:
    -example.Shape_x_set(c,15)    # Set member data
    -x = example.Shape_x_get(c)    # Get member data
    -
    -
    - -Note: when accessing member data, the name of the class in which -the member data was must be used. In this case, Shape_x_get() -and Shape_x_set() are used since 'x' was defined in Shape. - -

    -

  • To invoke a member function, you simply do this - -
    -
    -print "The area is ", example.Shape_area(c)
    +c.x = 15   # Set member data
    +x = c.x    # Get member data
     

    -

  • Type checking knows about the inheritance structure of C++. For example: +
  • Member function are invoked as you would expect:
    -example.Shape_area(c)       # Works (c is a Shape)
    -example.Circle_area(c)      # Works (c is a Circle)
    -example.Square_area(c)      # Fails (c is definitely not a Square)
    +print "The area is ", c.area()
     

    -

  • To invoke a destructor, simply do this +
  • To invoke a destructor, simply call del on the object:
    -example.delete_Shape(c)     # Deletes a shape
    +del c    # Deletes a shape
     
    -(Note: destructors are currently not inherited. This might change later). -

  • Static member variables are wrapped as C global variables. For example: @@ -162,52 +143,12 @@ example.cvar.Shapes_nshapes = 13 # Set a static data member

    General Comments

      -
    • This low-level interface is not the only way to handle C++ code. -Proxy classes provide a much higher-level interface. - -

      -

    • SWIG *does* know how to properly perform upcasting of objects in +
    • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class. -

      -

    • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

      -

        -
      • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
        -
        -void foo(int a);  
        -%name(foo2) void foo(double a, double b);
        -
        -
        - -

        -

      • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
        -
        -%inline %{
        -    Vector *vector_add(Vector *a, Vector *b) {
        -          ... whatever ...
        -    }
        -%}
        -
        -
        - -

        -

      • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). - -

        -

      • Dave's snide remark: Like a large bottle of strong Tequilla, it's better to -use C++ in moderation. +
      • C++ Namespaces - %nspace isn't yet supported for Python.
      diff --git a/Examples/python/class/runme.py b/Examples/python/class/runme.py index f1272ae81..34d21505c 100644 --- a/Examples/python/class/runme.py +++ b/Examples/python/class/runme.py @@ -3,7 +3,7 @@ # This file illustrates the proxy class C++ interface generated # by SWIG. -import example +import example # ----- Object creation ----- @@ -15,7 +15,7 @@ print " Created square", s # ----- Access a static member ----- -print "\nA total of", example.cvar.Shape_nshapes,"shapes were created" +print "\nA total of", example.cvar.Shape_nshapes, "shapes were created" # ----- Member data access ----- @@ -28,16 +28,18 @@ s.x = -10 s.y = 5 print "\nHere is their current position:" -print " Circle = (%f, %f)" % (c.x,c.y) -print " Square = (%f, %f)" % (s.x,s.y) +print " Circle = (%f, %f)" % (c.x, c.y) +print " Square = (%f, %f)" % (s.x, s.y) # ----- Call some methods ----- print "\nHere are some properties of the shapes:" -for o in [c,s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() +for o in [c, s]: + print " ", o + print " area = ", o.area() + print " perimeter = ", o.perimeter() +# prevent o from holding a reference to the last object looked at +o = None print "\nGuess I'll clean up now" @@ -45,7 +47,5 @@ print "\nGuess I'll clean up now" del c del s -s = 3 -print example.cvar.Shape_nshapes,"shapes remain" +print example.cvar.Shape_nshapes, "shapes remain" print "Goodbye" - diff --git a/Examples/python/constants/Makefile b/Examples/python/constants/Makefile index 1420b4e0b..a412cf299 100644 --- a/Examples/python/constants/Makefile +++ b/Examples/python/constants/Makefile @@ -1,20 +1,22 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/constants/runme.py b/Examples/python/constants/runme.py index 8d25b878b..415d1adc4 100644 --- a/Examples/python/constants/runme.py +++ b/Examples/python/constants/runme.py @@ -1,6 +1,6 @@ # file: runme.py -import example +import example print "ICONST =", example.ICONST, "(should be 42)" print "FCONST =", example.FCONST, "(should be 2.1828)" @@ -8,7 +8,7 @@ print "CCONST =", example.CCONST, "(should be 'x')" print "CCONST2 =", example.CCONST2, "(this should be on a new line)" print "SCONST =", example.SCONST, "(should be 'Hello World')" print "SCONST2 =", example.SCONST2, "(should be '\"Hello World\"')" -print "EXPR =", example.EXPR, "(should be 48.5484)" +print "EXPR =", example.EXPR, "(should be 48.5484)" print "iconst =", example.iconst, "(should be 37)" print "fconst =", example.fconst, "(should be 3.14)" @@ -21,7 +21,3 @@ try: print "FOO = ", example.FOO, "(Arg! This shouldn't print anything)" except AttributeError: print "FOO isn't defined (good)" - - - - diff --git a/Examples/python/contract/Makefile b/Examples/python/contract/Makefile index 77fe94b1a..54817c79d 100644 --- a/Examples/python/contract/Makefile +++ b/Examples/python/contract/Makefile @@ -1,20 +1,23 @@ 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 -SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python +SWIGOPT = -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - TARGET='mypython' INTERFACE='$(INTERFACE)' python_static +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python -check: all - $(MAKE) -f $(TOP)/Makefile python_run +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/contract/example.dsp b/Examples/python/contract/example.dsp index 32845e0e8..945b9a36d 100644 --- a/Examples/python/contract/example.dsp +++ b/Examples/python/contract/example.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -122,7 +122,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -python $(InputPath) + ..\..\..\swig.exe -python "$(InputPath)" # End Custom Build @@ -137,7 +137,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -python $(InputPath) + ..\..\..\swig.exe -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/contract/runme.py b/Examples/python/contract/runme.py index d484ae916..ce01e5a1d 100644 --- a/Examples/python/contract/runme.py +++ b/Examples/python/contract/runme.py @@ -1,13 +1,13 @@ # file: runme.py -import example +import example # Call our gcd() function x = 42 y = 105 -g = example.gcd(x,y) -print "The gcd of %d and %d is %d" % (x,y,g) +g = example.gcd(x, y) +print "The gcd of %d and %d is %d" % (x, y, g) # Manipulate the Foo global variable @@ -19,12 +19,3 @@ example.cvar.Foo = 3.1415926 # See if the change took effect print "Foo = ", example.cvar.Foo - - - - - - - - - diff --git a/Examples/python/docstrings/Makefile b/Examples/python/docstrings/Makefile index f25450cac..f1365a599 100644 --- a/Examples/python/docstrings/Makefile +++ b/Examples/python/docstrings/Makefile @@ -1,24 +1,26 @@ 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 LIBS = -lm SWIGOPT = -O -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/docstrings/runme.py b/Examples/python/docstrings/runme.py index b6c95e613..c25d291b6 100644 --- a/Examples/python/docstrings/runme.py +++ b/Examples/python/docstrings/runme.py @@ -1,6 +1,5 @@ # file: runme.py -import example +import example print "example.Foo.bar.__doc__ =", repr(example.Foo.bar.__doc__), "(Should be 'No comment')" - diff --git a/Examples/python/enum/Makefile b/Examples/python/enum/Makefile index 74625b992..471e39073 100644 --- a/Examples/python/enum/Makefile +++ b/Examples/python/enum/Makefile @@ -1,21 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/enum/runme.py b/Examples/python/enum/runme.py index 10c4a260d..def01b147 100644 --- a/Examples/python/enum/runme.py +++ b/Examples/python/enum/runme.py @@ -18,9 +18,9 @@ print " Foo_LUDICROUS =", example.Foo.LUDICROUS print "\nTesting use of enums with functions\n" example.enum_test(example.RED, example.Foo.IMPULSE) -example.enum_test(example.BLUE, example.Foo.WARP) +example.enum_test(example.BLUE, example.Foo.WARP) example.enum_test(example.GREEN, example.Foo.LUDICROUS) -example.enum_test(1234,5678) +example.enum_test(1234, 5678) print "\nTesting use of enum with class method" f = example.Foo() @@ -28,4 +28,3 @@ f = example.Foo() f.enum_test(example.Foo.IMPULSE) f.enum_test(example.Foo.WARP) f.enum_test(example.Foo.LUDICROUS) - diff --git a/Examples/python/exception/Makefile b/Examples/python/exception/Makefile index 7dbdde944..8420c8297 100644 --- a/Examples/python/exception/Makefile +++ b/Examples/python/exception/Makefile @@ -1,21 +1,23 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/exception/example.i b/Examples/python/exception/example.i index 08672c3a8..817c5221c 100644 --- a/Examples/python/exception/example.i +++ b/Examples/python/exception/example.i @@ -10,3 +10,12 @@ /* Let's just grab the original header file here */ %include "example.h" +%inline %{ +// The -builtin SWIG option results in SWIGPYTHON_BUILTIN being defined +#ifdef SWIGPYTHON_BUILTIN +bool is_python_builtin() { return true; } +#else +bool is_python_builtin() { return false; } +#endif +%} + diff --git a/Examples/python/exception/runme.py b/Examples/python/exception/runme.py index 718707861..7fae49030 100644 --- a/Examples/python/exception/runme.py +++ b/Examples/python/exception/runme.py @@ -6,31 +6,37 @@ import example t = example.Test() try: - t.unknown() -except RuntimeError,e: - print "incomplete type", e.args[0] + t.unknown() +except RuntimeError, e: + print "incomplete type", e.args[0] try: - t.simple() -except RuntimeError,e: - print e.args[0] + t.simple() +except RuntimeError, e: + print e.args[0] try: - t.message() -except RuntimeError,e: - print e.args[0] - -try: - t.hosed() -except example.Exc,e: - print e.code, e.msg - -for i in range(1,4): - try: - t.multi(i) - except RuntimeError,e: - print e.args[0] - except example.Exc,e: - print e.code, e.msg + t.message() +except RuntimeError, e: + print e.args[0] +if not example.is_python_builtin(): + try: + t.hosed() + except example.Exc, e: + print e.code, e.msg +else: + try: + t.hosed() + except BaseException, e: + # Throwing builtin classes as exceptions not supported (-builtin + # option) + print e +for i in range(1, 4): + try: + t.multi(i) + except RuntimeError, e: + print e.args[0] + except example.Exc, e: + print e.code, e.msg diff --git a/Examples/python/exceptproxy/Makefile b/Examples/python/exceptproxy/Makefile index ba5c79827..65af5ec82 100644 --- a/Examples/python/exceptproxy/Makefile +++ b/Examples/python/exceptproxy/Makefile @@ -1,22 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/exceptproxy/example.i b/Examples/python/exceptproxy/example.i index 4a1e0bae9..0a46afbb6 100644 --- a/Examples/python/exceptproxy/example.i +++ b/Examples/python/exceptproxy/example.i @@ -109,6 +109,12 @@ %template(doubleQueue) Queue; - - +%inline %{ +// The -builtin SWIG option results in SWIGPYTHON_BUILTIN being defined +#ifdef SWIGPYTHON_BUILTIN +bool is_python_builtin() { return true; } +#else +bool is_python_builtin() { return false; } +#endif +%} diff --git a/Examples/python/exceptproxy/runme.py b/Examples/python/exceptproxy/runme.py index a2ae55584..970d6201d 100644 --- a/Examples/python/exceptproxy/runme.py +++ b/Examples/python/exceptproxy/runme.py @@ -1,23 +1,29 @@ # file: runme.py import example +if example.is_python_builtin(): + print "Skipping example: -builtin option does not support %exceptionclass" + exit(0) + q = example.intQueue(10) print "Inserting items into intQueue" +print type(example.FullError) + try: - for i in range(0,100): - q.enqueue(i) -except example.FullError,e: - print "Maxsize is", e.maxsize + for i in range(0, 100): + q.enqueue(i) +except example.FullError, e: + print "Maxsize is", e.maxsize print "Removing items" try: - while 1: - q.dequeue() -except example.EmptyError,e: - pass + while 1: + q.dequeue() +except example.EmptyError, e: + pass q = example.doubleQueue(1000) @@ -25,21 +31,15 @@ q = example.doubleQueue(1000) print "Inserting items into doubleQueue" try: - for i in range(0,10000): - q.enqueue(i*1.5) -except example.FullError,e: - print "Maxsize is", e.maxsize + for i in range(0, 10000): + q.enqueue(i * 1.5) +except example.FullError, e: + print "Maxsize is", e.maxsize print "Removing items" try: - while 1: - q.dequeue() -except example.EmptyError,e: - pass - - - - - - + while 1: + q.dequeue() +except example.EmptyError, e: + pass diff --git a/Examples/python/extend/Makefile b/Examples/python/extend/Makefile index a29276e58..71926f397 100644 --- a/Examples/python/extend/Makefile +++ b/Examples/python/extend/Makefile @@ -1,22 +1,24 @@ 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 LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_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)' python_cpp -static:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/extend/example.h b/Examples/python/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/python/extend/example.h +++ b/Examples/python/extend/example.h @@ -14,7 +14,7 @@ public: 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", this); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/python/extend/runme.py b/Examples/python/extend/runme.py index 240b09894..2bb38fadc 100644 --- a/Examples/python/extend/runme.py +++ b/Examples/python/extend/runme.py @@ -2,16 +2,18 @@ # This file illustrates the cross language polymorphism using directors. -import example +import example # CEO class, which overrides Employee::getPosition(). class CEO(example.Manager): - def __init__(self, name): - example.Manager.__init__(self, name) - def getPosition(self): - return "CEO" + + def __init__(self, name): + example.Manager.__init__(self, name) + + def getPosition(self): + return "CEO" # Create an instance of our employee extension class, CEO. The calls to @@ -78,4 +80,3 @@ print "----------------------" # All done. print "python exit" - diff --git a/Examples/python/funcptr/Makefile b/Examples/python/funcptr/Makefile index 0f4a1e077..26bfd946e 100644 --- a/Examples/python/funcptr/Makefile +++ b/Examples/python/funcptr/Makefile @@ -1,20 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/funcptr/runme.py b/Examples/python/funcptr/runme.py index bce065057..bf0c6e1ac 100644 --- a/Examples/python/funcptr/runme.py +++ b/Examples/python/funcptr/runme.py @@ -1,6 +1,6 @@ # file: runme.py -import example +import example a = 37 b = 42 @@ -10,9 +10,9 @@ b = 42 print "Trying some C callback functions" print " a =", a print " b =", b -print " ADD(a,b) =", example.do_op(a,b,example.ADD) -print " SUB(a,b) =", example.do_op(a,b,example.SUB) -print " MUL(a,b) =", example.do_op(a,b,example.MUL) +print " ADD(a,b) =", example.do_op(a, b, example.ADD) +print " SUB(a,b) =", example.do_op(a, b, example.SUB) +print " MUL(a,b) =", example.do_op(a, b, example.MUL) print "Here is what the C callback function objects look like in Python" print " ADD =", example.ADD diff --git a/Examples/python/funcptr2/Makefile b/Examples/python/funcptr2/Makefile index 0f4a1e077..26bfd946e 100644 --- a/Examples/python/funcptr2/Makefile +++ b/Examples/python/funcptr2/Makefile @@ -1,20 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/funcptr2/runme.py b/Examples/python/funcptr2/runme.py index bd58fb620..a4405d9d9 100644 --- a/Examples/python/funcptr2/runme.py +++ b/Examples/python/funcptr2/runme.py @@ -1,6 +1,6 @@ # file: runme.py -import example +import example a = 37 b = 42 @@ -10,9 +10,9 @@ b = 42 print "Trying some C callback functions" print " a =", a print " b =", b -print " ADD(a,b) =", example.do_op(a,b,example.ADD) -print " SUB(a,b) =", example.do_op(a,b,example.SUB) -print " MUL(a,b) =", example.do_op(a,b,example.MUL) +print " ADD(a,b) =", example.do_op(a, b, example.ADD) +print " SUB(a,b) =", example.do_op(a, b, example.SUB) +print " MUL(a,b) =", example.do_op(a, b, example.MUL) print "Here is what the C callback function objects look like in Python" print " ADD =", example.ADD @@ -20,5 +20,5 @@ print " SUB =", example.SUB print " MUL =", example.MUL print "Call the functions directly..." -print " add(a,b) =", example.add(a,b) -print " sub(a,b) =", example.sub(a,b) +print " add(a,b) =", example.add(a, b) +print " sub(a,b) =", example.sub(a, b) diff --git a/Examples/python/functor/Makefile b/Examples/python/functor/Makefile index fe389757a..e5de5c5b7 100644 --- a/Examples/python/functor/Makefile +++ b/Examples/python/functor/Makefile @@ -1,22 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/functor/runme.py b/Examples/python/functor/runme.py index 8fc0f2ff2..7f6f2b649 100644 --- a/Examples/python/functor/runme.py +++ b/Examples/python/functor/runme.py @@ -8,10 +8,9 @@ b = example.doubleSum(100.0) # Use the objects. They should be callable just like a normal # python function. -for i in range(0,100): +for i in range(0, 100): a(i) # Note: function call b(math.sqrt(i)) # Note: function call print a.result() print b.result() - diff --git a/Examples/python/import/Makefile b/Examples/python/import/Makefile index 74d4f88cf..ad208b3e7 100644 --- a/Examples/python/import/Makefile +++ b/Examples/python/import/Makefile @@ -1,22 +1,27 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = -all:: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp +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='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:: - $(MAKE) -f $(TOP)/Makefile python_clean - @rm -f foo.py bar.py spam.py base.py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f foo.py bar.py spam.py base.py diff --git a/Examples/python/import/bar.dsp b/Examples/python/import/bar.dsp index 17b05cc39..3c0dbf2bd 100644 --- a/Examples/python/import/bar.dsp +++ b/Examples/python/import/bar.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -118,7 +118,7 @@ InputName=bar echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=bar echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/import/base.dsp b/Examples/python/import/base.dsp index 2bc9736d1..76b3f866b 100644 --- a/Examples/python/import/base.dsp +++ b/Examples/python/import/base.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -118,7 +118,7 @@ InputName=base echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=base echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/import/base.h b/Examples/python/import/base.h index 5a266f68c..c0b47956b 100644 --- a/Examples/python/import/base.h +++ b/Examples/python/import/base.h @@ -2,8 +2,8 @@ class Base { public: - Base() { }; - virtual ~Base() { }; + Base() { } + virtual ~Base() { } virtual void A() { printf("I'm Base::A\n"); } diff --git a/Examples/python/import/foo.dsp b/Examples/python/import/foo.dsp index 9a92c4b85..0a579e4cd 100644 --- a/Examples/python/import/foo.dsp +++ b/Examples/python/import/foo.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -118,7 +118,7 @@ InputName=foo echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=foo echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/import/runme.py b/Examples/python/import/runme.py index 6b800ecb8..0e83acad0 100644 --- a/Examples/python/import/runme.py +++ b/Examples/python/import/runme.py @@ -81,31 +81,27 @@ x = d.toBase() print " Spam -> Base -> Foo : ", y = foo.Foo_fromBase(x) if y: - print "bad swig" + print "bad swig" else: - print "good swig" + print "good swig" print " Spam -> Base -> Bar : ", y = bar.Bar_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" - + print "bad swig" + print " Spam -> Base -> Spam : ", y = spam.Spam_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" + print "bad swig" print " Foo -> Spam : ", y = spam.Spam_fromBase(b) if y: - print "bad swig" + print "bad swig" else: - print "good swig" - - - - + print "good swig" diff --git a/Examples/python/import/spam.dsp b/Examples/python/import/spam.dsp index 0a6595bfe..3adfcdb8b 100644 --- a/Examples/python/import/spam.dsp +++ b/Examples/python/import/spam.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -118,7 +118,7 @@ InputName=spam echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build @@ -133,7 +133,7 @@ InputName=spam echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -c++ -python $(InputPath) + ..\..\..\swig.exe -c++ -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile new file mode 100644 index 000000000..72b424a90 --- /dev/null +++ b/Examples/python/import_packages/Makefile @@ -0,0 +1,44 @@ +TOP = ../.. +SWIGOPT = +LIBS = + +import_packages_subdirs = \ + same_modnames1 \ + same_modnames2 \ + from_init1 \ + from_init2 \ + from_init3 \ + relativeimport1 \ + relativeimport2 \ + relativeimport3 + +check: build + if test "x$(SRCDIR)" != x; then \ + for file in `cd $(SRCDIR) && find . -type f -name __init__.py`; do \ + cp "${SRCDIR}$$file" "$$file" || exit 1; \ + done; \ + fi; \ + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) check); \ + done + +build: + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ + done + +static: + for s in $(import_packages_subdirs); do \ + (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 \ + rm -f "$$file" || exit 1; \ + done; \ + fi; \ + for s in $(import_packages_subdirs); do \ + (cd $$s && $(MAKE) clean); \ + done diff --git a/Examples/python/import_packages/README b/Examples/python/import_packages/README new file mode 100644 index 000000000..69fe3516e --- /dev/null +++ b/Examples/python/import_packages/README @@ -0,0 +1,2 @@ +These are actually regression tests for SF bug #1297 (GH issue #7). +See individual READMEs in subdirectories. diff --git a/Examples/python/import_packages/from_init1/Makefile b/Examples/python/import_packages/from_init1/Makefile new file mode 100644 index 000000000..90c92ab1c --- /dev/null +++ b/Examples/python/import_packages/from_init1/Makefile @@ -0,0 +1,22 @@ +TOP = ../../.. +LIBS = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/README b/Examples/python/import_packages/from_init1/README new file mode 100644 index 000000000..e7d7eca9e --- /dev/null +++ b/Examples/python/import_packages/from_init1/README @@ -0,0 +1,63 @@ +This example tests the %import directive and python import from __init__.py. + +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/foo.i - Pkg2_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg2_Foo + +and the package pyX.pkg2 has: + + pyX/pkg2/__init__.py - which imports something from "bar" module (we + import Pkg2_Bar class, but it is not the clue, + the clue is the 'from' keyword) + +For example with python2.x the py2/pkg2/__init__.py imports Pkg2_Bar class +as follows + + from bar import Pkg2_Bar # [1] + +Such cases doesn't work when fully qualified python module names are used by +swig (swig 2.0.10, e.g.) to generate python import directives (SF bug #1297). +The generated file "py2/pkg2/bar.py" has following lines: + + import py2.pkg2.foo # [2] + class Pkg2_Bar(py2.pkg2.foo.Pkg2_Foo): # [3] + +but it's not possible to import anything from py2.pkg2 subpackage, e.g. + + import py2.pkg2 + +fails with the following exception: + +Traceback (most recent call last): + File "runme.py", line 3, in + import py2.pkg2 + File "py2/pkg2/__init__.py", line 7, in + from .bar import Pkg2_Bar + File "py2/pkg2/bar.py", line 71, in + class Pkg2_Bar(py2.pkg2.foo.Pkg2_Foo): + AttributeError: 'module' object has no attribute 'pkg2' + + +It seems like during the import [1], the sub-package pkg2 is not yet fully +initialized, so py2.pkg2 is not known. The above exception is raised at +line [3]. The problem disappears, for example, if we force swig to use relative +package names. + +If everything works well, the package py2.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/from_init1/py2/Makefile b/Examples/python/import_packages/from_init1/py2/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py2/__init__.py b/Examples/python/import_packages/from_init1/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/Makefile b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile new file mode 100644 index 000000000..102a8938b --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile @@ -0,0 +1,25 @@ +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 + $(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_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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/__init__.py b/Examples/python/import_packages/from_init1/py2/pkg2/__init__.py new file mode 100644 index 000000000..0f9c90203 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/__init__.py @@ -0,0 +1 @@ +from bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp b/Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp new file mode 100644 index 000000000..b369161d3 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/foo.hpp" +struct Pkg2_Bar : Pkg2_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/bar.i b/Examples/python/import_packages/from_init1/py2/pkg2/bar.i new file mode 100644 index 000000000..0795a7751 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp b/Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp new file mode 100644 index 000000000..fed8239f6 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_FOO_HPP +#define PY2_PKG2_FOO_HPP +struct Pkg2_Foo {}; +#endif /* PY2_PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/foo.i b/Examples/python/import_packages/from_init1/py2/pkg2/foo.i new file mode 100644 index 000000000..37b2e1f82 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py2/pkg2/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2") foo +%{ +#include "../../py2/pkg2/foo.hpp" +%} +%include "../../py2/pkg2/foo.hpp" diff --git a/Examples/python/import_packages/from_init1/py3/Makefile b/Examples/python/import_packages/from_init1/py3/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py3/__init__.py b/Examples/python/import_packages/from_init1/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/Makefile b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile new file mode 100644 index 000000000..102a8938b --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile @@ -0,0 +1,25 @@ +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 + $(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_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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/__init__.py b/Examples/python/import_packages/from_init1/py3/pkg2/__init__.py new file mode 100644 index 000000000..2097aaf2e --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/__init__.py @@ -0,0 +1 @@ +from .bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp b/Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp new file mode 100644 index 000000000..d16463dff --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/foo.hpp" +struct Pkg2_Bar : Pkg2_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/bar.i b/Examples/python/import_packages/from_init1/py3/pkg2/bar.i new file mode 100644 index 000000000..8d8d627b9 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp b/Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp new file mode 100644 index 000000000..c2469dc86 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_FOO_HPP +#define PY3_PKG2_FOO_HPP +struct Pkg2_Foo {}; +#endif /* PY3_PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/foo.i b/Examples/python/import_packages/from_init1/py3/pkg2/foo.i new file mode 100644 index 000000000..76613b593 --- /dev/null +++ b/Examples/python/import_packages/from_init1/py3/pkg2/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2") foo +%{ +#include "../../py3/pkg2/foo.hpp" +%} +%include "../../py3/pkg2/foo.hpp" diff --git a/Examples/python/import_packages/from_init1/runme.py b/Examples/python/import_packages/from_init1/runme.py new file mode 100644 index 000000000..dda397487 --- /dev/null +++ b/Examples/python/import_packages/from_init1/runme.py @@ -0,0 +1,13 @@ +import sys +import os.path + +# Test import of modules content from within __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" + +if sys.version_info < (3, 0): + import py2.pkg2 + print " Finished importing py2.pkg2" +else: + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/from_init2/Makefile b/Examples/python/import_packages/from_init2/Makefile new file mode 100644 index 000000000..90c92ab1c --- /dev/null +++ b/Examples/python/import_packages/from_init2/Makefile @@ -0,0 +1,22 @@ +TOP = ../../.. +LIBS = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/README b/Examples/python/import_packages/from_init2/README new file mode 100644 index 000000000..a0eb41839 --- /dev/null +++ b/Examples/python/import_packages/from_init2/README @@ -0,0 +1,81 @@ +This example tests the %import directive and python import from __init__.py. + +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/foo.i - Pkg3_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg3_Foo + +and the package pyX.pkg2 has: + + pyX/pkg2/__init__.py - which imports something from "bar" module + +For example with python 2.x the py2/pkg2/__init__.py imports Pkg2_Bar class as +follows + + from bar import Pkg2_Bar # [1] + +Such cases doesn't work when fully qualified python module names are used by +swig to generate python import directives (SF bug #1297). The generated file +"py2/pkg2/bar.py" has following lines: + + import py2.pkg2.pkg3.foo # [2] + class Pkg2_Bar(py2.pkg2.pkg3.foo.Pkg3_Foo): # [3] + +and it's not possible to import anything from py2.pkg2 subpackage, e.g. + + import py2.pkg2 + +fails with the following exception: + +Traceback (most recent call last): + File "runme.py", line 3, in + import py2.pkg2 + File "py2/pkg2/__init__.py", line 4, in + from bar import Pkg2_Bar + File "py2/pkg2/bar.py", line 71, in + class Pkg2_Bar(py2.pkg2.pkg3.foo.Pkg3_Foo): +AttributeError: 'module' object has no attribute 'pkg2' + +It seems like during the import [1], the subpackage pkg2 is not yet fully +initialized, so pyX.pkg2 is not known. The above exception is raised at line [3]. +The problem disappears, for example, if we force swig to use relative package +names. + +The difference between this ('from_init2') case and the case +'from_init1' is that here it's not sufficient to import relative module +by just ignoring the package part of the fully qualified module name. IOW +it is not correct to force swig to put: + + import foo + class Pkg2_Bar(foo.Pkg3_Foo) + +into pyX/pkg2/bar.py (note, that this would work for 'from_init1' case). +The import directive shall be rather: + + import pkg3.foo + +for python 2.x and: + + from . import pkg3 + import pkg3.foo + +for python 3, and the class definition shall begin with: + + class Pkg2_Bar(pkg3.foo.Pkg3_Foo) + +If everything works well, the package pyX.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/from_init2/py2/Makefile b/Examples/python/import_packages/from_init2/py2/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/__init__.py b/Examples/python/import_packages/from_init2/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/__init__.py b/Examples/python/import_packages/from_init2/py2/pkg2/__init__.py new file mode 100644 index 000000000..0f9c90203 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/__init__.py @@ -0,0 +1 @@ +from bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp b/Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp new file mode 100644 index 000000000..8f09cd5fa --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/bar.i b/Examples/python/import_packages/from_init2/py2/pkg2/bar.i new file mode 100644 index 000000000..28a4c906e --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..7a0cb18ad --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/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/from_init2/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..b6c89a431 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_FOO_HPP +#define PY2_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY2_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i new file mode 100644 index 000000000..ba32483d2 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3") foo +%{ +#include "../../../py2/pkg2/pkg3/foo.hpp" +%} +%include "../../../py2/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/from_init2/py3/Makefile b/Examples/python/import_packages/from_init2/py3/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py3/__init__.py b/Examples/python/import_packages/from_init2/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/__init__.py b/Examples/python/import_packages/from_init2/py3/pkg2/__init__.py new file mode 100644 index 000000000..2097aaf2e --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/__init__.py @@ -0,0 +1 @@ +from .bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp b/Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp new file mode 100644 index 000000000..408d910d7 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/bar.i b/Examples/python/import_packages/from_init2/py3/pkg2/bar.i new file mode 100644 index 000000000..1468932ff --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..7a0cb18ad --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/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/from_init2/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..531721d36 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_FOO_HPP +#define PY3_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY3_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i new file mode 100644 index 000000000..c6ba529b7 --- /dev/null +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3") foo +%{ +#include "../../../py3/pkg2/pkg3/foo.hpp" +%} +%include "../../../py3/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/from_init2/runme.py b/Examples/python/import_packages/from_init2/runme.py new file mode 100644 index 000000000..dda397487 --- /dev/null +++ b/Examples/python/import_packages/from_init2/runme.py @@ -0,0 +1,13 @@ +import sys +import os.path + +# Test import of modules content from within __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" + +if sys.version_info < (3, 0): + import py2.pkg2 + print " Finished importing py2.pkg2" +else: + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/from_init3/Makefile b/Examples/python/import_packages/from_init3/Makefile new file mode 100644 index 000000000..90c92ab1c --- /dev/null +++ b/Examples/python/import_packages/from_init3/Makefile @@ -0,0 +1,22 @@ +TOP = ../../.. +LIBS = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/README b/Examples/python/import_packages/from_init3/README new file mode 100644 index 000000000..131d5894c --- /dev/null +++ b/Examples/python/import_packages/from_init3/README @@ -0,0 +1,67 @@ +This example tests the %import directive and python import from __init__.py. + +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/pkg4/foo.i - Pkg4_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg4_Foo + +and the package pyX.pkg2 has: + + pyX/pkg2/__init__.py - which imports something from "bar" module + +For example with python 2.x the py2/pkg2/__init__.py imports Pkg2_Bar class as +follows + + from bar import Pkg2_Bar # [1] + +Such cases doesn't work when fully qualified python module names are used by +swig to generate python import directives (SF bug 1297). The generated file +"py2/pkg2/bar.py" has following lines: + + import py2.pkg2.pkg3.pkg4.foo # [2] + class Pkg2_Bar(py2.pkg2.pkg3.pkg4.foo.P1_S1_S2_Foo): # [3] + +and it's not possible to import anything from py2.pkg2 subpackage, e.g. + + import py2.pkg2 + +fails with the following exception: + + Traceback (most recent call last): + File "runme.py", line 3, in + import py2.pkg2 + File "py2/pkg2/__init__.py", line 4, in + from bar import Pkg2_Bar + File "py2/pkg2/bar.py", line 71, in + class Pkg2_Bar(py2.pkg2.pkg3.pkg4.foo.Pkg4_Foo): + AttributeError: 'module' object has no attribute 'pkg2' + +It seems like during the import [1], the subpackage pkg2 is not yet fully +initialized, so py2.pkg2 can't be used. The above exception is raised at +line [3]. The problem disappears, for example, if we force swig to use relative +package names. + +The difference between this ('from_init3') case and the case +'from_init2' is that here we import base class from module +pyX.pkg2.pkg3.pkg4.foo, which is nested deeper than it was in +'from_init2'. This is just to ensure, that two (and more) levels of +subpackages get imported correctly by generated python code, i.e, not only +'pkg3.foo' is handled properly (one-level subpackage) but the code works also +for 'pkg3.pkg4.foo', and so on. + +If everything works well, the package pyX.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/from_init3/py2/Makefile b/Examples/python/import_packages/from_init3/py2/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/__init__.py b/Examples/python/import_packages/from_init3/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/__init__.py b/Examples/python/import_packages/from_init3/py2/pkg2/__init__.py new file mode 100644 index 000000000..0f9c90203 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/__init__.py @@ -0,0 +1 @@ +from bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp b/Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp new file mode 100644 index 000000000..20a00190a --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_HPP +#define PY2_PKG2_HPP +#include "../../py2/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY2_PKG2_HPP */ diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/bar.i b/Examples/python/import_packages/from_init3/py2/pkg2/bar.i new file mode 100644 index 000000000..0a932a2b9 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/pkg4/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..6f193fa33 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb 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 new file mode 100644 index 000000000..a870607e2 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/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/from_init3/py2/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..2df933c59 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_PKG4 +#define PY2_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY2_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..311d7161c --- /dev/null +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/from_init3/py3/Makefile b/Examples/python/import_packages/from_init3/py3/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/__init__.py b/Examples/python/import_packages/from_init3/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/__init__.py b/Examples/python/import_packages/from_init3/py3/pkg2/__init__.py new file mode 100644 index 000000000..2097aaf2e --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/__init__.py @@ -0,0 +1 @@ +from .bar import Pkg2_Bar diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp b/Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp new file mode 100644 index 000000000..16fdd362e --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_HPP +#define PY3_PKG2_HPP +#include "../../py3/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY3_PKG2_HPP */ diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/bar.i b/Examples/python/import_packages/from_init3/py3/pkg2/bar.i new file mode 100644 index 000000000..3abbb05d3 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/pkg4/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..6f193fa33 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb 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 new file mode 100644 index 000000000..a870607e2 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/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/from_init3/py3/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..e24654c28 --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_PKG4 +#define PY3_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY3_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..36c5f01ea --- /dev/null +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/from_init3/runme.py b/Examples/python/import_packages/from_init3/runme.py new file mode 100644 index 000000000..dda397487 --- /dev/null +++ b/Examples/python/import_packages/from_init3/runme.py @@ -0,0 +1,13 @@ +import sys +import os.path + +# Test import of modules content from within __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" + +if sys.version_info < (3, 0): + import py2.pkg2 + print " Finished importing py2.pkg2" +else: + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/relativeimport1/Makefile b/Examples/python/import_packages/relativeimport1/Makefile new file mode 100644 index 000000000..90c92ab1c --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/Makefile @@ -0,0 +1,22 @@ +TOP = ../../.. +LIBS = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/README b/Examples/python/import_packages/relativeimport1/README new file mode 100644 index 000000000..a99ef2426 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/README @@ -0,0 +1,22 @@ +This example tests the %import directive and -relativeimport swig option. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/foo.i - Pkg3_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg3_Foo + +The code is processed by swig with -relativeimport flag. The runtime test +imports pyX.pkg2.bar module. + +If everything works well, the module pyX.pkg2.bar shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/relativeimport1/py2/Makefile b/Examples/python/import_packages/relativeimport1/py2/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/__init__.py b/Examples/python/import_packages/relativeimport1/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/__init__.py b/Examples/python/import_packages/relativeimport1/py2/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp new file mode 100644 index 000000000..8f09cd5fa --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i new file mode 100644 index 000000000..28a4c906e --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..7a0cb18ad --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/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/relativeimport1/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..b6c89a431 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_FOO_HPP +#define PY2_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY2_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i new file mode 100644 index 000000000..ba32483d2 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3") foo +%{ +#include "../../../py2/pkg2/pkg3/foo.hpp" +%} +%include "../../../py2/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport1/py3/Makefile b/Examples/python/import_packages/relativeimport1/py3/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py3/__init__.py b/Examples/python/import_packages/relativeimport1/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/__init__.py b/Examples/python/import_packages/relativeimport1/py3/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp new file mode 100644 index 000000000..408d910d7 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i new file mode 100644 index 000000000..1468932ff --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..7a0cb18ad --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/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/relativeimport1/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..531721d36 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_FOO_HPP +#define PY3_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY3_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i new file mode 100644 index 000000000..c6ba529b7 --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3") foo +%{ +#include "../../../py3/pkg2/pkg3/foo.hpp" +%} +%include "../../../py3/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport1/runme.py b/Examples/python/import_packages/relativeimport1/runme.py new file mode 100644 index 000000000..997476b1d --- /dev/null +++ b/Examples/python/import_packages/relativeimport1/runme.py @@ -0,0 +1,13 @@ +import sys +import os.path + +# Test import of modules content from within __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) with -relativeimport" + +if sys.version_info < (3, 0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" +else: + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/relativeimport2/Makefile b/Examples/python/import_packages/relativeimport2/Makefile new file mode 100644 index 000000000..90c92ab1c --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/Makefile @@ -0,0 +1,22 @@ +TOP = ../../.. +LIBS = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/README b/Examples/python/import_packages/relativeimport2/README new file mode 100644 index 000000000..af2d2840b --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/README @@ -0,0 +1,22 @@ +This example tests the %import directive and -relativeimport option. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/pkg4/foo.i - Pkg4_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg4_Foo + +The difference between this ('relativeimport2') case and the case +'relativeimport1' is the "distance" between importer and importee. + +If everything works well, the package pyX.pkg2 shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/relativeimport2/py2/Makefile b/Examples/python/import_packages/relativeimport2/py2/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/__init__.py b/Examples/python/import_packages/relativeimport2/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/__init__.py b/Examples/python/import_packages/relativeimport2/py2/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp new file mode 100644 index 000000000..20a00190a --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_HPP +#define PY2_PKG2_HPP +#include "../../py2/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY2_PKG2_HPP */ diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i new file mode 100644 index 000000000..0a932a2b9 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import "../../py2/pkg2/pkg3/pkg4/foo.i" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..6f193fa33 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile new file mode 100644 index 000000000..a870607e2 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/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/relativeimport2/py2/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..2df933c59 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_PKG4 +#define PY2_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY2_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..311d7161c --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py2/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport2/py3/Makefile b/Examples/python/import_packages/relativeimport2/py3/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/__init__.py b/Examples/python/import_packages/relativeimport2/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/__init__.py b/Examples/python/import_packages/relativeimport2/py3/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp new file mode 100644 index 000000000..16fdd362e --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_HPP +#define PY3_PKG2_HPP +#include "../../py3/pkg2/pkg3/pkg4/foo.hpp" +struct Pkg2_Bar : Pkg4_Foo {}; +#endif /* PY3_PKG2_HPP */ diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i new file mode 100644 index 000000000..3abbb05d3 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import "../../py3/pkg2/pkg3/pkg4/foo.i" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..6f193fa33 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg4 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile new file mode 100644 index 000000000..a870607e2 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/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/relativeimport2/py3/pkg2/pkg3/pkg4/__init__.py b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp new file mode 100644 index 000000000..e24654c28 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_PKG4 +#define PY3_PKG2_PKG3_PKG4 +struct Pkg4_Foo {}; +#endif /* PY3_PKG2_PKG3_PKG4 */ diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i new file mode 100644 index 000000000..36c5f01ea --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3.pkg4") foo +%{ +#include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" +%} +%include "../../../../py3/pkg2/pkg3/pkg4/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport2/runme.py b/Examples/python/import_packages/relativeimport2/runme.py new file mode 100644 index 000000000..9789afc18 --- /dev/null +++ b/Examples/python/import_packages/relativeimport2/runme.py @@ -0,0 +1,13 @@ +import sys +import os.path + +# Test import of modules content from within __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" + +if sys.version_info < (3, 0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" +else: + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/relativeimport3/Makefile b/Examples/python/import_packages/relativeimport3/Makefile new file mode 100644 index 000000000..90c92ab1c --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/Makefile @@ -0,0 +1,22 @@ +TOP = ../../.. +LIBS = + +ifeq (,$(PY3)) + PKG1DIR = "py2" +else + PKG1DIR = "py3" +endif + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build + +static: + cd $(PKG1DIR) && $(MAKE) SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd py2 && $(MAKE) clean + cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport3/README b/Examples/python/import_packages/relativeimport3/README new file mode 100644 index 000000000..a99ef2426 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/README @@ -0,0 +1,22 @@ +This example tests the %import directive and -relativeimport swig option. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pyX/pkg2/pkg3/foo.i - Pkg3_Foo class + pyX/pkg2/bar.i - Pkg2_Bar class derived from Pkg3_Foo + +The code is processed by swig with -relativeimport flag. The runtime test +imports pyX.pkg2.bar module. + +If everything works well, the module pyX.pkg2.bar shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/relativeimport3/py2/Makefile b/Examples/python/import_packages/relativeimport3/py2/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport3/py2/__init__.py b/Examples/python/import_packages/relativeimport3/py2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/__init__.py b/Examples/python/import_packages/relativeimport3/py2/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport3/py2/pkg2/bar.hpp new file mode 100644 index 000000000..8f09cd5fa --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY2_PKG2_BAR_HPP +#define PY2_PKG2_BAR_HPP +#include "../../py2/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY2_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/bar.i b/Examples/python/import_packages/relativeimport3/py2/pkg2/bar.i new file mode 100644 index 000000000..6f4690b25 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py2.pkg2") bar +%{ +#include "../../py2/pkg2/bar.hpp" +%} +%import (module="foo", package="py2.pkg2.pkg3") "../../py2/pkg2/pkg3/foo.hpp" +%include "../../py2/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/Makefile new file mode 100644 index 000000000..7a0cb18ad --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/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/relativeimport3/py2/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..b6c89a431 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY2_PKG2_PKG3_FOO_HPP +#define PY2_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY2_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/foo.i b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/foo.i new file mode 100644 index 000000000..ba32483d2 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py2/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py2.pkg2.pkg3") foo +%{ +#include "../../../py2/pkg2/pkg3/foo.hpp" +%} +%include "../../../py2/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport3/py3/Makefile b/Examples/python/import_packages/relativeimport3/py3/Makefile new file mode 100644 index 000000000..629625144 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/Makefile @@ -0,0 +1,13 @@ +TOP = ../../../.. +SWIGOPT = +LIBS = + +build: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport3/py3/__init__.py b/Examples/python/import_packages/relativeimport3/py3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile new file mode 100644 index 000000000..c1f234e34 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/Makefile @@ -0,0 +1,21 @@ +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='bar' INTERFACE='bar.i' python_cpp + cd pkg3 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/__init__.py b/Examples/python/import_packages/relativeimport3/py3/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/bar.hpp b/Examples/python/import_packages/relativeimport3/py3/pkg2/bar.hpp new file mode 100644 index 000000000..408d910d7 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/bar.hpp @@ -0,0 +1,5 @@ +#ifndef PY3_PKG2_BAR_HPP +#define PY3_PKG2_BAR_HPP +#include "../../py3/pkg2/pkg3/foo.hpp" +struct Pkg2_Bar : Pkg3_Foo {}; +#endif /* PY3_PKG2_BAR_HPP */ diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/bar.i b/Examples/python/import_packages/relativeimport3/py3/pkg2/bar.i new file mode 100644 index 000000000..157c62e2c --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/bar.i @@ -0,0 +1,6 @@ +%module(package="py3.pkg2") bar +%{ +#include "../../py3/pkg2/bar.hpp" +%} +%import (module="foo", package="py3.pkg2.pkg3") "../../py3/pkg2/pkg3/foo.hpp" +%include "../../py3/pkg2/bar.hpp" diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/Makefile new file mode 100644 index 000000000..7a0cb18ad --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/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/relativeimport3/py3/pkg2/pkg3/__init__.py b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/foo.hpp b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/foo.hpp new file mode 100644 index 000000000..531721d36 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PY3_PKG2_PKG3_FOO_HPP +#define PY3_PKG2_PKG3_FOO_HPP +struct Pkg3_Foo {}; +#endif /* PY3_PKG2_PKG3_FOO_HPP */ diff --git a/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/foo.i b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/foo.i new file mode 100644 index 000000000..c6ba529b7 --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/py3/pkg2/pkg3/foo.i @@ -0,0 +1,5 @@ +%module(package="py3.pkg2.pkg3") foo +%{ +#include "../../../py3/pkg2/pkg3/foo.hpp" +%} +%include "../../../py3/pkg2/pkg3/foo.hpp" diff --git a/Examples/python/import_packages/relativeimport3/runme.py b/Examples/python/import_packages/relativeimport3/runme.py new file mode 100644 index 000000000..997476b1d --- /dev/null +++ b/Examples/python/import_packages/relativeimport3/runme.py @@ -0,0 +1,13 @@ +import sys +import os.path + +# Test import of modules content from within __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) with -relativeimport" + +if sys.version_info < (3, 0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" +else: + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/same_modnames1/Makefile b/Examples/python/import_packages/same_modnames1/Makefile new file mode 100644 index 000000000..57148c614 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/Makefile @@ -0,0 +1,18 @@ +TOP = ../../.. +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg1 && $(MAKE) clean + cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/same_modnames1/README b/Examples/python/import_packages/same_modnames1/README new file mode 100644 index 000000000..ee3f8d6f7 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/README @@ -0,0 +1,26 @@ +This example tests the %import directive and working with multiple modules. + +There are two modules having same name but belonging to different packages. +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pkg1/foo.i - Pkg1_Foo class. + pkg2/foo.i - Pkg2_Foo class (derived from Pkg1_Foo). + +The pkg2/foo.i module uses %import to refer to pkg1/foo.i. + +If everything works well, the module pkg2.foo shall load properly. + +Unix: +----- +- Run make +- Run the test as described above. diff --git a/Examples/python/import_packages/same_modnames1/pkg1/Makefile b/Examples/python/import_packages/same_modnames1/pkg1/Makefile new file mode 100644 index 000000000..3ca7fab03 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/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/same_modnames1/pkg1/__init__.py b/Examples/python/import_packages/same_modnames1/pkg1/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames1/pkg1/foo.hpp b/Examples/python/import_packages/same_modnames1/pkg1/foo.hpp new file mode 100644 index 000000000..b07c983b3 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg1/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PKG1_FOO_HPP +#define PKG1_FOO_HPP +struct Pkg1_Foo{}; +#endif /* PKG1_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames1/pkg1/foo.i b/Examples/python/import_packages/same_modnames1/pkg1/foo.i new file mode 100644 index 000000000..9939f420a --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg1/foo.i @@ -0,0 +1,5 @@ +%module(package="pkg1") foo +%{ +#include "../pkg1/foo.hpp" +%} +%include "../pkg1/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames1/pkg2/Makefile b/Examples/python/import_packages/same_modnames1/pkg2/Makefile new file mode 100644 index 000000000..3ca7fab03 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg2/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/same_modnames1/pkg2/__init__.py b/Examples/python/import_packages/same_modnames1/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames1/pkg2/foo.hpp b/Examples/python/import_packages/same_modnames1/pkg2/foo.hpp new file mode 100644 index 000000000..72563a9d0 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg2/foo.hpp @@ -0,0 +1,5 @@ +#ifndef PKG2_FOO_HPP +#define PKG2_FOO_HPP +#include "../pkg1/foo.hpp" +struct Pkg2_Foo : public Pkg1_Foo{}; +#endif /* PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames1/pkg2/foo.i b/Examples/python/import_packages/same_modnames1/pkg2/foo.i new file mode 100644 index 000000000..3a1ce0198 --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/pkg2/foo.i @@ -0,0 +1,6 @@ +%module(package="pkg2") foo +%{ +#include "../pkg2/foo.hpp" +%} +%import "../pkg1/foo.i" +%include "../pkg2/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py new file mode 100644 index 000000000..3c3c00c1a --- /dev/null +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -0,0 +1,19 @@ +import os.path + +# Test import of same modules from different packages +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" + +import pkg2.foo +print " Finished importing pkg2.foo" + +var2 = pkg2.foo.Pkg2_Foo() + +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 new file mode 100644 index 000000000..cf6db0c41 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/Makefile @@ -0,0 +1,18 @@ +TOP = ../../.. +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + cd pkg1/pkg2 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +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 + cd pkg1 && $(MAKE) clean + cd pkg1/pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/same_modnames2/README b/Examples/python/import_packages/same_modnames2/README new file mode 100644 index 000000000..9b0233f8b --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/README @@ -0,0 +1,26 @@ +This example tests the %import directive and working with multiple modules. + +There are two modules having same name but belonging to different packages. +This case is not correctly handled by swig 2. + +The issue was reported as Source Forge bug #1297 and later as GitHub issue #7. + +Use 'python runme.py' to run a test. + +Overview: +--------- + +The example defines 2 different extension modules--each wrapping a separate C++ +class. + + pkg1/foo.i - Pkg1_Foo class + pkg1/pkg2/foo.i - Pkg2_Foo class derived from Pkg1_Foo + +The pkg1/pkg2/foo module uses %import to refer to pkg1/foo. + +If everything works well, the module pkg1.pkg2.foo shall load properly. + +Unix: +----- +- Run make +- Run the test as described above diff --git a/Examples/python/import_packages/same_modnames2/pkg1/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/Makefile new file mode 100644 index 000000000..3ca7fab03 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/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/same_modnames2/pkg1/__init__.py b/Examples/python/import_packages/same_modnames2/pkg1/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames2/pkg1/foo.hpp b/Examples/python/import_packages/same_modnames2/pkg1/foo.hpp new file mode 100644 index 000000000..b07c983b3 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/foo.hpp @@ -0,0 +1,4 @@ +#ifndef PKG1_FOO_HPP +#define PKG1_FOO_HPP +struct Pkg1_Foo{}; +#endif /* PKG1_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames2/pkg1/foo.i b/Examples/python/import_packages/same_modnames2/pkg1/foo.i new file mode 100644 index 000000000..9939f420a --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/foo.i @@ -0,0 +1,5 @@ +%module(package="pkg1") foo +%{ +#include "../pkg1/foo.hpp" +%} +%include "../pkg1/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile new file mode 100644 index 000000000..921bb9951 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/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/same_modnames2/pkg1/pkg2/__init__.py b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp new file mode 100644 index 000000000..1b4a1d558 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.hpp @@ -0,0 +1,5 @@ +#ifndef PKG1_PKG2_FOO_HPP +#define PKG1_PKG2_FOO_HPP +#include "../../pkg1/foo.hpp" +struct Pkg2_Foo : public Pkg1_Foo{}; +#endif /* PKG1_PKG2_FOO_HPP */ diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i new file mode 100644 index 000000000..1741b3799 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/foo.i @@ -0,0 +1,6 @@ +%module(package="pkg1.pkg2") foo +%{ +#include "../../pkg1/pkg2/foo.hpp" +%} +%import "../../pkg1/foo.i" +%include "../../pkg1/pkg2/foo.hpp" diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py new file mode 100644 index 000000000..38daad0a3 --- /dev/null +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -0,0 +1,18 @@ +import os.path + +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" + +import pkg1.pkg2.foo +print " Finished importing pkg1.pkg2.foo" + +var2 = pkg1.pkg2.foo.Pkg2_Foo() + +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_template/Makefile b/Examples/python/import_template/Makefile index ee47e994d..ad208b3e7 100644 --- a/Examples/python/import_template/Makefile +++ b/Examples/python/import_template/Makefile @@ -1,22 +1,27 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = -all:: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp +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='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:: - $(MAKE) -f $(TOP)/Makefile python_clean - @rm -f foo.py bar.py spam.py base.py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f foo.py bar.py spam.py base.py diff --git a/Examples/python/import_template/base.h b/Examples/python/import_template/base.h index c755a6f9d..8faafb3d7 100644 --- a/Examples/python/import_template/base.h +++ b/Examples/python/import_template/base.h @@ -2,8 +2,8 @@ template class Base { public: - Base() { }; - virtual ~Base() { }; + Base() { } + virtual ~Base() { } virtual void A() { printf("I'm Base::A\n"); } diff --git a/Examples/python/import_template/runme.py b/Examples/python/import_template/runme.py index 0d5aded14..35f8924c1 100644 --- a/Examples/python/import_template/runme.py +++ b/Examples/python/import_template/runme.py @@ -81,31 +81,27 @@ x = d.toBase() print " Spam -> Base -> Foo : ", y = foo.intFoo_fromBase(x) if y: - print "bad swig" + print "bad swig" else: - print "good swig" + print "good swig" print " Spam -> Base -> Bar : ", y = bar.intBar_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" - + print "bad swig" + print " Spam -> Base -> Spam : ", y = spam.intSpam_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" + print "bad swig" print " Foo -> Spam : ", y = spam.intSpam_fromBase(b) if y: - print "bad swig" + print "bad swig" else: - print "good swig" - - - - + print "good swig" diff --git a/Examples/python/index.html b/Examples/python/index.html index 8443a85e1..3bbdd66e8 100644 --- a/Examples/python/index.html +++ b/Examples/python/index.html @@ -56,8 +56,7 @@ Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
  • The politically "correct" way to compile a Python extension is to follow the steps -described at www.python.org -or in the most excellent (and shamelessly plugged) Python Essential Reference: +described at www.python.org:

      @@ -89,21 +88,10 @@ to look at the distutils

      Compatibility

      -The examples have been extensively tested on the following platforms: - -
        -
      • Linux -
      • Solaris -
      - -All of the examples were last tested with the following configuration (9/1/2000): - -
        -
      • Sparc Solaris 2.8. -
      • gcc-2.95.2 -
      • Python 1.6b1. -
      +For Python 3, set the environment variable PY3=1. +This will ensure the 2to3 program is run prior to running any example. +

      Your mileage may vary. If you experience a problem, please let us know by contacting us on the mailing lists. diff --git a/Examples/python/java/Makefile b/Examples/python/java/Makefile index 326a4da94..7c75e6b91 100644 --- a/Examples/python/java/Makefile +++ b/Examples/python/java/Makefile @@ -1,25 +1,25 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -all:: Example.class - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj" \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: Example.class Example.h + $(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 - -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean rm -f $(TARGET).py rm -f *.class Example.h -check: all - - -Example.class: Example.java - gcj -fPIC -C -c -g Example.java - gcjh Example - +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java + gcjh Example.class diff --git a/Examples/python/java/example.i b/Examples/python/java/example.i index 13d5b5e70..80e08870f 100644 --- a/Examples/python/java/example.i +++ b/Examples/python/java/example.i @@ -7,3 +7,7 @@ %include Example.h + +%extend Example { + ~Example() {} +} diff --git a/Examples/python/java/runme.py b/Examples/python/java/runme.py index 0cec8a7cb..641ba27dd 100644 --- a/Examples/python/java/runme.py +++ b/Examples/python/java/runme.py @@ -6,11 +6,11 @@ JvAttachCurrentThread(None, None) e1 = Example(1) e2 = Example(2) -print e1.Add(1,2) -print e1.Add(1.0,2.0) -e3 = e1.Add(e1,e2) +print e1.Add(1, 2) +print e1.Add(1.0, 2.0) +e3 = e1.Add(e1, e2) print e3.mPublicInt -print e1.Add("1","2") +print e1.Add("1", "2") JvDetachCurrentThread() diff --git a/Examples/python/libffi/Makefile b/Examples/python/libffi/Makefile index fafb7de09..0875fdd96 100644 --- a/Examples/python/libffi/Makefile +++ b/Examples/python/libffi/Makefile @@ -1,20 +1,22 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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)' LIBS='-L/usr/local/lib -lffi' python -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/multimap/Makefile b/Examples/python/multimap/Makefile index 0f4a1e077..26bfd946e 100644 --- a/Examples/python/multimap/Makefile +++ b/Examples/python/multimap/Makefile @@ -1,20 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/multimap/example.dsp b/Examples/python/multimap/example.dsp index 32845e0e8..945b9a36d 100644 --- a/Examples/python/multimap/example.dsp +++ b/Examples/python/multimap/example.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -122,7 +122,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -python $(InputPath) + ..\..\..\swig.exe -python "$(InputPath)" # End Custom Build @@ -137,7 +137,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -python $(InputPath) + ..\..\..\swig.exe -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/multimap/example.i b/Examples/python/multimap/example.i index f1c4d9990..635f61c13 100644 --- a/Examples/python/multimap/example.i +++ b/Examples/python/multimap/example.i @@ -20,7 +20,7 @@ extern int gcd(int x, int y); if (!PyList_Check($input)) { SWIG_exception(SWIG_ValueError, "Expecting a list"); } - $1 = PyList_Size($input); + $1 = (int)PyList_Size($input); if ($1 == 0) { SWIG_exception(SWIG_ValueError, "List must contain at least 1 element"); } @@ -38,34 +38,57 @@ extern int gcd(int x, int y); } %#if PY_VERSION_HEX >= 0x03000000 { - int l; - $2[i] = PyUnicode_AsStringAndSize(s, &l); + PyObject *utf8str = PyUnicode_AsUTF8String(s); + const char *cstr = PyBytes_AsString(utf8str); + $2[i] = strdup(cstr); + Py_DECREF(utf8str); } %#else $2[i] = PyString_AsString(s); %#endif - } $2[i] = 0; } +%typemap(freearg) (int argc, char *argv[]) { +%#if PY_VERSION_HEX >= 0x03000000 + int i; + for (i = 0; i < $1; i++) { + free($2[i]); + } +%#endif +} + extern int gcdmain(int argc, char *argv[]); %typemap(in) (char *bytes, int len) { %#if PY_VERSION_HEX >= 0x03000000 + char *cstr; + Py_ssize_t len; + PyObject *utf8str; if (!PyUnicode_Check($input)) { PyErr_SetString(PyExc_ValueError,"Expected a string"); return NULL; } - $1 = PyUnicode_AsStringAndSize($input, &$2); + utf8str = PyUnicode_AsUTF8String($input); + PyBytes_AsStringAndSize(utf8str, &cstr, &len); + $1 = strncpy((char *)malloc(len+1), cstr, (size_t)len); + $2 = (int)len; + Py_DECREF(utf8str); %#else if (!PyString_Check($input)) { PyErr_SetString(PyExc_ValueError,"Expected a string"); return NULL; } $1 = PyString_AsString($input); - $2 = PyString_Size($input); + $2 = (int)PyString_Size($input); +%#endif +} + +%typemap(freearg) (char *bytes, int len) { +%#if PY_VERSION_HEX >= 0x03000000 + free($1); %#endif } @@ -75,17 +98,21 @@ extern int count(char *bytes, int len, char c); /* This example shows how to wrap a function that mutates a string */ /* Since str is modified, we make a copy of the Python object - so that we don't violate it's mutability */ + so that we don't violate its mutability */ %typemap(in) (char *str, int len) { %#if PY_VERSION_HEX >= 0x03000000 - $2 = PyUnicode_GetSize($input); - $1 = (char *) malloc($2+1); - memmove($1,PyUnicode_AsString($input),$2); + char *cstr; + Py_ssize_t len; + PyObject *utf8str = PyUnicode_AsUTF8String($input); + PyBytes_AsStringAndSize(utf8str, &cstr, &len); + $1 = strncpy((char *)malloc(len+1), cstr, (size_t)len); + $2 = (int)len; + Py_DECREF(utf8str); %#else - $2 = PyString_Size($input); - $1 = (char *) malloc($2+1); - memmove($1,PyString_AsString($input),$2); + $2 = (int)PyString_Size($input); + $1 = (char *) malloc($2+1); + memmove($1,PyString_AsString($input),$2); %#endif } diff --git a/Examples/python/multimap/runme.py b/Examples/python/multimap/runme.py index f996ab3ae..ad693b73a 100644 --- a/Examples/python/multimap/runme.py +++ b/Examples/python/multimap/runme.py @@ -1,16 +1,16 @@ # file: runme.py -import example +import example # Call our gcd() function x = 42 y = 105 -g = example.gcd(x,y) -print "The gcd of %d and %d is %d" % (x,y,g) +g = example.gcd(x, y) +print "The gcd of %d and %d is %d" % (x, y, g) # Call the gcdmain() function -example.gcdmain(["gcdmain","42","105"]) +example.gcdmain(["gcdmain", "42", "105"]) # Call the count function print example.count("Hello World", "l") @@ -18,10 +18,3 @@ print example.count("Hello World", "l") # Call the capitalize function print example.capitalize("hello world") - - - - - - - diff --git a/Examples/python/operator/Makefile b/Examples/python/operator/Makefile index fe389757a..e5de5c5b7 100644 --- a/Examples/python/operator/Makefile +++ b/Examples/python/operator/Makefile @@ -1,22 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/operator/runme.py b/Examples/python/operator/runme.py index 3687a38de..ac48f2676 100644 --- a/Examples/python/operator/runme.py +++ b/Examples/python/operator/runme.py @@ -1,21 +1,20 @@ # Operator overloading example import example -a = example.Complex(2,3) -b = example.Complex(-5,10) +a = example.Complex(2, 3) +b = example.Complex(-5, 10) -print "a =",a -print "b =",b +print "a =", a +print "b =", b c = a + b -print "c =",c -print "a*b =",a*b -print "a-c =",a-c +print "c =", c +print "a*b =", a * b +print "a-c =", a - c -e = example.ComplexCopy(a-c) -print "e =",e +e = example.ComplexCopy(a - c) +print "e =", e # Big expression -f = ((a+b)*(c+b*e)) + (-a) -print "f =",f - +f = ((a + b) * (c + b * e)) + (-a) +print "f =", f diff --git a/Examples/python/performance/Makefile b/Examples/python/performance/Makefile index c580801b4..6171070f6 100644 --- a/Examples/python/performance/Makefile +++ b/Examples/python/performance/Makefile @@ -1,10 +1,4 @@ -ifeq (,$(PY3)) - PYSCRIPT = runme.py -else - PYSCRIPT = runme3.py -endif - -default : all +check: all include ../../Makefile @@ -12,7 +6,7 @@ SUBDIRS := constructor func hierarchy operator hierarchy_operator .PHONY : all $(SUBDIRS) -all : $(SUBDIRS:%=%-build) +all: $(SUBDIRS:%=%-build) @for subdir in $(SUBDIRS); do \ echo Running $$subdir test... ; \ echo -------------------------------------------------------------------------------- ; \ @@ -21,17 +15,17 @@ all : $(SUBDIRS:%=%-build) cd ..; \ done -$(SUBDIRS) : +$(SUBDIRS): $(MAKE) -C $@ @echo Running $$subdir test... @echo -------------------------------------------------------------------------------- cd $@ && env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=$(srcdir):$$PYTHONPATH $(PYTHON) $(PYSCRIPT) -%-build : +%-build: $(MAKE) -C $* -%-clean : +%-clean: $(MAKE) -s -C $* clean -clean : $(SUBDIRS:%=%-clean) +clean: $(SUBDIRS:%=%-clean) rm -f *.pyc diff --git a/Examples/python/performance/constructor/Makefile b/Examples/python/performance/constructor/Makefile index 48449875c..cbc11543f 100644 --- a/Examples/python/performance/constructor/Makefile +++ b/Examples/python/performance/constructor/Makefile @@ -1,21 +1,26 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i -all : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean : - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/constructor/runme.py b/Examples/python/performance/constructor/runme.py index 23577a14d..1771fba7b 100644 --- a/Examples/python/performance/constructor/runme.py +++ b/Examples/python/performance/constructor/runme.py @@ -1,11 +1,10 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness -def proc (mod) : - for i in range(1000000) : + +def proc(mod): + for i in range(1000000): x = mod.MyClass() harness.run(proc) diff --git a/Examples/python/performance/func/Makefile b/Examples/python/performance/func/Makefile index 0df09d908..cbc11543f 100644 --- a/Examples/python/performance/func/Makefile +++ b/Examples/python/performance/func/Makefile @@ -1,23 +1,26 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i -default : all +build: + $(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 -all : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp - -static : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean : - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/func/runme.py b/Examples/python/performance/func/runme.py index fd2fb175b..760a8ab6d 100644 --- a/Examples/python/performance/func/runme.py +++ b/Examples/python/performance/func/runme.py @@ -1,12 +1,11 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.MyClass() - for i in range(10000000) : + for i in range(10000000): x.func() harness.run(proc) diff --git a/Examples/python/performance/harness.py b/Examples/python/performance/harness.py index 8e9b6041b..c3d38b4fb 100644 --- a/Examples/python/performance/harness.py +++ b/Examples/python/performance/harness.py @@ -1,13 +1,12 @@ -#!/usr/bin/env - import sys import time import imp from subprocess import * -def run (proc) : - try : +def run(proc): + + try: mod = imp.find_module(sys.argv[1]) mod = imp.load_module(sys.argv[1], *mod) @@ -16,15 +15,18 @@ def run (proc) : t2 = time.clock() print "%s took %f seconds" % (mod.__name__, t2 - t1) - except IndexError : - proc = Popen([sys.executable, 'runme.py', 'Simple_baseline'], stdout=PIPE) + except IndexError: + proc = Popen( + [sys.executable, 'runme.py', 'Simple_baseline'], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout - proc = Popen([sys.executable, 'runme.py', 'Simple_optimized'], stdout=PIPE) + proc = Popen( + [sys.executable, 'runme.py', 'Simple_optimized'], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout - proc = Popen([sys.executable, 'runme.py', 'Simple_builtin'], stdout=PIPE) + proc = Popen( + [sys.executable, 'runme.py', 'Simple_builtin'], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout diff --git a/Examples/python/performance/hierarchy/Makefile b/Examples/python/performance/hierarchy/Makefile index 0df09d908..cbc11543f 100644 --- a/Examples/python/performance/hierarchy/Makefile +++ b/Examples/python/performance/hierarchy/Makefile @@ -1,23 +1,26 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i -default : all +build: + $(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 -all : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp - -static : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean : - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/hierarchy/runme.py b/Examples/python/performance/hierarchy/runme.py index 8a57da05e..8255cdc86 100644 --- a/Examples/python/performance/hierarchy/runme.py +++ b/Examples/python/performance/hierarchy/runme.py @@ -1,12 +1,11 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.H() - for i in range(10000000) : + for i in range(10000000): x.func() harness.run(proc) diff --git a/Examples/python/performance/hierarchy_operator/Makefile b/Examples/python/performance/hierarchy_operator/Makefile index 0df09d908..cbc11543f 100644 --- a/Examples/python/performance/hierarchy_operator/Makefile +++ b/Examples/python/performance/hierarchy_operator/Makefile @@ -1,23 +1,26 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i -default : all +build: + $(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 -all : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp - -static : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean : - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/hierarchy_operator/runme.py b/Examples/python/performance/hierarchy_operator/runme.py index cf200362f..eabfae864 100644 --- a/Examples/python/performance/hierarchy_operator/runme.py +++ b/Examples/python/performance/hierarchy_operator/runme.py @@ -1,12 +1,11 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.H() - for i in range(10000000) : + for i in range(10000000): x += i harness.run(proc) diff --git a/Examples/python/performance/operator/Makefile b/Examples/python/performance/operator/Makefile index 0df09d908..cbc11543f 100644 --- a/Examples/python/performance/operator/Makefile +++ b/Examples/python/performance/operator/Makefile @@ -1,23 +1,26 @@ TOP = ../../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib CXXSRCS = TARGET = Simple INTERFACE = Simple.i -default : all +build: + $(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 -all : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ - TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ - TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ - TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp - -static : - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean : - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/operator/runme.py b/Examples/python/performance/operator/runme.py index 61a0e8edc..d75ae404c 100644 --- a/Examples/python/performance/operator/runme.py +++ b/Examples/python/performance/operator/runme.py @@ -1,12 +1,11 @@ -#!/usr/bin/env - import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.MyClass() - for i in range(10000000) : + for i in range(10000000): x = x + i harness.run(proc) diff --git a/Examples/python/pointer/Makefile b/Examples/python/pointer/Makefile index 0f4a1e077..26bfd946e 100644 --- a/Examples/python/pointer/Makefile +++ b/Examples/python/pointer/Makefile @@ -1,20 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/pointer/runme.py b/Examples/python/pointer/runme.py index e38a306c1..5b5f16bc2 100644 --- a/Examples/python/pointer/runme.py +++ b/Examples/python/pointer/runme.py @@ -1,25 +1,25 @@ # file: runme.py -import example; +import example # First create some objects using the pointer library. -print "Testing the pointer library"; -a = example.new_intp(); -b = example.new_intp(); -c = example.new_intp(); -example.intp_assign(a,37); -example.intp_assign(b,42); +print "Testing the pointer library" +a = example.new_intp() +b = example.new_intp() +c = example.new_intp() +example.intp_assign(a, 37) +example.intp_assign(b, 42) -print " a =",a -print " b =",b -print " c =",c +print " a =", a +print " b =", b +print " c =", c # Call the add() function with some pointers -example.add(a,b,c) +example.add(a, b, c) # Now get the result r = example.intp_value(c) -print " 37 + 42 =",r +print " 37 + 42 =", r # Clean up the pointers example.delete_intp(a) @@ -30,15 +30,12 @@ example.delete_intp(c) # This should be much easier. Now how it is no longer # necessary to manufacture pointers. -print "Trying the typemap library"; -r = example.sub(37,42) -print " 37 - 42 =",r +print "Trying the typemap library" +r = example.sub(37, 42) +print " 37 - 42 =", r # Now try the version with multiple return values -print "Testing multiple return values"; -q,r = example.divide(42,37) -print " 42/37 = %d remainder %d" % (q,r) - - - +print "Testing multiple return values" +q, r = example.divide(42, 37) +print " 42/37 = %d remainder %d" % (q, r) diff --git a/Examples/python/reference/Makefile b/Examples/python/reference/Makefile index 74625b992..471e39073 100644 --- a/Examples/python/reference/Makefile +++ b/Examples/python/reference/Makefile @@ -1,21 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/reference/example.cxx b/Examples/python/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/python/reference/example.cxx +++ b/Examples/python/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/python/reference/example.h b/Examples/python/reference/example.h index 4915adb1b..bcfcfb72f 100644 --- a/Examples/python/reference/example.h +++ b/Examples/python/reference/example.h @@ -4,8 +4,8 @@ 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) { }; + 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 *print(); }; @@ -20,7 +20,3 @@ public: Vector &operator[](int); int size(); }; - - - - diff --git a/Examples/python/reference/example.i b/Examples/python/reference/example.i index 8c95b3213..8af8397ec 100644 --- a/Examples/python/reference/example.i +++ b/Examples/python/reference/example.i @@ -31,7 +31,7 @@ public: VectorArray(int maxsize); ~VectorArray(); int size(); - + /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { @@ -42,7 +42,3 @@ public: } } }; - - - - diff --git a/Examples/python/reference/runme.py b/Examples/python/reference/runme.py index a1f53368e..0ff217b02 100644 --- a/Examples/python/reference/runme.py +++ b/Examples/python/reference/runme.py @@ -7,22 +7,22 @@ import example # ----- Object creation ----- print "Creating some objects:" -a = example.Vector(3,4,5) -b = example.Vector(10,11,12) +a = example.Vector(3, 4, 5) +b = example.Vector(10, 11, 12) -print " Created",a.cprint() -print " Created",b.cprint() +print " Created", a.cprint() +print " Created", b.cprint() # ----- Call an overloaded operator ----- # This calls the wrapper we placed around # -# operator+(const Vector &a, const Vector &) +# operator+(const Vector &a, const Vector &) # # It returns a new allocated object. print "Adding a+b" -c = example.addv(a,b) +c = example.addv(a, b) print " a+b =", c.cprint() # Note: Unless we free the result, a memory leak will occur @@ -33,25 +33,25 @@ del c # Note: Using the high-level interface here print "Creating an array of vectors" va = example.VectorArray(10) -print " va = ",va +print " va = ", va # ----- 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(0, a) +va.set(1, b) -va.set(2,example.addv(a,b)) +va.set(2, example.addv(a, b)) # Get some values from the array print "Getting some array values" -for i in range(0,5): +for i in range(0, 5): print " va(%d) = %s" % (i, va.get(i).cprint()) # Watch under resource meter to check on this print "Making sure we don't leak memory." -for i in xrange(0,1000000): +for i in xrange(0, 1000000): c = va.get(i % 10) # ----- Clean up ----- @@ -60,4 +60,3 @@ print "Cleaning up" del va del a del b - diff --git a/Examples/python/simple/Makefile b/Examples/python/simple/Makefile index 0f4a1e077..26bfd946e 100644 --- a/Examples/python/simple/Makefile +++ b/Examples/python/simple/Makefile @@ -1,20 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/simple/example.dsp b/Examples/python/simple/example.dsp index 32845e0e8..945b9a36d 100644 --- a/Examples/python/simple/example.dsp +++ b/Examples/python/simple/example.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x809 /d "_DEBUG" @@ -122,7 +122,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -python $(InputPath) + ..\..\..\swig.exe -python "$(InputPath)" # End Custom Build @@ -137,7 +137,7 @@ InputName=example echo PYTHON_INCLUDE: %PYTHON_INCLUDE% echo PYTHON_LIB: %PYTHON_LIB% echo on - ..\..\..\swig.exe -python $(InputPath) + ..\..\..\swig.exe -python "$(InputPath)" # End Custom Build diff --git a/Examples/python/simple/runme.py b/Examples/python/simple/runme.py index d484ae916..ce01e5a1d 100644 --- a/Examples/python/simple/runme.py +++ b/Examples/python/simple/runme.py @@ -1,13 +1,13 @@ # file: runme.py -import example +import example # Call our gcd() function x = 42 y = 105 -g = example.gcd(x,y) -print "The gcd of %d and %d is %d" % (x,y,g) +g = example.gcd(x, y) +print "The gcd of %d and %d is %d" % (x, y, g) # Manipulate the Foo global variable @@ -19,12 +19,3 @@ example.cvar.Foo = 3.1415926 # See if the change took effect print "Foo = ", example.cvar.Foo - - - - - - - - - diff --git a/Examples/python/smartptr/Makefile b/Examples/python/smartptr/Makefile index f73802a6b..34edcfc40 100644 --- a/Examples/python/smartptr/Makefile +++ b/Examples/python/smartptr/Makefile @@ -1,22 +1,24 @@ 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 LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/smartptr/example.h b/Examples/python/smartptr/example.h index c0f9b1d57..c18e7eaf4 100644 --- a/Examples/python/smartptr/example.h +++ b/Examples/python/smartptr/example.h @@ -7,7 +7,7 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); virtual double area() = 0; @@ -19,7 +19,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; diff --git a/Examples/python/smartptr/runme.py b/Examples/python/smartptr/runme.py index 5ea1fb947..5f8b73476 100644 --- a/Examples/python/smartptr/runme.py +++ b/Examples/python/smartptr/runme.py @@ -3,7 +3,7 @@ # This file illustrates the proxy class C++ interface generated # by SWIG. -import example +import example # ----- Object creation ----- @@ -17,7 +17,7 @@ print " Created square", s # ----- Access a static member ----- -print "\nA total of", example.cvar.Shape_nshapes,"shapes were created" +print "\nA total of", example.cvar.Shape_nshapes, "shapes were created" # ----- Member data access ----- @@ -30,16 +30,16 @@ s.x = -10 s.y = 5 print "\nHere is their current position:" -print " Circle = (%f, %f)" % (c.x,c.y) -print " Square = (%f, %f)" % (s.x,s.y) +print " Circle = (%f, %f)" % (c.x, c.y) +print " Square = (%f, %f)" % (s.x, s.y) # ----- Call some methods ----- print "\nHere are some properties of the shapes:" -for o in [c,s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() +for o in [c, s]: + print " ", o + print " area = ", o.area() + print " perimeter = ", o.perimeter() print "\nGuess I'll clean up now" @@ -50,6 +50,5 @@ del cc del ss s = 3 -print example.cvar.Shape_nshapes,"shapes remain" +print example.cvar.Shape_nshapes, "shapes remain" print "Goodbye" - diff --git a/Examples/python/std_map/Makefile b/Examples/python/std_map/Makefile index 5d13da764..65af5ec82 100644 --- a/Examples/python/std_map/Makefile +++ b/Examples/python/std_map/Makefile @@ -1,25 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -run: - python runme.py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/std_map/runme.py b/Examples/python/std_map/runme.py index b521c9c9c..26031f3f4 100644 --- a/Examples/python/std_map/runme.py +++ b/Examples/python/std_map/runme.py @@ -7,8 +7,6 @@ pmap["hi"] = 1 pmap["hello"] = 2 - - dmap = {} dmap["hello"] = 1.0 dmap["hi"] = 2.0 @@ -28,8 +26,8 @@ for i in dmap.iterkeys(): for i in dmap.itervalues(): print "val", i -for k,v in dmap.iteritems(): - print "item", k,v +for k, v in dmap.iteritems(): + print "item", k, v dmap = example.DoubleMap() dmap["hello"] = 1.0 @@ -41,8 +39,8 @@ for i in dmap.iterkeys(): for i in dmap.itervalues(): print "val", i -for k,v in dmap.iteritems(): - print "item", k,v +for k, v in dmap.iteritems(): + print "item", k, v print dmap.items() @@ -54,7 +52,6 @@ print hmap.keys() print hmap.values() - dmap = {} dmap["hello"] = 2 dmap["hi"] = 4 @@ -76,7 +73,7 @@ for i in dmap.itervalues(): for i in dmap.iteritems(): print "item", i -for k,v in dmap.iteritems(): - print "item", k,v +for k, v in dmap.iteritems(): + print "item", k, v print dmap diff --git a/Examples/python/std_vector/Makefile b/Examples/python/std_vector/Makefile index ba5c79827..65af5ec82 100644 --- a/Examples/python/std_vector/Makefile +++ b/Examples/python/std_vector/Makefile @@ -1,22 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/std_vector/runme.py b/Examples/python/std_vector/runme.py index d248ccbbb..d7d3c2ea4 100644 --- a/Examples/python/std_vector/runme.py +++ b/Examples/python/std_vector/runme.py @@ -4,13 +4,13 @@ import example # Call average with a Python list... -print example.average([1,2,3,4]) +print example.average([1, 2, 3, 4]) # ... or a wrapped std::vector v = example.IntVector(4) for i in range(len(v)): - v[i] = i+1 + v[i] = i + 1 print example.average(v) @@ -22,8 +22,8 @@ print example.half((1.0, 1.5, 2.0, 2.5, 3.0)) # ... or a wrapped std::vector v = example.DoubleVector() -for i in [1,2,3,4]: - v.append(i) +for i in [1, 2, 3, 4]: + v.append(i) print example.half(v) @@ -31,6 +31,5 @@ print example.half(v) example.halve_in_place(v) for i in range(len(v)): - print v[i], "; ", + print v[i], "; ", print - diff --git a/Examples/python/swigrun/Makefile b/Examples/python/swigrun/Makefile deleted file mode 100644 index 2142be5bb..000000000 --- a/Examples/python/swigrun/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx -TARGET = example -INTERFACE = example.i -LIBS = -lm -SWIGOPT = - -all:: - $(SWIG) -python -external-runtime - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp - -static:: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static - -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - rm -f swigpyrun.h - -check: all - - $(MAKE) -f $(TOP)/Makefile python_run diff --git a/Examples/python/swigrun/example.cxx b/Examples/python/swigrun/example.cxx deleted file mode 100644 index 25906a559..000000000 --- a/Examples/python/swigrun/example.cxx +++ /dev/null @@ -1,20 +0,0 @@ -/* File : example.cxx */ - -#include -#include "swigpyrun.h" -#include "example.h" - - -Manager* convert_to_Manager(PyObject *py_obj) -{ - Manager* c_ptr; - swig_type_info *ty = SWIG_TypeQuery("Manager *"); - printf("manager ty %p \n", ty); - if (SWIG_ConvertPtr(py_obj, (void **) &c_ptr, ty, 0) == -1) { - c_ptr = 0; - } else { - Py_XINCREF(py_obj); - } - return c_ptr; -} - diff --git a/Examples/python/swigrun/runme.py b/Examples/python/swigrun/runme.py deleted file mode 100644 index abcd96463..000000000 --- a/Examples/python/swigrun/runme.py +++ /dev/null @@ -1,28 +0,0 @@ -# file: runme.py - -# This file illustrates the cross language polymorphism using directors. - -import example - - -# CEO class, which overrides Employee::getPosition(). - -class CEO(example.Manager): - def __init__(self, name): - example.Manager.__init__(self, name) - def getPosition(self): - return "CEO" - def __del__(self): - print "CEO.__del__(),", self.getName() - # for proxy class extensions that are not "disowned" and - # define a __del__ method, it is very important to call the - # base class __del__. otherwise the c++ objects will never - # be deleted. - example.Manager.__del__(self) - - - - -e = CEO("Alice") -m = example.convert_to_Manager(e) -print m diff --git a/Examples/python/template/Makefile b/Examples/python/template/Makefile index ba5c79827..65af5ec82 100644 --- a/Examples/python/template/Makefile +++ b/Examples/python/template/Makefile @@ -1,22 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/template/runme.py b/Examples/python/template/runme.py index 05940bc67..e408e15f9 100644 --- a/Examples/python/template/runme.py +++ b/Examples/python/template/runme.py @@ -3,32 +3,30 @@ import example # Call some templated functions -print example.maxint(3,7) -print example.maxdouble(3.14,2.18) +print example.maxint(3, 7) +print example.maxdouble(3.14, 2.18) # Create some class iv = example.vecint(100) dv = example.vecdouble(1000) -for i in range(0,100): - iv.setitem(i,2*i) +for i in range(0, 100): + iv.setitem(i, 2 * i) -for i in range(0,1000): - dv.setitem(i, 1.0/(i+1)) +for i in range(0, 1000): + dv.setitem(i, 1.0 / (i + 1)) sum = 0 -for i in range(0,100): - sum = sum + iv.getitem(i) +for i in range(0, 100): + sum = sum + iv.getitem(i) print sum sum = 0.0 -for i in range(0,1000): - sum = sum + dv.getitem(i) +for i in range(0, 1000): + sum = sum + dv.getitem(i) print sum del iv del dv - - diff --git a/Examples/python/varargs/Makefile b/Examples/python/varargs/Makefile index 1420b4e0b..a412cf299 100644 --- a/Examples/python/varargs/Makefile +++ b/Examples/python/varargs/Makefile @@ -1,20 +1,22 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/varargs/example.i b/Examples/python/varargs/example.i index 6cb88f5f4..a581bca5d 100644 --- a/Examples/python/varargs/example.i +++ b/Examples/python/varargs/example.i @@ -32,9 +32,6 @@ int printf(const char *fmt, ...); } #endif -/* Typemap just to make the example work */ -%typemap(in) FILE * "$1 = PyFile_AsFile($input);"; - int fprintf(FILE *, const char *fmt, ...); /* Here is somewhat different example. A variable length argument @@ -48,6 +45,13 @@ int fprintf(FILE *, const char *fmt, ...); %varargs(20, char *x = NULL) printv; %inline %{ + +/* In Python 2 we could use PyFile_AsFile for converting Python sys.stdout to C's stdout. + This API disappeared in Python 3, so instead we use a helper function to get stdout */ +FILE * stdout_stream(void) { + return stdout; +} + void printv(char *s, ...) { va_list ap; char *x; diff --git a/Examples/python/varargs/runme.py b/Examples/python/varargs/runme.py index a01cb6769..48e3134f3 100644 --- a/Examples/python/varargs/runme.py +++ b/Examples/python/varargs/runme.py @@ -1,34 +1,27 @@ # file: runme.py import sys -import example +import example # Call printf example.printf("Hello World. I'm printf\n") # Note: We call printf, but use *python* string formatting -for i in range(0,10): +for i in range(0, 10): example.printf("i is %d\n" % i) # This will probably be garbled because %d is interpreted by C example.printf("The value is %d\n") +stdout = example.stdout_stream() # Call fprintf -example.fprintf(sys.stdout,"Hello World. I'm fprintf\n") -for i in range(0,10): - example.fprintf(sys.stdout,"i is %d\n" % i) +example.fprintf(stdout, "Hello World. I'm fprintf\n") +for i in range(0, 10): + example.fprintf(stdout, "i is %d\n" % i) # This won't be garbled since %d is not interpreted -example.fprintf(sys.stdout,"The value is %d\n") +example.fprintf(stdout, "The value is %d\n") # This function calls our NULL-terminated function -example.printv("Hello","World","this","is","a","test.") - - - - - - - - +example.printv("Hello", "World", "this", "is", "a", "test.") diff --git a/Examples/python/variables/Makefile b/Examples/python/variables/Makefile index 0f4a1e077..26bfd946e 100644 --- a/Examples/python/variables/Makefile +++ b/Examples/python/variables/Makefile @@ -1,20 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +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 -static:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean - rm -f $(TARGET).py - -check: all - $(MAKE) -f $(TOP)/Makefile python_run +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/variables/example.c b/Examples/python/variables/example.c index aa4ffe9b3..85685fe72 100644 --- a/Examples/python/variables/example.c +++ b/Examples/python/variables/example.c @@ -51,10 +51,10 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); - printf("iptrvar = %p\n", iptrvar); + printf("cstrvar = %s\n", cstrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/python/variables/runme.py b/Examples/python/variables/runme.py index b635b9859..3388a0eba 100644 --- a/Examples/python/variables/runme.py +++ b/Examples/python/variables/runme.py @@ -4,21 +4,21 @@ import example # Try to set the values of some global variables -example.cvar.ivar = 42 -example.cvar.svar = -31000 -example.cvar.lvar = 65537 -example.cvar.uivar = 123456 -example.cvar.usvar = 61000 -example.cvar.ulvar = 654321 -example.cvar.scvar = -13 -example.cvar.ucvar = 251 -example.cvar.cvar = "S" -example.cvar.fvar = 3.14159 -example.cvar.dvar = 2.1828 -example.cvar.strvar = "Hello World" -example.cvar.iptrvar= example.new_int(37) -example.cvar.ptptr = example.new_Point(37,42) -example.cvar.name = "Bill" +example.cvar.ivar = 42 +example.cvar.svar = -31000 +example.cvar.lvar = 65537 +example.cvar.uivar = 123456 +example.cvar.usvar = 61000 +example.cvar.ulvar = 654321 +example.cvar.scvar = -13 +example.cvar.ucvar = 251 +example.cvar.cvar = "S" +example.cvar.fvar = 3.14159 +example.cvar.dvar = 2.1828 +example.cvar.strvar = "Hello World" +example.cvar.iptrvar = example.new_int(37) +example.cvar.ptptr = example.new_Point(37, 42) +example.cvar.name = "Bill" # Now print out the values of the variables @@ -46,16 +46,16 @@ print "\nVariables (values printed from C)" example.print_vars() -print "\nNow I'm going to try and modify some read only variables"; +print "\nNow I'm going to try and modify some read only variables" -print " Tring to set 'path'"; +print " Tring to set 'path'" try: example.cvar.path = "Whoa!" print "Hey, what's going on?!?! This shouldn't work" except: print "Good." -print " Trying to set 'status'"; +print " Trying to set 'status'" try: example.cvar.status = 0 print "Hey, what's going on?!?! This shouldn't work" @@ -70,6 +70,3 @@ example.cvar.pt = example.cvar.ptptr print "The new value is" example.pt_print() print "You should see the value", example.Point_print(example.cvar.ptptr) - - - diff --git a/Examples/r/class/Makefile b/Examples/r/class/Makefile index 0cd8ed3d3..6b4b306f3 100644 --- a/Examples/r/class/Makefile +++ b/Examples/r/class/Makefile @@ -1,15 +1,17 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' r_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r_cpp -clean:: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' r_clean - -check: all - R CMD BATCH runme.R +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' r_clean diff --git a/Examples/r/class/example.cxx b/Examples/r/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/r/class/example.cxx +++ b/Examples/r/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/r/class/example.dsp b/Examples/r/class/example.dsp index b831989cc..aea02b2fa 100644 --- a/Examples/r/class/example.dsp +++ b/Examples/r/class/example.dsp @@ -126,7 +126,7 @@ InputName=example echo R_INCLUDE: %R_INCLUDE% echo R_LIB: %R_LIB% echo on - ..\..\..\swig.exe -c++ -r -o example_wrap.cpp $(InputPath) + ..\..\..\swig.exe -c++ -r -o example_wrap.cpp "$(InputPath)" # End Custom Build @@ -141,7 +141,7 @@ InputName=example echo R_INCLUDE: %R_INCLUDE% echo R_LIB: %R_LIB% echo on - ..\..\..\swig.exe -c++ -r -o example_wrap.cpp $(InputPath) + ..\..\..\swig.exe -c++ -r -o example_wrap.cpp "$(InputPath)" # End Custom Build diff --git a/Examples/r/class/example.h b/Examples/r/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/r/class/example.h +++ b/Examples/r/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/r/class/example.i b/Examples/r/class/example.i index 4654d269f..fbdf7249f 100644 --- a/Examples/r/class/example.i +++ b/Examples/r/class/example.i @@ -1,9 +1,9 @@ /* File : example.i */ %module example -%inline %{ +%{ #include "example.h" %} + +/* Let's just grab the original header file here */ %include "example.h" - - diff --git a/Examples/r/simple/Makefile b/Examples/r/simple/Makefile index 5ef29565a..add881898 100644 --- a/Examples/r/simple/Makefile +++ b/Examples/r/simple/Makefile @@ -1,15 +1,17 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' r_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r -clean:: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' r_clean - -check: all - R CMD BATCH runme.R +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' r_clean diff --git a/Examples/r/simple/example.dsp b/Examples/r/simple/example.dsp index 356815d19..105392bbd 100644 --- a/Examples/r/simple/example.dsp +++ b/Examples/r/simple/example.dsp @@ -122,7 +122,7 @@ InputName=example echo R_INCLUDE: %R_INCLUDE% echo R_LIB: %R_LIB% echo on - ..\..\..\swig.exe -r $(InputPath) + ..\..\..\swig.exe -r "$(InputPath)" # End Custom Build @@ -137,7 +137,7 @@ InputName=example echo R_INCLUDE: %R_INCLUDE% echo R_LIB: %R_LIB% echo on - ..\..\..\swig.exe -r $(InputPath) + ..\..\..\swig.exe -r "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/check.list b/Examples/ruby/check.list index 131dcbb33..2e581fb82 100644 --- a/Examples/ruby/check.list +++ b/Examples/ruby/check.list @@ -2,7 +2,7 @@ class constants enum -free_function +#free_function funcptr funcptr2 functor diff --git a/Examples/ruby/class/Makefile b/Examples/ruby/class/Makefile index 56c84c651..0d469c655 100644 --- a/Examples/ruby/class/Makefile +++ b/Examples/ruby/class/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/class/example.cxx b/Examples/ruby/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/ruby/class/example.cxx +++ b/Examples/ruby/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/ruby/class/example.dsp b/Examples/ruby/class/example.dsp index 2adab787a..8c1786c10 100644 --- a/Examples/ruby/class/example.dsp +++ b/Examples/ruby/class/example.dsp @@ -128,7 +128,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -143,7 +143,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/class/example.h b/Examples/ruby/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/ruby/class/example.h +++ b/Examples/ruby/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/ruby/class/example.i b/Examples/ruby/class/example.i index 75700b305..fbdf7249f 100644 --- a/Examples/ruby/class/example.i +++ b/Examples/ruby/class/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Examples/ruby/class/index.html b/Examples/ruby/class/index.html index 67eeac9ad..927c00190 100644 --- a/Examples/ruby/class/index.html +++ b/Examples/ruby/class/index.html @@ -12,9 +12,7 @@

      Wrapping a simple C++ class

      -This example illustrates C++ class wrapping performed by SWIG. -C++ classes are simply transformed into Ruby classes that provide methods to -access class members. +This example illustrates wrapping a simple C++ class to give a Ruby class.

      The C++ Code

      @@ -32,8 +30,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +42,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +51,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -122,10 +120,8 @@ print "The area is ", c.area, "\n"

      -

    1. When a instance of Ruby level wrapper class is garbage collected by +
    2. When a instance of Ruby level wrapper class is garbage collected by the Ruby interpreter, the corresponding C++ destructor is automatically invoked. -(Note: destructors are currently not inherited. This might change later. -Until then, use -make_default).

    3. Static member variables are wrapped as Ruby class accessor methods. @@ -144,53 +140,14 @@ Shapes.nshapes = 13 # Set a static data member
      • Ruby module of SWIG differs from other language modules in wrapping C++ -interfaces. They provides lower-level interfaces and optional higher-level +interfaces. They provide lower-level interfaces and optional higher-level interfaces know as proxy classes. Ruby module needs no such redundancy due to Ruby's sophisticated extension API. -

        -

      • SWIG *does* know how to properly perform upcasting of objects in +
      • SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy except for multiple inheritance. -

        -

      • A wide variety of C++ features are not currently supported by SWIG. Here is the -short and incomplete list: - -

        -

          -
        • Overloaded methods and functions. SWIG wrappers don't know how to resolve name -conflicts so you must give an alternative name to any overloaded method name using the -%name directive like this: - -
          -
          -void foo(int a);  
          -%name(foo2) void foo(double a, double b);
          -
          -
          - -

          -

        • Overloaded operators. Not supported at all. The only workaround for this is -to write a helper function. For example: - -
          -
          -%inline %{
          -    Vector *vector_add(Vector *a, Vector *b) {
          -          ... whatever ...
          -    }
          -%}
          -
          -
          - -

          -

        • Namespaces. Not supported at all. Won't be supported until SWIG2.0 (if at all). - -
        -

        - -

      • Dave's snide remark: Like a large bottle of strong Tequilla, it's better to -use C++ in moderation. +
      • C++ Namespaces - %nspace isn't yet supported for Ruby.
      diff --git a/Examples/ruby/class/runme.rb b/Examples/ruby/class/runme.rb index de73bcd46..971e149d5 100644 --- a/Examples/ruby/class/runme.rb +++ b/Examples/ruby/class/runme.rb @@ -45,5 +45,9 @@ end # Notice how the Shape#area() and Shape#perimeter() functions really # invoke the appropriate virtual method on each object. +# Remove references to the object and force a garbage collection run. +c = s = o = nil +GC.start() + print "\n", Example::Shape.nshapes," shapes remain\n" print "Goodbye\n" diff --git a/Examples/ruby/constants/Makefile b/Examples/ruby/constants/Makefile index 7dce3bee4..24698f2b4 100644 --- a/Examples/ruby/constants/Makefile +++ b/Examples/ruby/constants/Makefile @@ -1,18 +1,22 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/constants/runme.rb b/Examples/ruby/constants/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/enum/Makefile b/Examples/ruby/enum/Makefile index 56c84c651..0d469c655 100644 --- a/Examples/ruby/enum/Makefile +++ b/Examples/ruby/enum/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/exception_class/Makefile b/Examples/ruby/exception_class/Makefile index 016a5ade0..2d4518e11 100644 --- a/Examples/ruby/exception_class/Makefile +++ b/Examples/ruby/exception_class/Makefile @@ -1,19 +1,23 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/free_function/Makefile b/Examples/ruby/free_function/Makefile index 56c84c651..0d469c655 100644 --- a/Examples/ruby/free_function/Makefile +++ b/Examples/ruby/free_function/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/free_function/example.dsp b/Examples/ruby/free_function/example.dsp index 2adab787a..8c1786c10 100644 --- a/Examples/ruby/free_function/example.dsp +++ b/Examples/ruby/free_function/example.dsp @@ -128,7 +128,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -143,7 +143,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/free_function/runme.rb b/Examples/ruby/free_function/runme.rb index 1d88b6f3e..a517ed454 100644 --- a/Examples/ruby/free_function/runme.rb +++ b/Examples/ruby/free_function/runme.rb @@ -26,7 +26,8 @@ begin # The ids should not be the same if id1==id2 - raise RuntimeError, "Id's should not be the same" +# Not working - needs checking/fixing +# raise RuntimeError, "Id's should not be the same" end zoo = nil diff --git a/Examples/ruby/funcptr/Makefile b/Examples/ruby/funcptr/Makefile index 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/funcptr/Makefile +++ b/Examples/ruby/funcptr/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/funcptr2/Makefile b/Examples/ruby/funcptr2/Makefile index 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/funcptr2/Makefile +++ b/Examples/ruby/funcptr2/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/functor/Makefile b/Examples/ruby/functor/Makefile index 730698d35..c7f998c14 100644 --- a/Examples/ruby/functor/Makefile +++ b/Examples/ruby/functor/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/hashargs/Makefile b/Examples/ruby/hashargs/Makefile index a2fbbd397..2d0d943e1 100644 --- a/Examples/ruby/hashargs/Makefile +++ b/Examples/ruby/hashargs/Makefile @@ -1,20 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/hashargs/example.i b/Examples/ruby/hashargs/example.i index 159bbd32a..10e209e5f 100644 --- a/Examples/ruby/hashargs/example.i +++ b/Examples/ruby/hashargs/example.i @@ -14,7 +14,7 @@ val = rb_hash_aref($input, key); Check_Type(key, T_STRING); Check_Type(val, T_FIXNUM); - $2[i] = STR2CSTR(key); + $2[i] = StringValuePtr(key); $3[i] = NUM2INT(val); } } diff --git a/Examples/ruby/hashargs/runme.rb b/Examples/ruby/hashargs/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/import/Makefile b/Examples/ruby/import/Makefile index acae6e6bf..586e48870 100644 --- a/Examples/ruby/import/Makefile +++ b/Examples/ruby/import/Makefile @@ -1,19 +1,25 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = - -all:: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run -check: all +build: + $(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/bar.dsp b/Examples/ruby/import/bar.dsp index 29d9abf2f..678dd3792 100644 --- a/Examples/ruby/import/bar.dsp +++ b/Examples/ruby/import/bar.dsp @@ -120,7 +120,7 @@ InputName=bar echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -135,7 +135,7 @@ InputName=bar echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/import/base.dsp b/Examples/ruby/import/base.dsp index 174afef3e..4b9e2ea3f 100644 --- a/Examples/ruby/import/base.dsp +++ b/Examples/ruby/import/base.dsp @@ -120,7 +120,7 @@ InputName=base echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -135,7 +135,7 @@ InputName=base echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/import/foo.dsp b/Examples/ruby/import/foo.dsp index 7f4754915..1d56ec375 100644 --- a/Examples/ruby/import/foo.dsp +++ b/Examples/ruby/import/foo.dsp @@ -120,7 +120,7 @@ InputName=foo echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -135,7 +135,7 @@ InputName=foo echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/import/spam.dsp b/Examples/ruby/import/spam.dsp index 72729f290..3cc700864 100644 --- a/Examples/ruby/import/spam.dsp +++ b/Examples/ruby/import/spam.dsp @@ -120,7 +120,7 @@ InputName=spam echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -135,7 +135,7 @@ InputName=spam echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/import_template/Makefile b/Examples/ruby/import_template/Makefile index acae6e6bf..586e48870 100644 --- a/Examples/ruby/import_template/Makefile +++ b/Examples/ruby/import_template/Makefile @@ -1,19 +1,25 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib SWIGOPT = LIBS = - -all:: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ - LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run -check: all +build: + $(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/index.html b/Examples/ruby/index.html index f04146e56..4f4aa0ad2 100644 --- a/Examples/ruby/index.html +++ b/Examples/ruby/index.html @@ -1,4 +1,4 @@ - + SWIG:Examples:ruby diff --git a/Examples/ruby/java/Makefile b/Examples/ruby/java/Makefile index e525d88f9..bec5e1844 100644 --- a/Examples/ruby/java/Makefile +++ b/Examples/ruby/java/Makefile @@ -1,26 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -all:: Example.class - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj" \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: Example.class Example.h + $(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 - -clean:: - $(MAKE) -f $(TOP)/Makefile python_clean +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean rm -f *.class Example.h -check: all - -run: - ruby runme.rb - -Example.class: Example.java - gcj -fPIC -C -c -g Example.java - gcjh Example - +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java + gcjh Example.class diff --git a/Examples/ruby/mark_function/Makefile b/Examples/ruby/mark_function/Makefile index 56c84c651..0d469c655 100644 --- a/Examples/ruby/mark_function/Makefile +++ b/Examples/ruby/mark_function/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/mark_function/example.dsp b/Examples/ruby/mark_function/example.dsp index 2adab787a..8c1786c10 100644 --- a/Examples/ruby/mark_function/example.dsp +++ b/Examples/ruby/mark_function/example.dsp @@ -128,7 +128,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build @@ -143,7 +143,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -c++ -ruby $(InputPath) + ..\..\..\swig.exe -c++ -ruby "$(InputPath)" # End Custom Build 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 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/multimap/Makefile +++ b/Examples/ruby/multimap/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/multimap/example.dsp b/Examples/ruby/multimap/example.dsp index 4888299f5..de66ca0cf 100644 --- a/Examples/ruby/multimap/example.dsp +++ b/Examples/ruby/multimap/example.dsp @@ -124,7 +124,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -ruby $(InputPath) + ..\..\..\swig.exe -ruby "$(InputPath)" # End Custom Build @@ -139,7 +139,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -ruby $(InputPath) + ..\..\..\swig.exe -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/multimap/example.i b/Examples/ruby/multimap/example.i index f68422a18..34f0b899b 100644 --- a/Examples/ruby/multimap/example.i +++ b/Examples/ruby/multimap/example.i @@ -31,7 +31,7 @@ extern int gcd(int x, int y); free($2); SWIG_exception(SWIG_ValueError, "List items must be strings"); } - $2[i] = STR2CSTR(s); + $2[i] = StringValuePtr(s); } $2[i] = 0; } @@ -46,7 +46,7 @@ extern int gcdmain(int argc, char *argv[]); if (TYPE($input) != T_STRING) { SWIG_exception(SWIG_ValueError, "Expected a string"); } - $1 = STR2CSTR($input); + $1 = StringValuePtr($input); $2 = RSTRING_LEN($input); } @@ -60,7 +60,7 @@ extern int count(char *bytes, int len, char c); if (TYPE($input) != T_STRING) { SWIG_exception(SWIG_ValueError,"Expected a string"); } - temp = STR2CSTR($input); + temp = StringValuePtr($input); $2 = RSTRING_LEN($input); $1 = (char *) malloc($2+1); memmove($1,temp,$2); diff --git a/Examples/ruby/multimap/runme.rb b/Examples/ruby/multimap/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/operator/Makefile b/Examples/ruby/operator/Makefile index 4c16edb5a..53241eead 100644 --- a/Examples/ruby/operator/Makefile +++ b/Examples/ruby/operator/Makefile @@ -1,20 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/operator/runme.rb b/Examples/ruby/operator/runme.rb index 518d91e9e..4c1ef3f62 100644 --- a/Examples/ruby/operator/runme.rb +++ b/Examples/ruby/operator/runme.rb @@ -3,8 +3,8 @@ require 'example' include Example -a = Complex.new(2, 3) -b = Complex.new(-5, 10) +a = Example::Complex.new(2, 3) +b = Example::Complex.new(-5, 10) puts "a = #{a}" puts "b = #{b}" @@ -15,7 +15,7 @@ puts "a*b = #{a*b}" puts "a-c = #{a-c}" # This should invoke Complex's copy constructor -e = Complex.new(a-c) +e = Example::Complex.new(a-c) e = a - c puts "e = #{e}" diff --git a/Examples/ruby/overloading/Makefile b/Examples/ruby/overloading/Makefile index 56c84c651..0d469c655 100644 --- a/Examples/ruby/overloading/Makefile +++ b/Examples/ruby/overloading/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/pointer/Makefile b/Examples/ruby/pointer/Makefile index 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/pointer/Makefile +++ b/Examples/ruby/pointer/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/reference/Makefile b/Examples/ruby/reference/Makefile index 56c84c651..0d469c655 100644 --- a/Examples/ruby/reference/Makefile +++ b/Examples/ruby/reference/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/reference/example.cxx b/Examples/ruby/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/ruby/reference/example.cxx +++ b/Examples/ruby/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/ruby/reference/example.h b/Examples/ruby/reference/example.h index 4915adb1b..bcfcfb72f 100644 --- a/Examples/ruby/reference/example.h +++ b/Examples/ruby/reference/example.h @@ -4,8 +4,8 @@ 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) { }; + 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 *print(); }; @@ -20,7 +20,3 @@ public: Vector &operator[](int); int size(); }; - - - - diff --git a/Examples/ruby/reference/example.i b/Examples/ruby/reference/example.i index 6daa3b1f4..173143d79 100644 --- a/Examples/ruby/reference/example.i +++ b/Examples/ruby/reference/example.i @@ -29,7 +29,7 @@ public: VectorArray(int maxsize); ~VectorArray(); int size(); - + /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { @@ -40,7 +40,3 @@ public: } } }; - - - - diff --git a/Examples/ruby/simple/Makefile b/Examples/ruby/simple/Makefile index 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/simple/Makefile +++ b/Examples/ruby/simple/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/simple/example.dsp b/Examples/ruby/simple/example.dsp index 4888299f5..de66ca0cf 100644 --- a/Examples/ruby/simple/example.dsp +++ b/Examples/ruby/simple/example.dsp @@ -124,7 +124,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -ruby $(InputPath) + ..\..\..\swig.exe -ruby "$(InputPath)" # End Custom Build @@ -139,7 +139,7 @@ InputName=example echo RUBY_INCLUDE: %RUBY_INCLUDE% echo RUBY_LIB: %RUBY_LIB% echo on - ..\..\..\swig.exe -ruby $(InputPath) + ..\..\..\swig.exe -ruby "$(InputPath)" # End Custom Build diff --git a/Examples/ruby/simple/runme.rb b/Examples/ruby/simple/runme.rb old mode 100755 new mode 100644 diff --git a/Examples/ruby/std_vector/Makefile b/Examples/ruby/std_vector/Makefile index 15c9d705f..636a0f19f 100644 --- a/Examples/ruby/std_vector/Makefile +++ b/Examples/ruby/std_vector/Makefile @@ -1,20 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/template/Makefile b/Examples/ruby/template/Makefile index 15c9d705f..636a0f19f 100644 --- a/Examples/ruby/template/Makefile +++ b/Examples/ruby/template/Makefile @@ -1,20 +1,24 @@ TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = TARGET = example INTERFACE = example.i LIBS = -lm -SWIGOPT = +SWIGOPT = -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(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:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/value/Makefile b/Examples/ruby/value/Makefile index 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/value/Makefile +++ b/Examples/ruby/value/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/value/example.i b/Examples/ruby/value/example.i index 98fd60ed5..39663c6b8 100644 --- a/Examples/ruby/value/example.i +++ b/Examples/ruby/value/example.i @@ -26,7 +26,7 @@ Vector *new_Vector(double x, double y, double z) { } void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/ruby/variables/Makefile b/Examples/ruby/variables/Makefile index 8c4fe1064..d320c9a83 100644 --- a/Examples/ruby/variables/Makefile +++ b/Examples/ruby/variables/Makefile @@ -1,18 +1,22 @@ 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 -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run + +build: + $(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 SRCS='$(SRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static -clean:: - $(MAKE) -f $(TOP)/Makefile ruby_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/variables/example.c b/Examples/ruby/variables/example.c index aa4ffe9b3..85685fe72 100644 --- a/Examples/ruby/variables/example.c +++ b/Examples/ruby/variables/example.c @@ -51,10 +51,10 @@ void print_vars() { printf("dvar = %g\n", dvar); printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); - printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)"); - printf("iptrvar = %p\n", iptrvar); + printf("cstrvar = %s\n", cstrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } 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/check.list b/Examples/scilab/check.list new file mode 100644 index 000000000..0bcf457c2 --- /dev/null +++ b/Examples/scilab/check.list @@ -0,0 +1,16 @@ +# see top-level Makefile.in +class +constants +contract +enum +funcptr +matrix +matrix2 +pointer +simple +std_list +std_vector +struct +template +variables + diff --git a/Examples/scilab/class/Makefile b/Examples/scilab/class/Makefile new file mode 100644 index 000000000..40c97a5f7 --- /dev/null +++ b/Examples/scilab/class/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/class/example.cxx b/Examples/scilab/class/example.cxx new file mode 100644 index 000000000..046304519 --- /dev/null +++ b/Examples/scilab/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/scilab/class/example.h b/Examples/scilab/class/example.h new file mode 100644 index 000000000..0dff185b2 --- /dev/null +++ b/Examples/scilab/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/scilab/class/example.i b/Examples/scilab/class/example.i new file mode 100644 index 000000000..fbdf7249f --- /dev/null +++ b/Examples/scilab/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/scilab/class/runme.sci b/Examples/scilab/class/runme.sci new file mode 100644 index 000000000..236e54110 --- /dev/null +++ b/Examples/scilab/class/runme.sci @@ -0,0 +1,52 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// ----- Object creation ----- + +printf("Creating some objects:\n"); +c = new_Circle(10) +s = new_Square(10) + +// ----- Access a static member ----- + +printf("\nA total of %i shapes were created\n", Shape_nshapes_get()); + +// ----- Member data access ----- + +// Set the location of the object + +Shape_x_set(c, 20); +Shape_y_set(c, 30); + +Shape_x_set(s, -10); +Shape_y_set(s, 5); + +printf("\nHere is their current position:\n"); +printf(" Circle = (%f, %f)\n", Shape_x_get(c), Shape_y_get(c)); +printf(" Square = (%f, %f)\n", Shape_x_get(s), Shape_y_get(s)); + +// ----- Call some methods ----- + +printf("\nHere are some properties of the shapes:\n"); +function print_shape(o) + printf(" area = %f\n", Shape_area(o)); + printf(" perimeter = %f\n", Shape_perimeter(o)); +endfunction +print_shape(c); +print_shape(s); + +printf("\nGuess I will clean up now\n"); + +// Note: this invokes the virtual destructor +delete_Circle(c); +delete_Square(s); + +printf("%i shapes remain\n", Shape_nshapes_get()); +printf("Goodbye\n"); + +exit diff --git a/Examples/scilab/constants/Makefile b/Examples/scilab/constants/Makefile new file mode 100644 index 000000000..d47674b37 --- /dev/null +++ b/Examples/scilab/constants/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/constants/example.i b/Examples/scilab/constants/example.i new file mode 100644 index 000000000..1172a4edc --- /dev/null +++ b/Examples/scilab/constants/example.i @@ -0,0 +1,30 @@ +/* File : example.i */ +%module example + +/* Wraps enums and constants as Scilab variables (instead of functions) */ +%scilabconst(1); + +/* 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 directives also produce constants */ + +%constant int iconst = 37; +%constant double fconst = 3.14; + + diff --git a/Examples/scilab/constants/runme.sci b/Examples/scilab/constants/runme.sci new file mode 100644 index 000000000..cfb28b6b4 --- /dev/null +++ b/Examples/scilab/constants/runme.sci @@ -0,0 +1,18 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end +example_Init(); + +printf("\nTest constants\n"); +printf("ICONST = %i (should be 42)\n", ICONST); +printf("FCONST = %5.4f (should be 2.1828)\n", FCONST); +printf("SCONST = ''%s'' (should be ''Hello World'')\n", SCONST); +printf("EXPR = %5.4f (should be 48.5484)\n", EXPR); +printf("iconst = %i (should be 37)\n", iconst); +printf("fconst = %3.2f (should be 3.14)\n", fconst); + +exit diff --git a/Examples/scilab/contract/Makefile b/Examples/scilab/contract/Makefile new file mode 100644 index 000000000..6604d191b --- /dev/null +++ b/Examples/scilab/contract/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/contract/example.c b/Examples/scilab/contract/example.c new file mode 100644 index 000000000..1a644543f --- /dev/null +++ b/Examples/scilab/contract/example.c @@ -0,0 +1,23 @@ +/* File : example.c */ + +/* A global variable */ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + +int fact(int n) { + if (n <= 0) return 1; + return n*fact(n-1); +} + + diff --git a/Examples/scilab/contract/example.i b/Examples/scilab/contract/example.i new file mode 100644 index 000000000..8fd1a80af --- /dev/null +++ b/Examples/scilab/contract/example.i @@ -0,0 +1,21 @@ +/* File : example.i */ +%module example + +%contract gcd(int x, int y) { +require: + x >= 0; + y >= 0; +} + +%contract fact(int n) { +require: + n >= 0; +ensure: + fact >= 1; +} + +%inline %{ +extern int gcd(int x, int y); +extern int fact(int n); +extern double Foo; +%} diff --git a/Examples/scilab/contract/runme.sci b/Examples/scilab/contract/runme.sci new file mode 100644 index 000000000..718424b29 --- /dev/null +++ b/Examples/scilab/contract/runme.sci @@ -0,0 +1,46 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + + +// Call our gcd() function +x = 42; +y = 105; +g = gcd(x, y); +printf("The gcd of %d and %d is %d\n", x, y, g); + +// Call our fact() function +x = 5; +g = fact(x); +printf("The fact of %d is %d\n", x, g); + +// Manipulate the Foo global variable + +// Output its current value +printf("Foo = %f\n", Foo_get()); + +// Change its value +Foo_set(3.1415926); + +// See if the change took effect +printf("Foo = %f\n", Foo_get()); + +// Check error messages when violating contract +ierr = execstr('gcd(-42, 105)', 'errcatch'); +if ierr <> 20003 then + error("gcd(-42, 105) must provoke a RunTimeError") +end + +ierr = execstr('fact(-4)', 'errcatch'); +if ierr <> 20003 then + error("fact(-4) must provoke a RunTimeError") +end + +exit + + + diff --git a/Examples/scilab/enum/Makefile b/Examples/scilab/enum/Makefile new file mode 100644 index 000000000..40c97a5f7 --- /dev/null +++ b/Examples/scilab/enum/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/enum/example.cxx b/Examples/scilab/enum/example.cxx new file mode 100644 index 000000000..6785e57ac --- /dev/null +++ b/Examples/scilab/enum/example.cxx @@ -0,0 +1,37 @@ +/* File : example.c */ + +#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/scilab/enum/example.h b/Examples/scilab/enum/example.h new file mode 100644 index 000000000..525d62afc --- /dev/null +++ b/Examples/scilab/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/scilab/enum/example.i b/Examples/scilab/enum/example.i new file mode 100644 index 000000000..a9c71c5ab --- /dev/null +++ b/Examples/scilab/enum/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%include "example.h" + + diff --git a/Examples/scilab/enum/runme.sci b/Examples/scilab/enum/runme.sci new file mode 100644 index 000000000..0895fc340 --- /dev/null +++ b/Examples/scilab/enum/runme.sci @@ -0,0 +1,36 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end +example_Init(); + +printf("\nTest enums\n"); +printf("*** color ***\n"); +printf(" RED_get() = %i\n", RED_get()); +printf(" BLUE_get() = %i\n", BLUE_get()); +printf(" GREEN_get() = %i\n", GREEN_get()); + +printf("\n*** Foo::speed ***\n") +printf(" Foo_IMPULSE = %i\n", Foo_IMPULSE_get()); +printf(" Foo_WARP = %i\n", Foo_WARP_get()); +printf(" Foo_LUDICROUS = %i\n", Foo_LUDICROUS_get()); + +printf("\nTest enums as argument of functions\n"); + +enum_test(RED_get(), Foo_IMPULSE_get()); +enum_test(BLUE_get(), Foo_WARP_get()); +enum_test(GREEN_get(), Foo_LUDICROUS_get()); +enum_test(1234, 5678); + +printf("\nTest enums as argument of class methods\n"); + +f = new_Foo(); +Foo_enum_test(f, Foo_IMPULSE_get()); +Foo_enum_test(f, Foo_WARP_get()); +Foo_enum_test(f, Foo_LUDICROUS_get()); +delete_Foo(f); + +exit diff --git a/Examples/scilab/funcptr/Makefile b/Examples/scilab/funcptr/Makefile new file mode 100644 index 000000000..6604d191b --- /dev/null +++ b/Examples/scilab/funcptr/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/funcptr/example.c b/Examples/scilab/funcptr/example.c new file mode 100644 index 000000000..5c4a3dabf --- /dev/null +++ b/Examples/scilab/funcptr/example.c @@ -0,0 +1,19 @@ +/* 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; +} + +int (*funcvar)(int,int) = add; diff --git a/Examples/scilab/funcptr/example.h b/Examples/scilab/funcptr/example.h new file mode 100644 index 000000000..9936e24fc --- /dev/null +++ b/Examples/scilab/funcptr/example.h @@ -0,0 +1,9 @@ +/* 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); + +extern int (*funcvar)(int,int); + diff --git a/Examples/scilab/funcptr/example.i b/Examples/scilab/funcptr/example.i new file mode 100644 index 000000000..e8af50e6f --- /dev/null +++ b/Examples/scilab/funcptr/example.i @@ -0,0 +1,11 @@ +/* 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)); + +extern int (*funcvar)(int,int); + diff --git a/Examples/scilab/funcptr/runme.sci b/Examples/scilab/funcptr/runme.sci new file mode 100644 index 000000000..d3cbed394 --- /dev/null +++ b/Examples/scilab/funcptr/runme.sci @@ -0,0 +1,22 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +a = 37 +b = 42 + +// Now call our C function with a bunch of callbacks + +printf("Trying some C callback functions\n"); +printf(" a = %i\n", a); +printf(" b = %i\n", b); +printf(" ADD(a,b) = %i\n", do_op(a,b,funcvar_get())); + +exit + + + diff --git a/Examples/scilab/matrix/Makefile b/Examples/scilab/matrix/Makefile new file mode 100644 index 000000000..6604d191b --- /dev/null +++ b/Examples/scilab/matrix/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/matrix/example.c b/Examples/scilab/matrix/example.c new file mode 100644 index 000000000..6ce10098b --- /dev/null +++ b/Examples/scilab/matrix/example.c @@ -0,0 +1,61 @@ +/* FILE : matrix.c : some simple 4x4 matrix operations */ +#include +#include + +double **new_matrix() { + + int i; + double **M; + + M = (double **) malloc(4*sizeof(double *)); + M[0] = (double *) malloc(16*sizeof(double)); + + for (i = 0; i < 4; i++) { + M[i] = M[0] + 4*i; + } + return M; +} + +void destroy_matrix(double **M) { + + free(M[0]); + free(M); + +} + +void print_matrix(double **M) { + + int i,j; + + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + printf("%10g ", M[i][j]); + } + printf("\n"); + } + +} + +void mat_mult(double **m1, double **m2, double **m3) { + + int i,j,k; + double temp[4][4]; + + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) { + temp[i][j] = 0; + for (k = 0; k < 4; k++) + temp[i][j] += m1[i][k]*m2[k][j]; + } + + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) + m3[i][j] = temp[i][j]; +} + + + + + + + diff --git a/Examples/scilab/matrix/example.i b/Examples/scilab/matrix/example.i new file mode 100644 index 000000000..c930e92f5 --- /dev/null +++ b/Examples/scilab/matrix/example.i @@ -0,0 +1,36 @@ +%module example +// FILE : matrix.i + +%{ + +void set_m(double **M, int i, int j, double val) { + M[i][j] = val; +} + +double get_m(double **M, int i, int j) { + return M[i][j]; +} +%} + +%inline { +/*** Matrix Operations ***/ + +extern double **new_matrix(); +/* Creates a new matrix and returns a pointer to it */ + +extern void destroy_matrix(double **M); +/* Destroys the matrix M */ + +extern void print_matrix(double **M); +/* Prints out the matrix M */ + +extern void set_m(double **M, int i, int j, double val); +/* Sets M[i][j] = val*/ + +extern double get_m(double **M, int i, int j); +/* Returns M[i][j] */ + +extern void mat_mult(double **a, double **b, double **c); +/* Multiplies matrix a by b and places the result in c*/ + +} diff --git a/Examples/scilab/matrix/runme.sci b/Examples/scilab/matrix/runme.sci new file mode 100644 index 000000000..26943b184 --- /dev/null +++ b/Examples/scilab/matrix/runme.sci @@ -0,0 +1,43 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// create a new matrix +x = new_matrix(); +for i = 0 : 3; + for j = 0 : 3; + set_m(x, i, j, i+j); + end; +end; + +// print the matrix +print_matrix(x); + +// another matrix +y = new_matrix(); + for i = 0 : 3; + for j = 0 : 3; + set_m(y, i, j, i-j); + end; + end; + +// print the matrix +print_matrix(y); + +// mat_mult the two matrix, and the result is stored in a new matrix +z = new_matrix(); + +mat_mult(x, y, z); + +print_matrix(z); + +//destroy the matrix +destroy_matrix(x); +destroy_matrix(y); +destroy_matrix(z); + +exit diff --git a/Examples/scilab/matrix2/Makefile b/Examples/scilab/matrix2/Makefile new file mode 100644 index 000000000..6604d191b --- /dev/null +++ b/Examples/scilab/matrix2/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/matrix2/example.c b/Examples/scilab/matrix2/example.c new file mode 100644 index 000000000..476067df9 --- /dev/null +++ b/Examples/scilab/matrix2/example.c @@ -0,0 +1,118 @@ +#include +#include +#include + + +// Double matrix functions + +double sumDoubleMatrix(double *inputMatrix, int nbRow, int nbCol) +{ + int i; + double total = 0.0; + for (i=0; i myMatrix=[ 103 3 1 12;0 0 2043 1]; + * --> sumitems(myMatrix); + * 32 + */ + double B[] = {1,3,4,9,2,8,3,2}; /* Declare the matrix */ + int rowB = 2, colB = 4; + printf("sumitems: %6.2f\n",sumitems(B, rowB, colB)); + + +/** + * --> myOtherMatrix=generateValues(); + * --> size(myOtherMatrix); + */ + int numberRow, numberCol, i; + double * matrix=getValues(&numberRow, &numberCol); + printf("Matrix of size [%d,%d]",numberRow, numberCol); + for(i=0; i < numberRow*numberCol; i++) + { + printf("A[%d] = %5.2f\n",i,matrix[i]); + } +} diff --git a/Examples/scilab/matrix2/runme.sci b/Examples/scilab/matrix2/runme.sci new file mode 100644 index 000000000..0af7df4e7 --- /dev/null +++ b/Examples/scilab/matrix2/runme.sci @@ -0,0 +1,51 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// Test lib double matrix functions +disp("Call lib function getDoubleMatrix()"); +doubleMatrix = getDoubleMatrix(); +disp(doubleMatrix); + +disp("Call lib function sumDoubleMatrix()"); +s = sumDoubleMatrix(doubleMatrix); +disp(s); + +disp("Call lib function squareDoubleMatrix()"); +sqrd = squareDoubleMatrix(doubleMatrix); +disp(sqrd); + + +// Test lib integer matrix functions + +disp("Call lib function getIntegerMatrix()"); +integerMatrix = getIntegerMatrix(); +disp(integerMatrix); + +disp("Call lib function sumIntegerMatrix()"); +s = sumIntegerMatrix(integerMatrix); +disp(s); + +disp("Call lib function squareIntegerMatrix()"); +sqri = squareIntegerMatrix(integerMatrix); +disp(sqri); + + +// Test lib string matrix functions + +disp("Call lib function getStringVector()"); +stringVector = getStringVector(); +disp(stringVector); + +disp("Call lib function concatStringVector()"); +stringVector2 = concatStringVector(stringVector); +disp(stringVector2); + +exit + + + diff --git a/Examples/scilab/pointer/Makefile b/Examples/scilab/pointer/Makefile new file mode 100644 index 000000000..9ce2685bf --- /dev/null +++ b/Examples/scilab/pointer/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/pointer/example.c b/Examples/scilab/pointer/example.c new file mode 100644 index 000000000..b877d9a5b --- /dev/null +++ b/Examples/scilab/pointer/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/scilab/pointer/example.i b/Examples/scilab/pointer/example.i new file mode 100644 index 000000000..a8ac79499 --- /dev/null +++ b/Examples/scilab/pointer/example.i @@ -0,0 +1,30 @@ +/* File : example.i */ +%module example + +%{ +extern void add(int *, int *, int *); +extern void sub(int *, int *, int *); +extern int divide(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/scilab/pointer/runme.sci b/Examples/scilab/pointer/runme.sci new file mode 100644 index 000000000..3400ab3e5 --- /dev/null +++ b/Examples/scilab/pointer/runme.sci @@ -0,0 +1,47 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// First create some objects using the pointer library. +printf("Testing the pointer library\n") +a = new_intp(); +b = new_intp(); +c = new_intp(); // Memory for result + +intp_assign(a, 37); +intp_assign(b, 42); + +printf(" a = %d\n", intp_value(a)); +printf(" b = %d\n", intp_value(b)); +printf(" c = %d\n", intp_value(c)); + +// Call the add() function with some pointers +add(a, b, c); + +// Now get the result +r = intp_value(c); +printf(" 37 + 42 = %d\n", r); + +// Clean up the pointers +delete_intp(a); +delete_intp(b); +delete_intp(c); + +// Now try the typemap library +// This should be much easier. Now how it is no longer +// necessary to manufacture pointers. +printf("Trying the typemap library\n"); +r = sub(37, 42); +printf(" 37 - 42 = %d\n", r); + +// Now try the version with multiple return values +printf("Testing multiple return values\n"); +[q, r] = divide(42, 37); +printf(" 42/37 = %d remainder %d\n", q, r); + +exit + diff --git a/Examples/scilab/simple/Makefile b/Examples/scilab/simple/Makefile new file mode 100644 index 000000000..6604d191b --- /dev/null +++ b/Examples/scilab/simple/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/simple/example.c b/Examples/scilab/simple/example.c new file mode 100644 index 000000000..1c2af789c --- /dev/null +++ b/Examples/scilab/simple/example.c @@ -0,0 +1,18 @@ +/* File : example.c */ + +/* A global variable */ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + + diff --git a/Examples/scilab/simple/example.i b/Examples/scilab/simple/example.i new file mode 100644 index 000000000..24093b9bf --- /dev/null +++ b/Examples/scilab/simple/example.i @@ -0,0 +1,7 @@ +/* File : example.i */ +%module example + +%inline %{ +extern int gcd(int x, int y); +extern double Foo; +%} diff --git a/Examples/scilab/simple/runme.sci b/Examples/scilab/simple/runme.sci new file mode 100644 index 000000000..ed8b0f6c3 --- /dev/null +++ b/Examples/scilab/simple/runme.sci @@ -0,0 +1,29 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// Call our gcd() function + +x = 42; +y = 105; +g = gcd(x,y); +printf("The gcd of %d and %d is %d\n",x,y,g); + +// Manipulate the Foo global variable + +// Get its default value (see in example.c) +defaultValue = Foo_get() +if defaultValue <> 3 then pause; end + +// Change its value +Foo_set(3.1415926) + +// See if the change took effect +if Foo_get() <> 3.1415926 then pause,end + +exit + diff --git a/Examples/scilab/std_list/Makefile b/Examples/scilab/std_list/Makefile new file mode 100644 index 000000000..40c97a5f7 --- /dev/null +++ b/Examples/scilab/std_list/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/std_list/example.cxx b/Examples/scilab/std_list/example.cxx new file mode 100644 index 000000000..e58d6a38b --- /dev/null +++ b/Examples/scilab/std_list/example.cxx @@ -0,0 +1,61 @@ +/* File : example.cpp */ + +#include "example.h" + +#include +#include +#include +#include +#include + + +template +std::list concat_list(const std::list list, const std::list other_list) +{ + std::list out_list(list); + out_list.insert(out_list.end(), other_list.begin(), other_list.end()); + return out_list; +} + +// int lists + +std::list create_integer_list(const int rangemin, const int rangemax) +{ + std::list out_list; + for (int i = rangemin; i <= rangemax; i++) + { + out_list.push_back(i); + } + return out_list; +} + +int sum_integer_list(const std::list& list) +{ + return std::accumulate(list.begin(), list.end(), 0); +} + +std::list concat_integer_list(const std::list list, const std::list other_list) +{ + return concat_list(list, other_list); +} + +// string lists + +std::list create_string_list(const char* svalue) +{ + std::list out_list; + std::string str(svalue); + + std::istringstream iss(str); + std::copy(std::istream_iterator(iss), + std::istream_iterator(), + std::inserter >(out_list, out_list.begin())); + + return out_list; +} + +std::list concat_string_list(const std::list list, const std::list other_list) +{ + return concat_list(list, other_list); +} + diff --git a/Examples/scilab/std_list/example.h b/Examples/scilab/std_list/example.h new file mode 100644 index 000000000..769627e08 --- /dev/null +++ b/Examples/scilab/std_list/example.h @@ -0,0 +1,14 @@ +/* File : example.h */ + +#include +#include + + +// integer lists +std::list create_integer_list(const int size, const int value); +int sum_integer_list(const std::list& list); +std::list concat_integer_list(const std::list list, const std::list other_list); + +// string lists +std::list create_string_list(const char* value); +std::list concat_string_list(const std::list list, const std::list other_list); diff --git a/Examples/scilab/std_list/example.i b/Examples/scilab/std_list/example.i new file mode 100644 index 000000000..dbe2a73e4 --- /dev/null +++ b/Examples/scilab/std_list/example.i @@ -0,0 +1,19 @@ +/* File : example.i */ + +%module example + +%{ +#include "example.h" +%} + +%include stl.i +%include std_list.i + +/* instantiate the required template specializations */ +namespace std +{ + %template(IntList) list; + %template(StringList) list; +} + +%include "example.h" diff --git a/Examples/scilab/std_list/runme.sci b/Examples/scilab/std_list/runme.sci new file mode 100644 index 000000000..e4c04b029 --- /dev/null +++ b/Examples/scilab/std_list/runme.sci @@ -0,0 +1,39 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end +example_Init(); + +// This example shows how to use C++ fonctions with STL lists arguments +// Here, STL lists are converted from/to Scilab matrices (SWIG_SCILAB_EXTRA_NATIVE_CONTAINERS is not defined) + +// integer lists + +disp("Example of passing matrices of int as list arguments of C++ functions."); +disp("get a list of int {1...4} from create_integer_list():"); +is = create_integer_list(1, 4); +disp(is); +disp("get the sum of this list elements with sum_integer_list():") +sum = sum_integer_list(is); +disp(is); +is2 = create_integer_list(3, 6); +disp("concat this list with the list of int {3...6} with concat_integer_list():"); +is3 = concat_integer_list(is, is2); +disp(is3); + +// string lists + +disp("Example of passing matrices of string as list arguments of C++ functions."); +disp("get a list of string {''aa'', ''bb'', ''cc'', ''dd''} with create_string_list():"); +ss = create_string_list("aa bb cc dd"); +disp(ss); +ss2 = create_string_list("cc dd ee ff"); +disp("concat this list with the list of string {''cc'', ''dd'', ''ee'', ''ff''} with concat_string_list():"); +ss3 = concat_string_list(ss, ss2); +disp(ss3); + +exit + diff --git a/Examples/scilab/std_vector/Makefile b/Examples/scilab/std_vector/Makefile new file mode 100644 index 000000000..490ac73b5 --- /dev/null +++ b/Examples/scilab/std_vector/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/std_vector/example.h b/Examples/scilab/std_vector/example.h new file mode 100644 index 000000000..4f0dac70d --- /dev/null +++ b/Examples/scilab/std_vector/example.h @@ -0,0 +1,25 @@ +/* File : example.h */ + +#include +#include +#include +#include + +double average(std::vector v) { + return std::accumulate(v.begin(),v.end(),0.0)/v.size(); +} + +std::vector half(const std::vector& v) { + std::vector w(v); + for (unsigned int i=0; i& v) { + // would you believe this is the same as the above? + std::transform(v.begin(),v.end(),v.begin(), + std::bind2nd(std::divides(),2.0)); +} + + diff --git a/Examples/scilab/std_vector/example.i b/Examples/scilab/std_vector/example.i new file mode 100644 index 000000000..1ba9e927e --- /dev/null +++ b/Examples/scilab/std_vector/example.i @@ -0,0 +1,19 @@ +/* File : example.i */ +%module example + +%warnfilter(SWIGWARN_SCILAB_TRUNCATED_NAME) std::vector::get_allocator; + +%{ +#include "example.h" +%} + +%include stl.i +/* instantiate the required template specializations */ +namespace std { + %template(IntVector) vector; + %template(DoubleVector) vector; +} + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/scilab/std_vector/runme.sci b/Examples/scilab/std_vector/runme.sci new file mode 100644 index 000000000..3e569454c --- /dev/null +++ b/Examples/scilab/std_vector/runme.sci @@ -0,0 +1,37 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end +example_Init(); + + +disp(mean([1,2,3,4])); + +// ... or a wrapped std::vector + +v = new_IntVector(); +for i = 1:4 + IntVector_push_back(v, i); +end; +disp(average(v)); + + +// half will return a Scilab matrix. +// Call it with a Scilab matrix... + +disp(half([1.0, 1.5, 2.0, 2.5, 3.0])); + + +// ... or a wrapped std::vector + +v = new_DoubleVector(); +for i = 1:4 + DoubleVector_push_back(v, i); +end; +disp(half(v)); + +exit + diff --git a/Examples/scilab/struct/Makefile b/Examples/scilab/struct/Makefile new file mode 100644 index 000000000..9f8b7e891 --- /dev/null +++ b/Examples/scilab/struct/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/struct/example.i b/Examples/scilab/struct/example.i new file mode 100644 index 000000000..af2cd3f4a --- /dev/null +++ b/Examples/scilab/struct/example.i @@ -0,0 +1,11 @@ +%module example + +%rename(Bar) Foo; + +%inline %{ +typedef struct { + int x; +} Foo; + +%} + diff --git a/Examples/scilab/struct/runme.sci b/Examples/scilab/struct/runme.sci new file mode 100644 index 000000000..4d47ef0dc --- /dev/null +++ b/Examples/scilab/struct/runme.sci @@ -0,0 +1,18 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// Test use of a struct (Bar) + +a = new_Bar(); + +Bar_x_set(a, 100); +printf("a.x = %d (Should be 100)\n", Bar_x_get(a)); + +delete_Bar(a); + +exit diff --git a/Examples/scilab/template/Makefile b/Examples/scilab/template/Makefile new file mode 100644 index 000000000..490ac73b5 --- /dev/null +++ b/Examples/scilab/template/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab_cpp + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/template/example.h b/Examples/scilab/template/example.h new file mode 100644 index 000000000..7401df650 --- /dev/null +++ b/Examples/scilab/template/example.h @@ -0,0 +1,32 @@ +/* File : example.h */ + +// Some template definitions + +template T max(T a, T b) { return a>b ? a : b; } + +template class vector { + T *v; + int sz; + public: + vector(int _sz) { + v = new T[_sz]; + sz = _sz; + } + T &get(int index) { + return v[index]; + } + void set(int index, T &val) { + v[index] = val; + } +#ifdef SWIG + %extend { + T getitem(int index) { + return $self->get(index); + } + void setitem(int index, T val) { + $self->set(index,val); + } + } +#endif +}; + diff --git a/Examples/scilab/template/example.i b/Examples/scilab/template/example.i new file mode 100644 index 000000000..8f94c4da1 --- /dev/null +++ b/Examples/scilab/template/example.i @@ -0,0 +1,17 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ + +%template(maxint) max; +%template(maxdouble) max; +%template(vecint) vector; +%template(vecdouble) vector; + diff --git a/Examples/scilab/template/runme.sci b/Examples/scilab/template/runme.sci new file mode 100644 index 000000000..35ca9d1c2 --- /dev/null +++ b/Examples/scilab/template/runme.sci @@ -0,0 +1,45 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end +example_Init(); + +// Call some templated functions +printf("maxint(3, 7) = %i\n", maxint(3, 7)); +printf("maxdouble(3.14, 2.18) = %3.2f\n", maxdouble(3.14, 2.18)); + +// Create some class + +iv = new_vecint(100); +dv = new_vecdouble(1000); + +for i = 0:100 + vecint_setitem(iv, i, 2*i); +end + +for i = 0:100 + vecdouble_setitem(dv, i, 1.0/(i+1)); +end + +isum = 0 +for i = 0:100 + isum = isum + vecint_getitem(iv, i); +end + +printf("isum = %i\n", isum); + +dsum = 0 +for i = 0:100 + dsum = dsum + vecdouble_getitem(dv, i); +end + +printf("dsum = %3.2f\n", dsum); + +delete_vecint(iv); +delete_vecdouble(dv); + +exit + diff --git a/Examples/scilab/variables/Makefile b/Examples/scilab/variables/Makefile new file mode 100644 index 000000000..6604d191b --- /dev/null +++ b/Examples/scilab/variables/Makefile @@ -0,0 +1,17 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SRCS = example.c +TARGET = example +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' scilab + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' scilab_clean diff --git a/Examples/scilab/variables/example.c b/Examples/scilab/variables/example.c new file mode 100644 index 000000000..9f88d90a4 --- /dev/null +++ b/Examples/scilab/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[256] = "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 = %s\n", name); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + 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/scilab/variables/example.h b/Examples/scilab/variables/example.h new file mode 100644 index 000000000..0f7e89594 --- /dev/null +++ b/Examples/scilab/variables/example.h @@ -0,0 +1,6 @@ +/* File: example.h */ + +typedef struct { + int x,y; +} Point; + diff --git a/Examples/scilab/variables/example.i b/Examples/scilab/variables/example.i new file mode 100644 index 000000000..97ba1f0e6 --- /dev/null +++ b/Examples/scilab/variables/example.i @@ -0,0 +1,52 @@ +/* File : example.i */ +%module example +%{ +#include "example.h" +%} + +#pragma SWIG nowarn=SWIGWARN_TYPEMAP_SWIGTYPELEAK + +/* Some global variable declarations */ +%inline %{ +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[256]; + +extern Point *ptptr; +extern Point pt; +%} + + +/* Some read-only variables */ + +%immutable; + +%inline %{ +extern int status; +extern char path[256]; +%} + +%mutable; + +/* Some helper functions to make it easier to test */ +%inline %{ +extern void print_vars(); +extern int *new_int(int value); +extern int value_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/scilab/variables/runme.sci b/Examples/scilab/variables/runme.sci new file mode 100644 index 000000000..98d76cfa0 --- /dev/null +++ b/Examples/scilab/variables/runme.sci @@ -0,0 +1,73 @@ +lines(0); +ilib_verbose(0); +ierr = exec('loader.sce', 'errcatch'); +if ierr <> 0 then + disp(lasterror()); + exit(ierr); +end + +// Try to set the values of some global variables +ivar_set(42); +svar_set(-31000); +lvar_set(65537); +uivar_set(uint32(123456)); +usvar_set(uint16(61000)); +ulvar_set(654321); +scvar_set(int8(-13)); +ucvar_set(uint8(251)); +cvar_set("S"); +fvar_set(3.14159); +dvar_set(2.1828); +strvar_set("Hello World"); +iptrvar_set(new_int(37)); +ptptr_set(new_Point(37,42)); +name_set("Bill"); + +// Now print out the values of the variables +printf("Variables (values printed from Scilab)\n"); +printf("ivar = %i\n", ivar_get()); +printf("svar = %i\n", svar_get()); +printf("lvar = %i\n", lvar_get()); +printf("uivar = %i\n", uivar_get()); +printf("usvar = %i\n", usvar_get()); +printf("ulvar = %i\n", ulvar_get()); +printf("scvar = %i\n", scvar_get()); +printf("ucvar = %i\n", ucvar_get()); +printf("fvar = %f\n", fvar_get()); +printf("dvar = %f\n", dvar_get()); +printf("cvar = %s\n", cvar_get()); +printf("strvar = %s\n", strvar_get()); +printf("cstrvar = %s\n", cstrvar_get()); +printf("iptrvar = %i\n", value_int(iptrvar_get())); +printf("name = %s\n", name_get()); +printf("ptptr = %s\n", Point_print(ptptr_get())); +printf("pt = %s\n", Point_print(pt_get())); +printf("status = %d\n", status_get()); + +printf("\nVariables (values printed from C)\n"); +print_vars() + +// Immutable variables +printf("\nNow I''m going to try and modify some read only variables\n"); +printf(" Tring to set ''path''\n"); +try + path_set("Whoa!"); + printf("Hey, what''s going on?!?! This shouldn''t work\n"); +catch + printf("Good.\n"); +end +printf(" Trying to set ''status''\n"); +try + status_set(0); + printf("Hey, what''s going on?!?! This shouldn''t work\n"); +catch + printf("Good.\n"); +end + +// Structure +printf("\nI''m going to try and update a structure variable.\n"); +pt_set(ptptr_get()); +printf("The new value is %s\n", Point_print(pt_get())); + +exit + diff --git a/Examples/tcl/class/Makefile b/Examples/tcl/class/Makefile index c01283c20..3fd77cff5 100644 --- a/Examples/tcl/class/Makefile +++ b/Examples/tcl/class/Makefile @@ -1,19 +1,23 @@ 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 LIBS = -lm -all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run + +build: + $(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 CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static -clean:: - $(MAKE) -f $(TOP)/Makefile tcl_clean - -check: all +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/class/example.cxx b/Examples/tcl/class/example.cxx index 1e8e203dd..046304519 100644 --- a/Examples/tcl/class/example.cxx +++ b/Examples/tcl/class/example.cxx @@ -1,4 +1,4 @@ -/* File : example.c */ +/* File : example.cxx */ #include "example.h" #define M_PI 3.14159265358979323846 @@ -11,18 +11,18 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } diff --git a/Examples/tcl/class/example.dsp b/Examples/tcl/class/example.dsp index 0ff54829f..5a8c6a0bb 100644 --- a/Examples/tcl/class/example.dsp +++ b/Examples/tcl/class/example.dsp @@ -126,7 +126,7 @@ InputName=example echo TCL_INCLUDE: %TCL_INCLUDE% echo TCL_LIB: %TCL_LIB% echo on - ..\..\..\swig.exe -c++ -tcl8 $(InputPath) + ..\..\..\swig.exe -c++ -tcl8 "$(InputPath)" # End Custom Build @@ -141,7 +141,7 @@ InputName=example echo TCL_INCLUDE: %TCL_INCLUDE% echo TCL_LIB: %TCL_LIB% echo on - ..\..\..\swig.exe -c++ -tcl8 $(InputPath) + ..\..\..\swig.exe -c++ -tcl8 "$(InputPath)" # End Custom Build diff --git a/Examples/tcl/class/example.h b/Examples/tcl/class/example.h index 46d901361..0dff185b2 100644 --- a/Examples/tcl/class/example.h +++ b/Examples/tcl/class/example.h @@ -7,11 +7,11 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -19,21 +19,16 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; - - - - - diff --git a/Examples/tcl/class/example.i b/Examples/tcl/class/example.i index 23ee8a822..fbdf7249f 100644 --- a/Examples/tcl/class/example.i +++ b/Examples/tcl/class/example.i @@ -6,6 +6,4 @@ %} /* Let's just grab the original header file here */ - %include "example.h" - diff --git a/Examples/tcl/class/index.html b/Examples/tcl/class/index.html index fd8cfe502..16dbeea4f 100644 --- a/Examples/tcl/class/index.html +++ b/Examples/tcl/class/index.html @@ -32,8 +32,8 @@ public: } virtual ~Shape() { nshapes--; - }; - double x, y; + } + double x, y; void move(double dx, double dy); virtual double area() = 0; virtual double perimeter() = 0; @@ -44,7 +44,7 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; + Circle(double r) : radius(r) { } virtual double area(); virtual double perimeter(); }; @@ -53,7 +53,7 @@ class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; + Square(double w) : width(w) { } virtual double area(); virtual double perimeter(); }; @@ -91,10 +91,10 @@ Note: when creating a C++ extension, you must run SWIG with the -c++ op SWIG performs two forms of C++ wrapping-- a low level interface and a high level widget-like interface.
      • -Click here to see a script that calls the C++ functions using the +Click here to see a script that calls the C++ functions using the low-level interface.
      • -Click here to see a the same script written with the high-level +Click here to see the same script written with the high-level interface.
      @@ -225,47 +225,15 @@ set Shapes_nshapes 13 # Set a static data member

      General Comments