Downloads:
413,670
Downloads of v 4.0.2.04082020:
87,734
Last Update:
06 Aug 2020
Package Maintainer(s):
Software Author(s):
- William Fulton
Tags:
interface-generator wrapper-generator programming-language- Software Specific:
- Software Site
- Package Specific:
- Package Source
- Package outdated?
- Package broken?
- Contact Maintainers
- Contact Site Admins
- Software Vendor?
- Report Abuse
- Download
Simplified Wrapper and Interface Generator
This is not the latest version of Simplified Wrapper and Interface Generator available.
- 1
- 2
- 3
4.0.2.04082020 | Updated: 06 Aug 2020
- Software Specific:
- Software Site
- Package Specific:
- Package Source
- Package outdated?
- Package broken?
- Contact Maintainers
- Contact Site Admins
- Software Vendor?
- Report Abuse
- Download
Downloads:
413,670
Downloads of v 4.0.2.04082020:
87,734
Maintainer(s):
Software Author(s):
- William Fulton
Simplified Wrapper and Interface Generator 4.0.2.04082020
This is not the latest version of Simplified Wrapper and Interface Generator available.
Legal Disclaimer: Neither this package nor Chocolatey Software, Inc. are affiliated with or endorsed by William Fulton. The inclusion of William Fulton trademark(s), if any, upon this webpage is solely to identify William Fulton goods or services and not for commercial purposes.
- 1
- 2
- 3
Some Checks Have Failed or Are Not Yet Complete
Not All Tests Have Passed
Validation Testing Passed
Verification Testing Passed
DetailsScan Testing Resulted in Flagged:
This package was submitted (and approved) prior to automated virus scanning integration into the package moderation processs.
We recommend clicking the "Details" link to make your own decision on installing this package.
Deployment Method: Individual Install, Upgrade, & Uninstall
To install Simplified Wrapper and Interface Generator, run the following command from the command line or from PowerShell:
To upgrade Simplified Wrapper and Interface Generator, run the following command from the command line or from PowerShell:
To uninstall Simplified Wrapper and Interface Generator, run the following command from the command line or from PowerShell:
Deployment Method:
This applies to both open source and commercial editions of Chocolatey.
1. Enter Your Internal Repository Url
(this should look similar to https://community.chocolatey.org/api/v2/)
2. Setup Your Environment
1. Ensure you are set for organizational deployment
Please see the organizational deployment guide
2. Get the package into your environment
Option 1: Cached Package (Unreliable, Requires Internet - Same As Community)-
Open Source or Commercial:
- Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
- You can also just download the package and push it to a repository Download
-
Open Source
-
Download the package:
Download - Follow manual internalization instructions
-
-
Package Internalizer (C4B)
-
Run: (additional options)
choco download swig --internalize --version=4.0.2.04082020 --source=https://community.chocolatey.org/api/v2/
-
For package and dependencies run:
choco push --source="'INTERNAL REPO URL'"
- Automate package internalization
-
Run: (additional options)
3. Copy Your Script
choco upgrade swig -y --source="'INTERNAL REPO URL'" --version="'4.0.2.04082020'" [other options]
See options you can pass to upgrade.
See best practices for scripting.
Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.
If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:
choco upgrade swig -y --source="'INTERNAL REPO URL'" --version="'4.0.2.04082020'"
$exitCode = $LASTEXITCODE
Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
Exit 0
}
Exit $exitCode
- name: Install swig
win_chocolatey:
name: swig
version: '4.0.2.04082020'
source: INTERNAL REPO URL
state: present
See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.
chocolatey_package 'swig' do
action :install
source 'INTERNAL REPO URL'
version '4.0.2.04082020'
end
See docs at https://docs.chef.io/resource_chocolatey_package.html.
cChocoPackageInstaller swig
{
Name = "swig"
Version = "4.0.2.04082020"
Source = "INTERNAL REPO URL"
}
Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.
package { 'swig':
ensure => '4.0.2.04082020',
provider => 'chocolatey',
source => 'INTERNAL REPO URL',
}
Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.
4. If applicable - Chocolatey configuration/installation
See infrastructure management matrix for Chocolatey configuration elements and examples.
This package was approved by moderator gep13 on 31 Aug 2020.
SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages. SWIG is used with different types of target languages including common scripting languages such as Perl, PHP, Python, Tcl and Ruby. The list of supported languages also includes non-scripting languages such as C#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), D, Go language, Java, Lua, Modula-3, OCAML, Octave and R. Also several interpreted and compiled Scheme implementations (Guile, MzScheme/Racket, Chicken) are supported. SWIG is most commonly used to create high-level interpreted or compiled programming environments, user interfaces, and as a tool for testing and prototyping C/C++ software. SWIG is typically used to parse C/C++ interfaces and generate the 'glue code' required for the above target languages to call into the C/C++ code. SWIG can also export its parse tree in the form of XML and Lisp s-expressions.
#! /bin/sh
# Bootstrap the development environment - add extra files needed to run configure.
# Note autoreconf should do what this file achieves, but it has a bug when working with automake!
# The latest config.guess and config.sub should be copied into Tools/config.
# This script will ensure the latest is copied from your autotool installation.
set -e
set -x
test -d Tools/config || mkdir Tools/config
${ACLOCAL-aclocal} -I Tools/config
${AUTOHEADER-autoheader}
${AUTOMAKE-automake} --add-missing --copy --force-missing
${AUTOCONF-autoconf}
cd CCache && ${AUTORECONF-autoreconf}
md5: 352CA435F2DDDB713AEA939A92931F05 | sha1: 5DF4FF60A3A35B67CAC594BDC8FA03C2EF0A90C8 | sha256: BFC4EDF3747CD96DF47BBD6F2B114F564B2828515A4FEF7BA3AD980C704BEFF1 | sha512: 2F1D55CC9E2C00515D43C50A8537ECCCA2A9CA62E058AF25CF20A361F10C6DFF810FE2B7FE2518DE8538A7B4178ABC4BFAE7FC1A766476F1BCE97C3903509623
#!/bin/sh
# a simple test suite for ccache
# [email protected]
if test -n "$CC"; then
COMPILER="$CC"
else
COMPILER=cc
fi
if test -n "$SWIG"; then
SWIG="$SWIG"
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'`"
if test -n "$CCACHE"; then
CCACHE="$CCACHE"
else
CCACHE=../ccache-swig
fi
TESTDIR=test.$$
test_failed() {
reason="$1"
echo $1
$CCACHE -s
cd ..
rm -rf $TESTDIR
echo TEST FAILED
exit 1
}
randcode() {
outfile="$1"
nlines=$2
i=0;
(
while [ $i -lt $nlines ]; do
echo "int foo$nlines$i(int x) { return x; }"
i=`expr $i + 1`
done
) >> "$outfile"
}
genswigcode() {
outfile="$1"
nlines=$2
i=0;
(
echo "%module swigtest$2;"
while [ $i -lt $nlines ]; do
echo "int foo$nlines$i(int x);"
echo "struct Bar$nlines$i { int y; };"
i=`expr $i + 1`
done
) >> "$outfile"
}
getstat() {
stat="$1"
value=`$CCACHE -s | grep "$stat" | cut -c34-40`
echo $value
}
checkstat() {
stat="$1"
expected_value="$2"
value=`getstat "$stat"`
# echo "exp: $expected_value got: $value $testname"
if [ "$expected_value" != "$value" ]; then
test_failed "SUITE: $testsuite TEST: $testname - Expected $stat to be $expected_value got $value"
fi
}
basetests() {
echo "starting testsuite $testsuite"
rm -rf "$CCACHE_DIR"
checkstat 'cache hit' 0
checkstat 'cache miss' 0
j=1
rm -f *.c
while [ $j -lt 32 ]; do
randcode test$j.c $j
j=`expr $j + 1`
done
testname="BASIC"
$CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 0
checkstat 'cache miss' 1
testname="BASIC2"
$CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 1
checkstat 'cache miss' 1
testname="debug"
$CCACHE_COMPILE -c test1.c -g
checkstat 'cache hit' 1
checkstat 'cache miss' 2
testname="debug2"
$CCACHE_COMPILE -c test1.c -g
checkstat 'cache hit' 2
checkstat 'cache miss' 2
testname="output"
$CCACHE_COMPILE -c test1.c -o foo.o
checkstat 'cache hit' 3
checkstat 'cache miss' 2
testname="link"
$CCACHE_COMPILE test1.c -o test 2> /dev/null
checkstat 'called for link' 1
testname="multiple"
$CCACHE_COMPILE -c test1.c test2.c
checkstat 'multiple source files' 1
testname="find"
$CCACHE blahblah -c test1.c 2> /dev/null
checkstat "couldn't find the compiler" 1
testname="bad"
$CCACHE_COMPILE -c test1.c -I 2> /dev/null
checkstat 'bad compiler arguments' 1
testname="c/c++"
ln -f test1.c test1.ccc
$CCACHE_COMPILE -c test1.ccc 2> /dev/null
checkstat 'not a C/C++ file' 1
testname="unsupported"
$CCACHE_COMPILE -M foo -c test1.c > /dev/null 2>&1
checkstat 'unsupported compiler option' 1
testname="stdout"
$CCACHE echo foo -c test1.c > /dev/null
checkstat 'compiler produced stdout' 1
testname="non-regular"
mkdir testd
$CCACHE_COMPILE -o testd -c test1.c > /dev/null 2>&1
rm -rf testd
checkstat 'output to a non-regular file' 1
testname="no-input"
$CCACHE_COMPILE -c -O2 2> /dev/null
checkstat 'no input file' 1
testname="CCACHE_DISABLE"
CCACHE_DISABLE=1 $CCACHE_COMPILE -c test1.c 2> /dev/null
checkstat 'cache hit' 3
$CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 4
testname="CCACHE_CPP2"
CCACHE_CPP2=1 $CCACHE_COMPILE -c test1.c -O -O
checkstat 'cache hit' 4
checkstat 'cache miss' 3
CCACHE_CPP2=1 $CCACHE_COMPILE -c test1.c -O -O
checkstat 'cache hit' 5
checkstat 'cache miss' 3
testname="CCACHE_NOSTATS"
CCACHE_NOSTATS=1 $CCACHE_COMPILE -c test1.c -O -O
checkstat 'cache hit' 5
checkstat 'cache miss' 3
testname="CCACHE_RECACHE"
CCACHE_RECACHE=1 $CCACHE_COMPILE -c test1.c -O -O
checkstat 'cache hit' 5
checkstat 'cache miss' 4
# strictly speaking should be 6 - RECACHE causes a double counting!
checkstat 'files in cache' 8
$CCACHE -c > /dev/null
checkstat 'files in cache' 6
testname="CCACHE_HASHDIR"
CCACHE_HASHDIR=1 $CCACHE_COMPILE -c test1.c -O -O
checkstat 'cache hit' 5
checkstat 'cache miss' 5
CCACHE_HASHDIR=1 $CCACHE_COMPILE -c test1.c -O -O
checkstat 'cache hit' 6
checkstat 'cache miss' 5
checkstat 'files in cache' 8
testname="comments"
echo '/* a silly comment */' > test1-comment.c
cat test1.c >> test1-comment.c
$CCACHE_COMPILE -c test1-comment.c
rm -f test1-comment*
checkstat 'cache hit' 6
checkstat 'cache miss' 6
testname="CCACHE_UNIFY"
CCACHE_UNIFY=1 $CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 6
checkstat 'cache miss' 7
mv test1.c test1-saved.c
echo '/* another comment */' > test1.c
cat test1-saved.c >> test1.c
CCACHE_UNIFY=1 $CCACHE_COMPILE -c test1.c
mv test1-saved.c test1.c
checkstat 'cache hit' 7
checkstat 'cache miss' 7
testname="cache-size"
for f in *.c; do
$CCACHE_COMPILE -c $f
done
checkstat 'cache hit' 8
checkstat 'cache miss' 37
checkstat 'files in cache' 72
$CCACHE -F 48 -c > /dev/null
if [ `getstat 'files in cache'` -gt 48 ]; then
test_failed '-F test failed'
fi
testname="cpp call"
$CCACHE_COMPILE -c test1.c -E > test1.i
checkstat 'cache hit' 8
checkstat 'cache miss' 37
testname="direct .i compile"
$CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 8
checkstat 'cache miss' 38
$CCACHE_COMPILE -c test1.i
checkstat 'cache hit' 9
checkstat 'cache miss' 38
$CCACHE_COMPILE -c test1.i
checkstat 'cache hit' 10
checkstat 'cache miss' 38
# removed these tests as some compilers (including newer versions of gcc)
# determine which language to use based on .ii/.i extension, and C++ may
# not be installed
# testname="direct .ii file"
# mv test1.i test1.ii
# $CCACHE_COMPILE -c test1.ii
# checkstat 'cache hit' 10
# checkstat 'cache miss' 39
# $CCACHE_COMPILE -c test1.ii
# checkstat 'cache hit' 11
# checkstat 'cache miss' 39
testname="stripc" # This test might not be portable
CCACHE_STRIPC=1 $CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 10
checkstat 'cache miss' 39
CCACHE_STRIPC=1 $CCACHE_COMPILE -c test1.c
checkstat 'cache hit' 11
checkstat 'cache miss' 39
testname="zero-stats"
$CCACHE -z > /dev/null
checkstat 'cache hit' 0
checkstat 'cache miss' 0
testname="clear"
$CCACHE -C > /dev/null
checkstat 'files in cache' 0
rm -f test1.c
}
swigtests() {
echo "starting swig testsuite $testsuite"
rm -rf "$CCACHE_DIR"
checkstat 'cache hit' 0
checkstat 'cache miss' 0
j=1
rm -f *.i
genswigcode testswig1.i 1
testname="BASIC"
$CCACHE_COMPILE -java testswig1.i
checkstat 'cache hit' 0
checkstat 'cache miss' 1
checkstat 'files in cache' 6
testname="BASIC2"
$CCACHE_COMPILE -java testswig1.i
checkstat 'cache hit' 1
checkstat 'cache miss' 1
testname="output"
$CCACHE_COMPILE -java testswig1.i -o foo_wrap.c
checkstat 'cache hit' 1
checkstat 'cache miss' 2
testname="bad"
$CCACHE_COMPILE -java testswig1.i -I 2> /dev/null
checkstat 'bad compiler arguments' 1
testname="stdout"
$CCACHE_COMPILE -v -java testswig1.i > /dev/null
checkstat 'compiler produced stdout' 1
testname="non-regular"
mkdir testd
$CCACHE_COMPILE -o testd -java testswig1.i > /dev/null 2>&1
rm -rf testd
checkstat 'output to a non-regular file' 1
testname="no-input"
$CCACHE_COMPILE -java 2> /dev/null
checkstat 'no input file' 1
testname="CCACHE_DISABLE"
CCACHE_DISABLE=1 $CCACHE_COMPILE -java testswig1.i 2> /dev/null
checkstat 'cache hit' 1
$CCACHE_COMPILE -java testswig1.i
checkstat 'cache hit' 2
testname="CCACHE_CPP2"
CCACHE_CPP2=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 2
checkstat 'cache miss' 3
CCACHE_CPP2=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 3
checkstat 'cache miss' 3
testname="CCACHE_NOSTATS"
CCACHE_NOSTATS=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 3
checkstat 'cache miss' 3
testname="CCACHE_RECACHE"
CCACHE_RECACHE=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 3
checkstat 'cache miss' 4
# strictly speaking should be 3x6=18 instead of 4x6=24 - RECACHE causes a double counting!
checkstat 'files in cache' 24
$CCACHE -c > /dev/null
checkstat 'files in cache' 18
testname="CCACHE_HASHDIR"
CCACHE_HASHDIR=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 3
checkstat 'cache miss' 5
CCACHE_HASHDIR=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 4
checkstat 'cache miss' 5
checkstat 'files in cache' 24
testname="cpp call"
$CCACHE_COMPILE -java -E testswig1.i > testswig1-preproc.i
checkstat 'cache hit' 4
checkstat 'cache miss' 5
testname="direct .i compile"
$CCACHE_COMPILE -java testswig1.i
checkstat 'cache hit' 5
checkstat 'cache miss' 5
# No cache hit due to different input file name, -nopreprocess should not be given twice to SWIG
$CCACHE_COMPILE -java -nopreprocess testswig1-preproc.i
checkstat 'cache hit' 5
checkstat 'cache miss' 6
$CCACHE_COMPILE -java -nopreprocess testswig1-preproc.i
checkstat 'cache hit' 6
checkstat 'cache miss' 6
testname="stripc"
CCACHE_STRIPC=1 $CCACHE_COMPILE -java -O -O testswig1.i
checkstat 'cache hit' 7
checkstat 'cache miss' 6
CCACHE_STRIPC=1 $CCACHE_COMPILE -java -O -O -O testswig1.i
checkstat 'cache hit' 7
checkstat 'cache miss' 7
rm -f testswig1-preproc.i
rm -f testswig1.i
}
######
# main program
rm -rf $TESTDIR
mkdir $TESTDIR
if test -n "$CCACHE_PROG"; then
ln -s $CCACHE $TESTDIR/$CCACHE_PROG
CCACHE=./$CCACHE_PROG
fi
cd $TESTDIR || exit 1
unset CCACHE_DIR
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
testsuite="base"
CCACHE_COMPILE="$CCACHE $COMPILER"
basetests
CCACHE_COMPILE="$CCACHE $SWIG"
swigtests
if test -z "$NOSOFTLINKSTEST"; then
testsuite="link"
compilername=`basename $COMPILER`
ln -s $CCACHE ./$compilername
CCACHE_COMPILE="./$compilername"
basetests
rm "./$compilername"
compilername=`basename $SWIG`
ln -s $CCACHE ./$compilername
CCACHE_COMPILE="./$compilername"
swigtests
rm "./$compilername"
else
echo "skipping testsuite link"
fi
testsuite="hardlink"
CCACHE_COMPILE="env CCACHE_NOCOMPRESS=1 CCACHE_HARDLINK=1 $CCACHE $COMPILER"
basetests
CCACHE_COMPILE="env CCACHE_NOCOMPRESS=1 CCACHE_HARDLINK=1 $CCACHE $SWIG"
swigtests
testsuite="cpp2"
CCACHE_COMPILE="env CCACHE_CPP2=1 $CCACHE $COMPILER"
basetests
CCACHE_COMPILE="env CCACHE_CPP2=1 $CCACHE $SWIG"
swigtests
testsuite="nlevels4"
CCACHE_COMPILE="env CCACHE_NLEVELS=4 $CCACHE $COMPILER"
basetests
testsuite="nlevels1"
CCACHE_COMPILE="env CCACHE_NLEVELS=1 $CCACHE $COMPILER"
basetests
cd ..
rm -rf $TESTDIR
echo test done - OK
exit 0
SWIG1.3 Migration Guide
(The not entirely complete guide to updating language modules to work with SWIG1.3).
Dave Beazley
August 15, 2000
1. Introduction
---------------
Virtually all of SWIG's internal data structures have now been
rewritten. Take everything you thought you knew about SWIG1.1 and
throw it out.
2. DataTypes
------------
The old 'DataType' data structure is gone. Therefore, direct
manipulation of 'is_pointer', 'implicit_ptr', and 'arraystr'
attributes no longer applies. Sorry.
Datatypes are now represented by the type 'SwigType' which has no
public attributes. Actually, if you look at it closely, 'SwigType' is
really just an alias for 'void' and if you look at it even closer than
that you will realize that it's nothing more than a string!
The string encoding of types is described in more detail in the file
Source/Swig/stype.c and is not so important here. What is important is
the functions used to produce various types of output:
SwigType_str(type,name = 0);
This produces an exact C representation of the datatype with all
qualifiers, arrays, references, and so forth. name is an optional
name that is given if you wanted to associate the type with a
parameter name or something.
SwigType_lstr(type,name = 0);
This function takes a type and produces a C string containing
a type suitable for assignment (appearing as an lvalue in an
expression). To do this, certain things such as 'const',
arrays, and references are stripped away or converted into
pointers.
SwigType_ltype(type);
Returns a SwigType object corresponding to the type created
by SwigType_lstr().
SwigType_lcaststr(type,name);
Produces a string casting a value 'name' from the real datatype
to the assignable type created by SwigType_lstr().
SwigType_rcaststr(type,name)
Produces a string that casts a value 'name' from the type
created by SwigType_lstr() to the real datatype.
SwigType_manglestr(type)
Produces the 'mangled' version of a datatype.
Getting the 'type' code. Most language modules still operate by
looking at special integer type codes. This interface is a little
ragged and will probably go away at some point. However, for now the
following function can be used to get the type code:
int SwigType_type(type)
The codes are the same as the before, except that there are a few
special codes:
T_STRING - The 'char *' type and variations.
T_POINTER - Any pointer type (not char * though)
T_REFERENCE - Any C++ reference
T_ARRAY - Any array
T_FUNCTION - A function (this is usually an error).
Because of the special codes, it is no longer necessary to have code like this:
if ((t->is_pointer == 1) and (t->type == T_CHAR)) {
... get a string ...
}
Instead, just use the type code above like this:
switch(SwigType_type(type)) {
case T_STRING:
... get a string ...
break;
case T_POINTER:
... get a pointer ...
break;
}
There are about 2-dozen type manipulation functions that could also be useful.
See Source/Swig/swig.h and Source/Swig/stype.c.
3. Parameter Lists
------------------
The ParmList data structure is gone. In reality, parameter lists are nothing more than
a linked list of parameters. The proper way to iterate over this list and get
parameter values is as follows:
ParmList *l;
Parm *p;
for (p = l; p; p = Getnext(p)) {
SwigType *pt = Gettype(p); /* Get parameter type */
String *pn = Getname(p); /* Get parameter name */
String *value = Getvalue(p); /* Get parameter value */
...
do whatever
...
}
4. Typemaps
-----------
Typemaps more or less work. However, the interface has changed slightly. Instead of
typemap_lookup("in","python",type,pname,"$source","$target",wrapper);
the function is
Swig_typemap_lookup("in",type,pname,"$source","$target",wrapper);
There are a variety of other changes to typemaps (see CHANGES).
5. Use of new types
-------------------
When possible, language modules should try to use the built in String,
List, and Hash objects instead of C arrays or 'char *'. This will probably require a
detailed pass through the code with an eye towards cleanup.
6. Miscellaneous
----------------
Language modules no longer need to concern themselves with formatting the
wrapper code they produce (provided you are using the special Wrapper object).
The function Wrapper_print() passes everything through a pretty-printer that
automatically performs indentation and tries to clean things up. This especially
works well when there are lots of typemaps.
Project Plan
============
SWIG Code Comments
Google Summer of Code 2012
This document describes goals for the Google Summer of Code 2012,
SWIG code documentation project.
Author: Marko Klopcic, Dmitry Kabak
Introduction
============
The goal of this project is _not_ to translate _any_ possible Doxygen
formatted comment to JavaDoc or PyDoc, but to make it possible to
translate a subset of comment types in C/C++ code to
JavaDoc and PyDoc. Covering all the Doxygen functionality would be to
complex for the limited time. However, the code must be flexible so
that implementing missing features would not require redesign of the
comment handling code in SWIG.
There will also be a possibility to add untranslated comments to Java
and Python code (## comments, see Doxygen manual), if the user will
prefer to use Doxygen on the generated code.
Note:
'-OK-' tick below means that the item is implemented, committed and
working.
Abbreviations:
JD - JavaDoc
PD - PyDoc
Functionality
=============
Types of comments
-----------------
Note:
See 'http://www.stack.nl/~dimitri/doxygen/docblocks.html' for
the detailed description of Doxygen syntax and terms used in this
section.
1. -OK- Only JavaDoc (/** */) and Qt (/*! */) styles of comment blocks
will be supported by SWIG translator.
2. -OK- The following doc after members will be supported:
int var; ///< Detailed description after the member
//!<
int var; //!< Brief description after the member
int var; ///< Brief description after the member
3. -OK- Only comments before or after declaration/definition will be
supported. Comments with structural commands will be ignored
(warning will be written). (What about writing them to
'package.info.java' for JD?)
Tags
----
This section contains all doxygen tags taken from
http://www.stack.nl/~dimitri/doxygen/commands.html. If a tag is
marked as 'ignored', then the tag is ignored, but the text is copied
to the destination documentation. 'Not implemented' means that the
tag with it's contents is stripped out of the output.
Doxygen tags:
All tags: -OK-
\a - translated to <i></i> in JD, surrounded with _ in PD
\addindex - ignored
\addtogroup - ignored
\anchor - ignored, not supported by JD and PD
\arg - equivalent to \li
\attention - ignored
\authors, \author - translated to @author in JD, 'Author:' in PD
\b - <b></b> in JD, surrounded with __ in PD
\brief - ignored
\bug - ignored
\c - translated to <code></code> in JD, ignored in PD
\callgraph - ignored, not supported by JD and PD
\callergraph - ignored, not supported by JD and PD
\category - ignored, used only in Objective C
\cite - translated to <i></i> in JD, single quotes in PD
\class - ignored (structural command)
\code - translated to {@code ...} in JD, ignored in PD
\cond - translated to 'Conditional comment: <condition>'. Later
SWIG may support definitions of conditions in config file.
\copybrief - ignored. Later SWIG may support this command by
performing copy
\copydetails - ignored. Later SWIG may support this command by
performing copy
\copydoc - ignored. Later SWIG may support this command by
performing copy
\copyright - replaced with text 'Copyright' in PD and PD
\date - ignored
\def - ignored (structural command)
\defgroup - not supported
\deprecated - translated to @deprecated in JD, 'Deprecated:' in PD
\details - ignored
\dir - not supported
\dontinclude - not supported
\dot - not supported. Later SWIG may call dot and produce the graph image
to include in JD and PD
\dotfile - see note for \dot
\e - equivalent \a
\else - see note for \cond
\elseif - see note for \cond
\em - equivalent to \a
\endcode - see note for \code
\endcond - translated to 'End of conditional comment: <condition>'. Later
SWIG may support definitions of conditions in config file.
\enddot - see note for \dot
\endhtmlonly - ignored
\endif - see note for \cond
\endinternal - ignored
\endlatexonly - ignored
\endlink - see note for \link
\endmanonly - ignored
\endmsc - see note for \msc
\endrtfonly - ignored
\endverbatim - see note for \verbatim
\endxmlonly - ignored
\enum - ignored (structural command)
\example - translated to 'Example:' in JD and PD
\exception - equivalent to throws, but translates to @exception in JD
\extends - not supported
\f$ - ignored. Later swig may call LATeX to produce bitmaps with formulas
to include in JD and PD
\f[ - see note for \f$
\f] - see note for \f$
\f{ - see note for \f$
\f} - see note for \f$
\file - ignored (structural command)
\fn - ignored (structural command)
\headerfile - not supported
\hideinitializer - not supported
\htmlinclude - not supported
\htmlonly - ignored
\if - see note for \cond
\ifnot - see note for \cond
\image - translated to <img/> in JD only when target=HTML, translated to
'Image: filename(Title)'
\implements - not supported
\include - not supported
\includelineno - not supported
\ingroup - not supported. Later swig may print group names as plain text
in comments like 'Code group: something' in both JD and PD
\internal - ignored
\invariant - ignored
\interface - ignored (structural command)
\latexonly - ignored
\li - trabslated to <li></li> in JD, ignored in PD
\line - not supported
\link - translated to {@link ...} in JD, ignored in PD
\mainpage - ignored
\manonly - ignored
\memberof - not supported
\msc - not supported. Later SWIG may call dot and produce the graph image
to include in JD and PD
\mscfile - see note for \msc
\n - prints the new line
\name - ignored
\namespace - included in package-info.java if nspace feature is enabled,
otherwise ignored, ignored in PD
\nosubgrouping - ignored
\note - translated to 'Note:' in both JD and PD
\overload - prints 'This is an overloaded member function, provided for
convenience. It differs from the above function only in what
argument(s) it accepts.' to the output in both JD and PD
\p - equivalent to \c
\package - is kept same in JD (it is already a JD tag), ignored in PD
\page - ignored
\par - translated to <p alt='title'></p> in JD, 'Title: ...' in PD
\paragraph - ignored
\param - translated to @param in JD, special formatting in PD
\post - ignored
\pre - ignored
\private - ignored
\privatesection - ignored
\property - ignored
\protected - ignored
\protectedsection - ignored
\protocol - ignored (Objective-C tag)
\public - ignored
\publicsection - ignored
\ref - ignored, not supported by JD and PD
\related - ignored
\relates - ignored
\relatedalso - ignored
\relatesalso - ignored
\remark - translated to 'Remarks:' in both JD and PD
\remarks - equivalent to remark
\result - translated to @return in JD, 'Return:' in PD
\return - equivalent to result
\returns - equivalent to result
\retval - ignored
\rtfonly - ignored
\sa - translated to @see in JD, 'See also:' in PD
\section - not supported
\see - equivalent to \sa
\short - equivalent to \brief
\showinitializer - not supported
\since - translated to @since in JD, 'Since:' in PD
\skip - not supported
\skipline - not supported
\snippet - not supported
\struct - ignored (structural command)
\subpage - not supported
\subsection - not supported
\subsubsection - not supported
\tableofcontents - not supported
\test - ignored
\throw - translated to @throws in JD, 'Throws:' in PD
\throws - equivalent to \throw
\todo - translated to 'TODO:' in both JD and PD
\tparam - similar to \arg
\typedef - ignored (structural command)
\union - ignored (structural command)
\until - not supported
\var - ignored (structural command)
\verbatim - translated to {@literal ...} in JD, ignored in PD
\verbinclude - ignored
\version - translated to @version in JD, 'Version:' in PD
\warning - translated to 'Warning:' in both JD and PD
\weakgroup - not supported
\xmlonly - ignored
\xrefitem - ignored
\$ - this and all the others below: these commands insert single char,
it is escaped as HTML char in JD, kept as-is in PD
\@
\\
\&
\~
\<
\>
\#
\%
\"
\.
\::
Optional functionality
======================
That section describes some complex cases where the current code
does not behave really well. Like a short to-do list of special cases.
-OK- When translating functions with default parameters in swig to
java, it creates overloaded functions with all the parameters
except the default ones. We need to copy the doxygen comment to
such functions and correct the list of @param tags.
-OK- In doxygen there is a special tags (and even a special option)
to create links to some code members from the current comment.
Sometimes it needs a type of parameters specified because of the
overloaded functions. And the same linking tags are supported in JD,
but it has a completely different typesystem, so we need to translate
the types of function parameters in comments also. For example:
{@link MyClass#doSomething(const std::string &)}
does not make sense in Java, so the type should be converted.
{@link MyClass#doSomething(String)}
Tests
=====
The following test cases will be implemented:
-OK- Class comments.
-OK- Struct comments.
-OK- Enum comments.
-OK- Function comments.
-OK- Var comments.
-OK- Class attributes, comment before and after declaration.
-OK- Class methods, comment of parameters in function
comment.
-OK- Class methods, comment of parameters
after parameter declaration.
-OK- Struct attributes, comment before and after declaration.
-OK- Struct methods, comment of parameters in function
comment.
-OK- Struct methods, comment of parameters
after parameter declaration.
-OK- Enum items JD and Qt style, comment before items
-OK- Enum items JD and Qt style, comment after items
-OK- Class comment, with all supported tags.
-OK- Class comment, with all doxygen tags, including
ignored ones.
The list of all tests, in form of shell commands to make it simple
to test project by copying the text below into terminal program.
make doxygen_parsing.cpptest -s
make doxygen_translate.cpptest -s
make doxygen_translate_all_tags.cpptest -s
make doxygen_basic_translate.cpptest -s
make doxygen_basic_notranslate.cpptest -s
make doxygen_translate_links.cpptest -s
make doxygen_tricky_constructs.cpptest -s
Refactoring
===========
All the code in directory _Doxygen_ should be refactored:
-OK- all methods should be class members
-OK- most static methods should be normal members
-OK- replace C arrays of strings and sequential searches with STL data
structures and algorithms.
-OK- use singletons instead of class instantiaion for each comment found.
Documentation
=============
SWIG documentation will contain:
-OK- command line options
-OK- list of implemented features (types and placements of comments)
-OK- list of unimplemented features (types and placements of comments)
-OK- list of tags and their translations (all Doxygen tags).
-OK- some amount of debugging and development information
This file describes the necessary functions and interfaces a language module
needs to implement to take advantage of the run time type system. I assume you
have read the run-time section of the Typemaps chapter in the SWIG
documentation.
Last updated: February 23, 2005
The file we are concerned with here should be named langrun.swg. A good example
of a simple file is the Lib/mzscheme/mzrun.swg file. First, a few requirements
and notes:
1) Every function in this file should be declared static.
2) It should be inserted into the runtime section of the _wrap file from your
config file. The Lib/swigrun.swg file should be included before this file.
That is, you need to have
%runtime "swigrun.swg"
%runtime "langrun.swg"
3) You must also include the swiginit.swg file in the init section of the
wrapper. That is, you should have
%insert(init) "swiginit.swg"
4) From module.cxx, you need to call the SwigType_emit_type_table function, as
well as register types with SwigType_remember or SwigType_remember_clientdata
5) By convention, all functions in this file are of the form
SWIG_Language_Whatever, and #defines are used to rename SWIG API functions to
these function names
6) You need to call void SWIG_InitializeModule(void *clientdata) from your init
function.
7) You need to implement the runtimeCode() and defaultExternalRuntimeFilename()
functions inside module.cxx. runtimeCode should return all the language
specific runtime code as a string, and defaultExternalRuntimeFilename should
return a string for the default name of the external runtime header. This is
usually "swigpyrun.h", where "py" is replaced by the language name. These
two functions are used by the -external-runtime argument.
-------------------------------------------------------------------------------
Required Functions
-------------------------------------------------------------------------------
swig_module_info *SWIG_GetModule(void *clientdata);
void SWIG_SetModule(void *clientdata, swig_module_info *mod);
The SetModule function should store the mod argument into some globally
accessible variable in the target language. The action of these two functions
is to provide a way for multiple modules to share information. The SetModule
function should create a new global var named something like
"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME
SWIG_RUNTIME_VERSION is currently defined as "2", and SWIG_TYPE_TABLE_NAME is
defined by the -DSWIG_TYPE_TABLE=mytable option when compiling the wrapper.
Alternatively, if the language supports modules, a module named
"swig_runtime_data" SWIG_RUNTIME_VERSION can be created, and a global variable
named "type_table" SWIG_TYPE_TABLE_NAME can be created inside it. The most
common approach is to store the mod pointer in some global variable in the
target language, but if the language provides an alternative place to store data
then that is good too.
The way the code is set up, SetModule should only be called when GetModule
returns NULL, and if SetModule is called a second time, the behavior is
undefined. Just make sure it doesn't crash in the random chance occurrence that
SetModule is called twice.
There are two options here.
1) The preferred approach is for GetModule and SetModule to not require a
clientdata pointer. If you can at all avoid it, please do so. Here, you would
write swig_module_info *SWIG_Language_GetModule();
void SWIG_Language_SetModule(swig_module_info *mod);
and then add
#define SWIG_GetModule(clientdata) SWIG_Language_GetModule()
#define SWIG_SetModule(cd, ptr) SWIG_Language_SetModule(ptr)
You would then call
SWIG_InitializeModule(0)
2) If GetModule and SetModule need to take a custom pointer (most notably an
environment pointer, see tcl or mzscheme), then you should write
swig_module_info *SWIG_Language_GetModule(void *clientdata)
void SWIG_Language_SetModule(void *clientdata, swig_module_info *mod);
and also define
#define SWIG_GetModule(cd) SWIG_Language_GetModule(cd)
#define SWIG_SetModule(cd, ptr) SWIG_Language_SetModule(cd, ptr)
#define SWIG_MODULE_CLIENTDATA_TYPE Whatever
SWIG_MODULE_CLIENTDATA_TYPE should be defined to whatever the type of
clientdata is.
You would then call SWIG_InitializeModule(clientdata), and clientdata would get
passed to GetModule and SetModule. clientdata will not be stored and will only
be referenced during the InitializeModule call. After InitializeModule returns,
clientdata does not need to be valid any more.
This method is not preferred, because it makes external access to the type
system more complicated. See the Modules chapter of the documentation, and read
the "External access to the run-time" section. Then take a look at
Lib/runtime.swg. Anybody that calls SWIG_TypeQuery needs to pass along the
clientdata pointer, and that is the reason for defining
SWIG_MODULE_CLIENTDATA_TYPE.
-------------------------------------------------------------------------------
Standard Functions
-------------------------------------------------------------------------------
These functions are not required and their API is not formalized, but almost all
language modules implement them for consistency across languages. Throughout
this discussion, I will use LangType to represent the underlying language type
(Scheme_Object * in mzscheme, PyObject * in python, etc)
LangObj SWIG_NewPointerObj(void *ptr, swig_type_info *type, int flags);
Create and return a new pointer object that has both ptr and type. For almost
all language modules, flags is used for ownership. If flags==1, then the
created pointer should be registered to be garbage collected.
int SWIG_ConvertPtr(LangType obj, void **result, swig_type_info *type, int flags);
Convert a language wrapped pointer into a void *. The pointer is returned in
result, and the function should return 0 on success, non-zero on error.
A sample ConvertPtr is given here:
swig_cast_info *cast;
if (<obj is a wrapped pointer type>) {
cast = SWIG_TypeCheck(<obj type name>, type);
cast = SWIG_TypeCheckStruct(<obj type structure>, type);
if (cast) {
*result = SWIG_TypeCast(cast, <obj pointer>);
return 0;
}
}
return 1;
Either TypeCheck or TypeCheckStruct can be called, depending on how the pointer
is wrapped in langtype. If obj stores the void pointer and the type name, then
the TypeCheck function should be used, while if obj stores the void pointer and
a pointer to the swig_type_info structure, then the TypeCheckStruct function
should be called. The TypeCheckStruct is slightly faster, since it does a
pointer comparison instead of a strcmp.
The flag argument to ConvertPtr is used in some languages for disowning a
pointer. If the wrapped C function is taking ownership of the pointer (that
means, the wrapped C function is responsible for deleting the object), then that
pointer should be removed from the garbage collector. We do that in the
ConvertPtr function. The pointer is still valid in the target language, but
when the target language type is garbage collected, it will not call the
associated destructor. Languages have a special typemap called DISOWN that can be
applied which passes this argument. All the languages have the flags argument
for consistency, and the flags argument can be ignored or used for some other
purpose.
void *SWIG_MustGetPtr(LangType obj, swig_type_info *type, int flags,
int argnum, const char *func_name) {
void *result;
if (SWIG_ConvertPtr(s, &result, type, flags)) {
generate runtime type error ("Error in func_name, expected a" +
type->str ? type->str : "void *" +
"at argument number" + argnum);
}
return result;
}
This function is optional, and the number and type of parameters can be
different, but is useful for typemap purposes:
%typemap(in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
$1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, 0, $argnum, FUNC_NAME);
}
#!/usr/bin/python
# Replace the inline htmldoc stylesheet with the SWIG stylesheet
import sys
import string
filename = sys.argv[1]
data = open(filename).read()
open(filename+".bak","w").write(data)
swigstyle = "\n" + open("style.css").read()
lines = data.splitlines()
result = [ ]
skip = False
for s in lines:
if not skip:
result.append(s)
if s == "<STYLE TYPE=\"text/css\"><!--":
result.append(swigstyle)
skip = True
elif s == "--></STYLE>":
result.append(s)
skip = False
data = "\n".join(result)
open(filename,"w").write(data)
[filtering]
ignorewarnings=http-robots-denied
ignorewarnings=https-certificate-error
#!/usr/bin/env python
###############################################################################
# Takes a chapter as input and adds internal links and numbering to all
# of the H1, H2, H3, H4 and H5 sections.
#
# Every heading HTML tag (H1, H2 etc) is given an autogenerated name to link
# to. However, if the name is not an autogenerated name from a previous run,
# it will be kept. If it is autogenerated, it might change on subsequent runs
# of this program. Thus if you want to create links to one of the headings,
# then change the heading link name to something that does not look like an
# autogenerated link name.
###############################################################################
import sys
import re
import string
###############################################################################
# Functions
###############################################################################
# Regexs for <a name="..."></a>
alink = re.compile(r"<a *name *= *\"(.*)\">.*</a>", re.IGNORECASE)
heading = re.compile(r"(_nn\d)", re.IGNORECASE)
def getheadingname(m):
autogeneratedheading = True;
if m.group(1) != None:
amatch = alink.match(m.group(1))
if amatch:
# A non-autogenerated heading - keep it
headingname = amatch.group(1)
autogeneratedheading = heading.match(headingname)
if autogeneratedheading:
# The heading name was either non-existent or autogenerated,
# We can create a new heading / change the existing heading
headingname = "%s_nn%d" % (filenamebase, nameindex)
return headingname
# Return heading - 1.1. Introduction in the examples below:
# old style example: <H2><a name="Preface_nn2"></a>1.1 Introduction</H2>
# new style example: <H2><a name="Preface_nn2">1.1 Introduction</a></H2>
def getheadingtext(m, s):
prevheadingtext_newstyle = m.group(2)
prevheadingtext_oldstyle = m.group(3)
if prevheadingtext_oldstyle is None or prevheadingtext_newstyle is None:
raise RuntimeError("Ill-formed heading in line:\n%s" % s)
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
###############################################################################
if len(sys.argv) != 3:
print "usage: makechap.py filename num"
sys.exit(1)
filename = sys.argv[1]
filenamebase = string.split(filename,".")[0]
num = int(sys.argv[2])
section = 0
subsection = 0
subsubsection = 0
nameindex = 0
name = ""
# Regexs for <h1>,... <h5> sections
h1 = re.compile(r".*?<H1>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H1>", re.IGNORECASE)
h2 = re.compile(r".*?<H2>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H2>", re.IGNORECASE)
h3 = re.compile(r".*?<H3>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H3>", re.IGNORECASE)
h4 = re.compile(r".*?<H4>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H4>", re.IGNORECASE)
h5 = re.compile(r".*?<H5>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H5>", re.IGNORECASE)
data = open(filename).read() # Read data
open(filename+".bak","w").write(data) # Make backup
lines = data.splitlines()
result = [ ] # This is the result of postprocessing the file
index = "<!-- INDEX -->\n<div class=\"sectiontoc\">\n" # index contains the index for adding at the top of the file. Also printed to stdout.
skip = 0
skipspace = 0
for s in lines:
if s == "<!-- INDEX -->":
if not skip:
skip = 1
else:
skip = 0
continue;
if skip:
continue
if not s and skipspace:
continue
if skipspace:
result.append("")
result.append("")
skipspace = 0
m = h1.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
headingname = getheadingname(m)
result.append("""<H1><a name="%s">%d %s</a></H1>""" % (headingname,num,prevheadingtext))
result.append("@INDEX@")
section = 0
subsection = 0
subsubsection = 0
subsubsubsection = 0
name = prevheadingtext
skipspace = 1
continue
m = h2.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
section += 1
headingname = getheadingname(m)
result.append("""<H2><a name="%s">%d.%d %s</a></H2>""" % (headingname,num,section, prevheadingtext))
if subsubsubsection:
index += "</ul>\n"
if subsubsection:
index += "</ul>\n"
if subsection:
index += "</ul>\n"
if section == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
subsection = 0
subsubsection = 0
subsubsubsection = 0
skipspace = 1
continue
m = h3.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
subsection += 1
headingname = getheadingname(m)
result.append("""<H3><a name="%s">%d.%d.%d %s</a></H3>""" % (headingname,num,section, subsection, prevheadingtext))
if subsubsubsection:
index += "</ul>\n"
if subsubsection:
index += "</ul>\n"
if subsection == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
subsubsection = 0
skipspace = 1
continue
m = h4.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
subsubsection += 1
headingname = getheadingname(m)
result.append("""<H4><a name="%s">%d.%d.%d.%d %s</a></H4>""" % (headingname,num,section, subsection, subsubsection, prevheadingtext))
if subsubsubsection:
index += "</ul>\n"
if subsubsection == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
subsubsubsection = 0
skipspace = 1
continue
m = h5.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
subsubsubsection += 1
headingname = getheadingname(m)
result.append("""<H5><a name="%s">%d.%d.%d.%d.%d %s</a></H5>""" % (headingname,num,section, subsection, subsubsection, subsubsubsection, prevheadingtext))
if subsubsubsection == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
skipspace = 1
continue
result.append(s)
if subsubsubsection:
index += "</ul>\n"
if subsubsection:
index += "</ul>\n"
if subsection:
index += "</ul>\n"
if section:
index += "</ul>\n"
index += "</div>\n<!-- INDEX -->\n"
data = "\n".join(result)
data = data.replace("@INDEX@",index) + "\n";
# Write the file back out
open(filename,"w").write(data)
# Print the TOC data to stdout correcting the anchor links for external referencing
index = index.replace("<li><a href=\"#","<li><a href=\"%s#" % filename)
print """<h3><a href="%s#%s">%d %s</a></h3>\n""" % (filename,filenamebase,num,name)
print index
#!/usr/bin/env python
import sys
import os
chs = open("chapters").readlines()
f = open("Contents.html","w")
print >>f, """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>SWIG Users Manual</TITLE>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</HEAD>
<BODY BGCOLOR="#ffffff">
<H1><a name="Contents"></a>SWIG Users Manual</H1>
<p>
"""
f.close()
num = 1
for c in chs:
c = c.strip()
print "Processing %s" % c
if c:
os.system("python makechap.py %s %d >> Contents.html" % (c,num))
num += 1
f = open("Contents.html","a")
print >>f, """
</BODY>
</HTML>
"""
md5: B5024AB027D593844D12631322AA1580 | sha1: AF48476F2545DE1A5F2CE8C1591BD1517CE5A9F7 | sha256: C2622FE6BC41FFE05C0A162FA583E3E44F03DCA6510384C4A022DBAEAC33FF06 | sha512: 710B12A33F5D8E23A3FBB2D74F2F322004EEE41BEB9C556FF29272F8C88ACF0A3E5D9CB38A3AB33F767D758B9159227EE2308908BA0563B609947306B9EA3843
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.swig.classexample"
android:versionCode="1"
android:versionName="1.0">
<application android:label="@string/app_name" >
<activity android:name="SwigClass"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="UTF-8"?>
<project name="SwigClass" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<loadproperties srcFile="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project'"
unless="sdk.dir"
/>
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!--
<target name="-pre-build">
</target>
<target name="-pre-compile">
</target>
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */
<target name="-post-compile">
</target>
-->
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/>
<ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SwigClass</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.swig.extendexample"
android:versionCode="1"
android:versionName="1.0">
<application android:label="@string/app_name" >
<activity android:name="SwigExtend"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="UTF-8"?>
<project name="SwigExtend" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<loadproperties srcFile="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project'"
unless="sdk.dir"
/>
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!--
<target name="-pre-build">
</target>
<target name="-pre-compile">
</target>
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */
<target name="-post-compile">
</target>
-->
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/>
<ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SwigExtend</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.swig.simple"
android:versionCode="1"
android:versionName="1.0">
<application android:label="@string/app_name" >
<activity android:name="SwigSimple"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="UTF-8"?>
<project name="SwigSimple" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<loadproperties srcFile="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project'"
unless="sdk.dir"
/>
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!--
<target name="-pre-build">
</target>
<target name="-pre-compile">
</target>
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */
<target name="-post-compile">
</target>
-->
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/>
<ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SwigSimple</string>
</resources>
import example
# Call the Circle() function correctly
x = 1;
y = 1;
r = 3;
c = example.Circle(x, y, r)
# test post-assertion
x = 1;
y = 1;
r = 2;
c = example.Circle(x, y, r)
print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c)
import example
# Call the Circle() function correctly
x = 1;
y = 1;
r = 3;
c = example.Circle(x, y, r)
print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c)
# test pre-assertion
x = 1;
y = -1;
r = 3;
c = example.Circle(x, y, r)
print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c)
import example
# Create the Circle object
r = 2;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
# Set the location of the object
c.x = 20
c.y = 30
print " Here is its current position:"
print " Circle = (%f, %f)" % (c.x,c.y)
# ----- Call some methods -----
print "\n Here are some properties of the Circle:"
print " area = ", c.area()
print " perimeter = ", c.perimeter()
dx = 1;
dy = 1;
print " Moving with (%d, %d)..." % (dx, dy)
c.move(dx, dy)
del c
print "==================================="
# test construction */
r = -1;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
import example
# Create the Circle object
r = 2;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
# Set the location of the object
c.x = 20
c.y = 30
print " Here is its current position:"
print " Circle = (%f, %f)" % (c.x,c.y)
# ----- Call some methods -----
print "\n Here are some properties of the Circle:"
print " area = ", c.area()
print " perimeter = ", c.perimeter()
dx = 1;
dy = 1;
print " Moving with (%d, %d)..." % (dx, dy)
c.move(dx, dy)
del c
print "==================================="
# test area function */
r = 1;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
# Set the location of the object
c.x = 20
c.y = 30
print " Here is its current position:"
print " Circle = (%f, %f)" % (c.x,c.y)
# ----- Call some methods -----
print "\n Here are some properties of the Circle:"
print " area = ", c.area()
import example
# Create the Circle object
r = 2;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
# Set the location of the object
c.x = 20
c.y = 30
print " Here is its current position:"
print " Circle = (%f, %f)" % (c.x,c.y)
# ----- Call some methods -----
print "\n Here are some properties of the Circle:"
print " area = ", c.area()
print " perimeter = ", c.perimeter()
dx = 1;
dy = 1;
print " Moving with (%d, %d)..." % (dx, dy)
c.move(dx, dy)
del c
print "==================================="
# test move function */
r = 2;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
# Set the location of the object
c.x = 20
c.y = 30
print " Here is its current position:"
print " Circle = (%f, %f)" % (c.x,c.y)
# ----- Call some methods -----
print "\n Here are some properties of the Circle:"
print " area = ", c.area()
print " perimeter = ", c.perimeter()
# no error for Circle's pre-assertion
dx = 1;
dy = -1;
print " Moving with (%d, %d)..." % (dx, dy)
c.move(dx, dy)
# error with Shape's pre-assertion
dx = -1;
dy = 1;
print " Moving with (%d, %d)..." % (dx, dy)
c.move(dx, dy)
using System;
public class runme
{
static void Main()
{
int[] source = { 1, 2, 3 };
int[] target = new int[ source.Length ];
example.myArrayCopy( source, target, target.Length );
Console.WriteLine( "Contents of copy target array using default marshaling" );
PrintArray( target );
target = new int[ source.Length ];
example.myArrayCopyUsingFixedArrays( source, target, target.Length );
Console.WriteLine( "Contents of copy target array using fixed arrays" );
PrintArray( target );
target = new int[] { 4, 5, 6 };
example.myArraySwap( source, target, target.Length );
Console.WriteLine( "Contents of arrays after swapping using default marshaling" );
PrintArray( source );
PrintArray( target );
source = new int[] { 1, 2, 3 };
target = new int[] { 4, 5, 6 };
example.myArraySwapUsingFixedArrays( source, target, target.Length );
Console.WriteLine( "Contents of arrays after swapping using fixed arrays" );
PrintArray( source );
PrintArray( target );
}
static void PrintArray( int[] a )
{
foreach ( int i in a )
Console.Write( "{0} ", i );
Console.WriteLine();
}
}
using System;
public class runme
{
static void Main()
{
Console.WriteLine("Adding and calling a normal C++ callback");
Console.WriteLine("----------------------------------------");
Caller caller = new Caller();
using (Callback callback = new Callback())
{
caller.setCallback(callback);
caller.call();
caller.resetCallback();
}
Console.WriteLine();
Console.WriteLine("Adding and calling a C# callback");
Console.WriteLine("------------------------------------");
using (Callback callback = new CSharpCallback())
{
caller.setCallback(callback);
caller.call();
caller.resetCallback();
}
Console.WriteLine();
Console.WriteLine("C# exit");
}
}
public class CSharpCallback : Callback
{
public CSharpCallback()
: base()
{
}
public override void run()
{
Console.WriteLine("CSharpCallback.run()");
}
}
// This example illustrates how C++ classes can be used from C# using SWIG.
// The C# class gets mapped onto the C++ class and behaves as if it is a C# class.
using System;
public class runme
{
static void Main()
{
// ----- Object creation -----
Console.WriteLine( "Creating some objects:" );
using (Square s = new Square(10))
using (Circle c = new Circle(10))
{
Console.WriteLine( " Created circle " + c );
Console.WriteLine( " Created square " + s );
// ----- Access a static member -----
Console.WriteLine( "\nA total of " + Shape.nshapes + " shapes were created" );
// ----- Member data access -----
// Notice how we can do this using functions specific to
// the 'Circle' class.
c.x = 20;
c.y = 30;
// Now use the same functions in the base class
Shape shape = s;
shape.x = -10;
shape.y = 5;
Console.WriteLine( "\nHere is their current position:" );
Console.WriteLine( " Circle = (" + c.x + " " + c.y + ")" );
Console.WriteLine( " Square = (" + s.x + " " + s.y + ")" );
// ----- Call some methods -----
Console.WriteLine( "\nHere are some properties of the shapes:" );
Shape[] shapes = {c,s};
// for (int i=0; i<shapes.Size; i++)
for (int i=0; i<2; i++)
{
Console.WriteLine( " " + shapes[i].ToString() );
Console.WriteLine( " area = " + shapes[i].area() );
Console.WriteLine( " perimeter = " + shapes[i].perimeter() );
}
// Notice how the area() and perimeter() functions really
// invoke the appropriate virtual method on each object.
// ----- Delete everything -----
Console.WriteLine( "\nGuess I'll clean up now" );
}
// Note: when this using scope is exited the C# Dispose() methods
// are called which in turn call the C++ destructors
Console.WriteLine( Shape.nshapes + " shapes remain" );
Console.WriteLine( "Goodbye" );
}
}
using System;
public class runme
{
static void Main()
{
// Print out the value of some enums
Console.WriteLine("*** color ***");
Console.WriteLine(" " + color.RED + " = " + (int)color.RED);
Console.WriteLine(" " + color.BLUE + " = " + (int)color.BLUE);
Console.WriteLine(" " + color.GREEN + " = " + (int)color.GREEN);
Console.WriteLine("\n*** Foo::speed ***");
Console.WriteLine(" Foo::" + Foo.speed.IMPULSE + " = " + (int)Foo.speed.IMPULSE);
Console.WriteLine(" Foo::" + Foo.speed.WARP + " = " + (int)Foo.speed.WARP);
Console.WriteLine(" Foo::" + Foo.speed.LUDICROUS + " = " + (int)Foo.speed.LUDICROUS);
Console.WriteLine("\nTesting use of enums with functions\n");
example.enum_test(color.RED, Foo.speed.IMPULSE);
example.enum_test(color.BLUE, Foo.speed.WARP);
example.enum_test(color.GREEN, Foo.speed.LUDICROUS);
Console.WriteLine( "\nTesting use of enum with class method" );
Foo f = new Foo();
f.enum_test(Foo.speed.IMPULSE);
f.enum_test(Foo.speed.WARP);
f.enum_test(Foo.speed.LUDICROUS);
}
}
// This file illustrates the cross language polymorphism using directors.
using System;
// CEO class, which overrides Employee::getPosition().
class CEO : Manager {
public CEO(String name) : base(name) {
}
public override String getPosition() {
return "CEO";
}
// Public method to stop the SWIG proxy base class from thinking it owns the underlying C++ memory.
public void disownMemory() {
swigCMemOwn = false;
}
}
public class runme
{
static void Main()
{
// Create an instance of CEO, a class derived from the C# proxy of the
// underlying C++ class. The calls to getName() and getPosition() are standard,
// the call to getTitle() uses the director wrappers to call CEO.getPosition().
CEO e = new CEO("Alice");
Console.WriteLine( e.getName() + " is a " + e.getPosition() );
Console.WriteLine( "Just call her \"" + e.getTitle() + "\"" );
Console.WriteLine( "----------------------" );
// Create a new EmployeeList instance. This class does not have a C++
// director wrapper, but can be used freely with other classes that do.
using (EmployeeList list = new EmployeeList()) {
// EmployeeList owns its items, so we must surrender ownership of objects we add.
e.disownMemory();
list.addEmployee(e);
Console.WriteLine( "----------------------" );
// 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, all methods resolve in C++. For item 3, our CEO, getTitle calls
// getPosition which resolves in C#. The call to getPosition is
// 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, C# resolved the call
// immediately in CEO, but now C# thinks the object is an instance of
// class Employee. So the call passes through the
// Employee proxy class and on to the C wrappers and C++ director,
// eventually ending up back at the C# 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 C# implementation
// in CEO. All this routing takes place transparently.
Console.WriteLine( "(position, title) for items 0-3:" );
Console.WriteLine( " " + list.get_item(0).getPosition() + ", \"" + list.get_item(0).getTitle() + "\"" );
Console.WriteLine( " " + list.get_item(1).getPosition() + ", \"" + list.get_item(1).getTitle() + "\"" );
Console.WriteLine( " " + list.get_item(2).getPosition() + ", \"" + list.get_item(2).getTitle() + "\"" );
Console.WriteLine( " " + list.get_item(3).getPosition() + ", \"" + list.get_item(3).getTitle() + "\"" );
Console.WriteLine( "----------------------" );
// The using statement ensures the EmployeeList.Dispose() will be called, which will delete all the Employee*
// items it contains. The last item is our CEO, which gets destroyed as well.
}
Console.WriteLine( "----------------------" );
// All done.
Console.WriteLine( "C# exit" );
}
}
using System;
using System.Reflection;
public class runme {
public static void Main(String[] args) {
int a = 37;
int b = 42;
// Now call our C function with a bunch of callbacks
Console.WriteLine( "Trying some C callback functions" );
Console.WriteLine( " a = " + a );
Console.WriteLine( " b = " + b );
Console.WriteLine( " ADD(a,b) = " + example.do_op(a,b,example.ADD) );
Console.WriteLine( " SUB(a,b) = " + example.do_op(a,b,example.SUB) );
Console.WriteLine( " MUL(a,b) = " + example.do_op(a,b,example.MUL) );
Console.WriteLine( "Here is what the C callback function classes are called in C#" );
Console.WriteLine( " ADD = " + example.ADD.GetType() );
Console.WriteLine( " SUB = " + example.SUB.GetType() );
Console.WriteLine( " MUL = " + example.MUL.GetType() );
}
}
// This example illustrates how C++ classes can be used from C# using SWIG.
// The C# class gets mapped onto the C++ class and behaves as if it is a C# class.
using System;
public class runme
{
static void Main()
{
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));
Console.WriteLine("Expert opinion on " + car1.Name() + " : \n " + car1.WillItWork());
Console.WriteLine("Expert opinion on " + car2.Name() + " : \n " + car2.WillItWork());
Console.WriteLine("Expert opinion on " + car3.Name() + " : \n " + car3.WillItWork());
Console.WriteLine("Expert opinion on " + car4.Name() + " : \n " + car4.WillItWork());
int count = MotorCar.DesignOpinion.AceDesignCount;
int total = MotorCar.DesignOpinion.TotalDesignCount;
int percent = MotorCar.DesignOpinion.PercentScore();
Console.WriteLine("Overall opinion rating on car design is " + count + "/" + total + " = " + percent + "%");
Console.WriteLine("Single square wheel thoughts: " + new MotorCar.Wheels(MotorCar.Wheels.Shape.Square, 1).Opinion().reason);
}
}
// This example illustrates the manipulation of C++ references in C#.
using System;
public class runme {
public static void Main()
{
Console.WriteLine( "Creating some objects:" );
Vector a = new Vector(3,4,5);
Vector b = new Vector(10,11,12);
Console.WriteLine( " Created " + a.print() );
Console.WriteLine( " Created " + b.print() );
// ----- Call an overloaded operator -----
// This calls the wrapper we placed around
//
// operator+(const Vector &a, const Vector &)
//
// It returns a new allocated object.
Console.WriteLine( "Adding a+b" );
Vector c = example.addv(a,b);
Console.WriteLine( " a+b = " + c.print() );
// Note: Unless we free the result, a memory leak will occur if the -noproxy commandline
// is used as the proxy classes define finalizers which call the Dispose() method. When
// -noproxy is not specified the memory management is controlled by the garbage collector.
// You can still call Dispose(). It will free the c++ memory immediately, but not the
// C# memory! You then must be careful not to call any member functions as it will
// use a NULL c pointer on the underlying c++ object. We set the C# object to null
// which will then throw a C# exception should we attempt to use it again.
c.Dispose();
c = null;
// ----- Create a vector array -----
Console.WriteLine( "Creating an array of vectors" );
VectorArray va = new VectorArray(10);
Console.WriteLine( " va = " + va.ToString() );
// ----- Set some values in the array -----
// These operators copy the value of Vector a and Vector b to the vector array
va.set(0,a);
va.set(1,b);
// This works, but it would cause a memory leak if -noproxy was used!
va.set(2,example.addv(a,b));
// Get some values from the array
Console.WriteLine( "Getting some array values" );
for (int i=0; i<5; i++)
Console.WriteLine( " va(" + i + ") = " + va.get(i).print() );
// Watch under resource meter to check on this
Console.WriteLine( "Making sure we don't leak memory." );
for (int i=0; i<1000000; i++)
c = va.get(i%10);
// ----- Clean up -----
// This could be omitted. The garbage collector would then clean up for us.
Console.WriteLine( "Cleaning up" );
va.Dispose();
a.Dispose();
b.Dispose();
}
}
using System;
public class runme
{
static void Main()
{
// Call our gcd() function
int x = 42;
int y = 105;
int g = example.gcd(x,y);
Console.WriteLine("The gcd of " + x + " and " + y + " is " + g);
// Manipulate the Foo global variable
// Output its current value
Console.WriteLine("Foo = " + example.Foo);
// Change its value
example.Foo = 3.1415926;
// See if the change took effect
Console.WriteLine("Foo = " + example.Foo);
}
}
// This example illustrates how C++ templates can be used from C#.
using System;
public class runme {
public static void Main()
{
// Call some templated functions
Console.WriteLine(example.maxint(3,7));
Console.WriteLine(example.maxdouble(3.14,2.18));
// Create some class
vecint iv = new vecint(100);
vecdouble dv = new vecdouble(1000);
for (int i=0; i<100; i++)
iv.setitem(i,2*i);
for (int i=0; i<1000; i++)
dv.setitem(i, 1.0/(i+1));
{
int sum = 0;
for (int i=0; i<100; i++)
sum = sum + iv.getitem(i);
Console.WriteLine(sum);
}
{
double sum = 0.0;
for (int i=0; i<1000; i++)
sum = sum + dv.getitem(i);
Console.WriteLine(sum);
}
}
}
// This example illustrates global variable access from C#.
using System;
using System.Reflection;
public class runme {
public static void Main() {
// 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 = (float)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 print out the values of the variables
Console.WriteLine( "Variables (values printed from C#)" );
Console.WriteLine( "ivar =" + example.ivar );
Console.WriteLine( "svar =" + example.svar );
Console.WriteLine( "lvar =" + example.lvar );
Console.WriteLine( "uivar =" + example.uivar );
Console.WriteLine( "usvar =" + example.usvar );
Console.WriteLine( "ulvar =" + example.ulvar );
Console.WriteLine( "scvar =" + example.scvar );
Console.WriteLine( "ucvar =" + example.ucvar );
Console.WriteLine( "fvar =" + example.fvar );
Console.WriteLine( "dvar =" + example.dvar );
Console.WriteLine( "cvar =" + example.cvar );
Console.WriteLine( "strvar =" + example.strvar );
Console.WriteLine( "cstrvar =" + example.cstrvar );
Console.WriteLine( "iptrvar =" + example.iptrvar );
Console.WriteLine( "name =" + example.name );
Console.WriteLine( "ptptr =" + example.ptptr + example.Point_print(example.ptptr) );
Console.WriteLine( "pt =" + example.pt + example.Point_print(example.pt) );
Console.WriteLine( "\nVariables (values printed from C)" );
example.print_vars();
Console.WriteLine( "\nNow I'm going to try and modify some read only variables" );
Console.WriteLine( "\nChecking that the read only variables are readonly..." );
example ex = new example();
Type t = ex.GetType();
Console.WriteLine( " 'path'" );
PropertyInfo pi = t.GetProperty("path");
if (pi.CanWrite)
Console.WriteLine("Oh dear this variable is not read only\n");
else
Console.WriteLine("Good.");
Console.WriteLine( " 'status'" );
pi = t.GetProperty("status");
if (pi.CanWrite)
Console.WriteLine("Oh dear this variable is not read only");
else
Console.WriteLine("Good.");
Console.WriteLine( "\nI'm going to try and update a structure variable.\n" );
example.pt = example.ptptr;
Console.WriteLine( "The new value is" );
example.pt_print();
Console.WriteLine( "You should see the value" + example.Point_print(example.ptptr) );
}
}
module.exports = require("build/Release/example");
var example = require("example");
// ----- Object creation -----
console.log("Creating some objects:");
c = new example.Circle(10);
console.log("Created circle " + c);
s = new example.Square(10);
console.log("Created square " + s);
// ----- Access a static member -----
console.log("\nA total of " + example.Shape.nshapes + " shapes were created"); // access static member as properties of the class object
// ----- Member data access -----
// Set the location of the object.
// Note: methods in the base class Shape are used since
// x and y are defined there.
c.x = 20;
c.y = 30;
s.x = -10;
s.y = 5;
console.log("\nHere is their new position:");
console.log("Circle = (" + c.x + "," + c.y + ")");
console.log("Square = (" + s.x + "," + s.y + ")");
// ----- Call some methods -----
console.log("\nHere are some properties of the shapes:");
console.log("Circle:");
console.log("area = " + c.area() + "");
console.log("perimeter = " + c.perimeter() + "");
console.log("\n");
console.log("Square:");
console.log("area = " + s.area() + "");
console.log("perimeter = " + s.perimeter() + "");
// ----- Delete everything -----
console.log("\nGuess I'll clean up now");
// Note: this invokes the virtual destructor
delete c;
delete s;
console.log(example.Shape.nshapes + " shapes remain");
console.log("Goodbye");
module.exports = require("build/Release/example");
var example = require("example");
console.log("ICONST = " + example.ICONST + " (should be 42)");
console.log("FCONST = " + example.FCONST + " (should be 2.1828)");
console.log("CCONST = " + example.CCONST + " (should be 'x')");
console.log("CCONST2 = " + example.CCONST2 + " (this should be on a new line)");
console.log("SCONST = " + example.SCONST + " (should be 'Hello World')");
console.log("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')");
console.log("EXPR = " + example.EXPR + " (should be 48.5484)");
console.log("iconst = " + example.iconst + " (should be 37)");
console.log("fconst = " + example.fconst + " (should be 3.14)");
console.log("EXTERN = " + example.EXTERN + " (should be undefined)");
console.log("FOO = " + example.FOO + " (should be undefined)");
module.exports = require("build/Release/example");
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 property of cconst
console.log("example.speed.LUDICROUS= " + example.Foo.LUDICROUS);
module.exports = require("build/Release/example");
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 caught 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 caught 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 caught 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 caught 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 caught throw in Test::multi().");
}
}
}
module.exports = require("build/Release/example");
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());
module.exports = require("build/Release/example");
var example = require("example");
console.log("My magic number is: ", example.magicNumber());
module.exports = require("build/Release/example");
// 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());
module.exports = require("build/Release/example");
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);
module.exports = require("build/Release/example");
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);
module.exports = require("build/Release/example");
var example = require("example");
// First create some objects using the pointer library.
console.log("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);
console.log(" a = " + example.intp_value(a));
console.log(" b = " + example.intp_value(b));
console.log(" c = " + example.intp_value(c));
//// Call the add() function with some pointers
example.add(a, b, c);
//
//// Now get the result
r = example.intp_value(c);
console.log(" 37 + 42 = " + r);
// Clean up the pointers
example.delete_intp(a);
example.delete_intp(b);
example.delete_intp(c);
//// Now try the typemap library
//// This should be much easier. Now how it is no longer
//// necessary to manufacture pointers.
//"OUTPUT" Mapping is not supported
//console.log("Trying the typemap library");
//r = example.subtract(37,42);
//console.log("37 - 42 =" + r);
module.exports = require("build/Release/example");
// This file illustrates the manipulation of C++ references in Javascript.
var example = require("example");
// ----- Object creation -----
console.log("Creating some objects:");
a = new example.Vector(3,4,5);
b = new example.Vector(10,11,12);
console.log(" created" + a.print());
console.log(" created" + b.print());
// ----- Call an overloaded operator -----
// This calls the wrapper we placed around operator+(const Vector &a, const Vector &)
// It returns a new allocated object.
console.log("Adding a+b");
c = example.addv(a, b);
console.log("a+b = " + c.print());
// TODO: Note: Unless we free the result, a memory leak will occur
//delete_Vector(c);
// ----- Create a vector array -----
// Note: Using the high-level interface here
console.log("Creating an array of vectors");
va = new example.VectorArray(10);
console.log("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);
// This will work, but it will cause a memory leak!
va.set(2,example.addv(a,b));
// The non-leaky way to do it
//c = addv(a,b);
//va.set(3,c);
//delete_Vector(c);
// Get some values from the array
console.log("Getting some array values");
for (i = 0; i < 5; i++) {
temp = va.get(i);
console.log(i,temp.print());
}
// Watch under resource meter to check on this
console.log("Making sure we don't leak memory.");
for (i = 0; i < 1000000; i++) {
c = va.get(i % 10);
}
//---------TODO---------
//----- Clean up -----
//console.log("Cleaning up");
//example.delete_VectorArray(va);
//example.delete_Vector(a);
//example.delete_Vector(b);
module.exports = require("build/Release/example");
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);
module.exports = require("build/Release/example");
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;
module.exports = require("build/Release/example");
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("Trying 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));
# file: runme.py
# This file illustrates the cross language polymorphism using directors.
import example
class PyCallback(example.Callback):
def __init__(self):
example.Callback.__init__(self)
def run(self):
print "PyCallback.run()"
# Create an Caller instance
caller = example.Caller()
# 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"
print "----------------------------------------"
callback = example.Callback()
callback.thisown = 0
caller.setCallback(callback)
caller.call()
caller.delCallback()
print
print "Adding and calling a Python callback"
print "------------------------------------"
# Add a Python callback (caller owns the callback, so we
# disown it first by calling __disown__).
caller.setCallback(PyCallback().__disown__())
caller.call()
caller.delCallback()
print
print "Adding and calling another Python callback"
print "------------------------------------------"
# Let's do the same but use the weak reference this time.
callback = PyCallback().__disown__()
caller.setCallback(callback)
caller.call()
caller.delCallback()
# All done.
print
print "python exit"
# file: runme.py
# This file illustrates the proxy class C++ interface generated
# by SWIG.
import example
# ----- Object creation -----
print "Creating some objects:"
c = example.Circle(10)
print " Created circle", c
s = example.Square(10)
print " Created square", s
# ----- Access a static member -----
print "\nA total of", example.cvar.Shape_nshapes, "shapes were created"
# ----- Member data access -----
# Set the location of the object
c.x = 20
c.y = 30
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)
# ----- 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()
# prevent o from holding a reference to the last object looked at
o = None
print "\nGuess I'll clean up now"
# Note: this invokes the virtual destructor
del c
del s
print example.cvar.Shape_nshapes, "shapes remain"
print "Goodbye"
# file: runme.py
import example
print "ICONST =", example.ICONST, "(should be 42)"
print "FCONST =", example.FCONST, "(should be 2.1828)"
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 "iconst =", example.iconst, "(should be 37)"
print "fconst =", example.fconst, "(should be 3.14)"
try:
print "EXTERN = ", example.EXTERN, "(Arg! This shouldn't print anything)"
except AttributeError:
print "EXTERN isn't defined (good)"
try:
print "FOO = ", example.FOO, "(Arg! This shouldn't print anything)"
except AttributeError:
print "FOO isn't defined (good)"
# file: runme.py
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)
# Manipulate the Foo global variable
# Output its current value
print "Foo = ", example.cvar.Foo
# Change its value
example.cvar.Foo = 3.1415926
# See if the change took effect
print "Foo = ", example.cvar.Foo
# file: runme.py
import example
print "example.Foo.bar.__doc__ =", repr(example.Foo.bar.__doc__), "(Should be 'No comment')"
# This example shows simple usage of the wrapped Shape classes.
# The main purpose of this example is to show the doxygen comments translation to PyDoc comments.
# Users should look at the generated example.py file.
# The generated PyDoc can be viewed in a browser by opening the example.html file.
import example
print "Creating some objects:"
c = example.MakeCircle(10)
print " Created circle", c
s = example.MakeSquare(10)
print " Created square", s
r = example.MakeRectangleInt(10, 20)
print " Created rectangle", r
print "\nHere are some properties of the shapes:"
for o in [c, s, r]:
print " ", o
print " area = ", o.area()
print " perimeter = ", o.perimeter()
print "\nRunning pydoc, this is the equivalent to executing: pydoc -w ./example.py"
import pydoc
pydoc.writedoc("example")
print "Open example.html in your browser to view the generated python docs"
# file: runme.py
import example
# ----- Object creation -----
# Print out the value of some enums
print "*** color ***"
print " RED =", example.RED
print " BLUE =", example.BLUE
print " GREEN =", example.GREEN
print "\n*** Foo::speed ***"
print " Foo_IMPULSE =", example.Foo.IMPULSE
print " Foo_WARP =", example.Foo.WARP
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.GREEN, example.Foo.LUDICROUS)
example.enum_test(1234, 5678)
print "\nTesting use of enum with class method"
f = example.Foo()
f.enum_test(example.Foo.IMPULSE)
f.enum_test(example.Foo.WARP)
f.enum_test(example.Foo.LUDICROUS)
# file: runme.py
# Throw a lot of exceptions
import example
t = example.Test()
try:
t.unknown()
except RuntimeError, e:
print "incomplete type", e.args[0]
try:
t.simple()
except RuntimeError, e:
print e.args[0]
try:
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
# 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
print "Removing items"
try:
while 1:
q.dequeue()
except example.EmptyError, e:
pass
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
print "Removing items"
try:
while 1:
q.dequeue()
except example.EmptyError, e:
pass
# 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"
# 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("Alice")
print e.getName(), "is a", e.getPosition()
print "Just call her \"%s\"" % e.getTitle()
print "----------------------"
# 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()
# EmployeeList owns its items, so we must surrender ownership of objects
# we add. This involves first calling the __disown__ method to tell the
# C++ director to start reference counting. We reassign the resulting
# weakref.proxy to e so that no hard references remain. This can also be
# done when the object is constructed, as in: e =
# CEO("Alice").__disown__()
e = e.__disown__()
list.addEmployee(e)
print "----------------------"
# 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 Python. 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, Python resolved the call
# immediately in CEO, but now Python 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 Python implementation
# in CEO. All this routing takes place transparently.
print "(position, title) for items 0-3:"
print " %s, \"%s\"" % (list.get_item(0).getPosition(), list.get_item(0).getTitle())
print " %s, \"%s\"" % (list.get_item(1).getPosition(), list.get_item(1).getTitle())
print " %s, \"%s\"" % (list.get_item(2).getPosition(), list.get_item(2).getTitle())
print " %s, \"%s\"" % (list.get_item(3).getPosition(), list.get_item(3).getTitle())
print "----------------------"
# 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 Python 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.
del list
print "----------------------"
# All done.
print "python exit"
# file: runme.py
import example
a = 37
b = 42
# Now call our C function with a bunch of callbacks
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 "Here is what the C callback function objects look like in Python"
print " ADD =", example.ADD
print " SUB =", example.SUB
print " MUL =", example.MUL
# file: runme.py
import example
a = 37
b = 42
# Now call our C function with a bunch of callbacks
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 "Here is what the C callback function objects look like in Python"
print " ADD =", example.ADD
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)
# Operator overloading example
import example
import math
a = example.intSum(0)
b = example.doubleSum(100.0)
# Use the objects. They should be callable just like a normal
# python function.
for i in range(0, 100):
a(i) # Note: function call
b(math.sqrt(i)) # Note: function call
print a.result()
print b.result()
# file: runme.py
# Test various properties of classes defined in separate modules
print "Testing the %import directive"
import base
import foo
import bar
import spam
# Create some objects
print "Creating some objects"
a = base.Base()
b = foo.Foo()
c = bar.Bar()
d = spam.Spam()
# Try calling some methods
print "Testing some methods"
print "",
print "Should see 'Base::A' ---> ",
a.A()
print "Should see 'Base::B' ---> ",
a.B()
print "Should see 'Foo::A' ---> ",
b.A()
print "Should see 'Foo::B' ---> ",
b.B()
print "Should see 'Bar::A' ---> ",
c.A()
print "Should see 'Bar::B' ---> ",
c.B()
print "Should see 'Spam::A' ---> ",
d.A()
print "Should see 'Spam::B' ---> ",
d.B()
# Try some casts
print "\nTesting some casts\n"
print "",
x = a.toBase()
print "Should see 'Base::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = b.toBase()
print "Should see 'Foo::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = c.toBase()
print "Should see 'Bar::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = d.toBase()
print "Should see 'Spam::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = d.toBar()
print "Should see 'Bar::B' ---> ",
x.B()
print "\nTesting some dynamic casts\n"
x = d.toBase()
print " Spam -> Base -> Foo : ",
y = foo.Foo_fromBase(x)
if y:
print "bad swig"
else:
print "good swig"
print " Spam -> Base -> Bar : ",
y = bar.Bar_fromBase(x)
if y:
print "good swig"
else:
print "bad swig"
print " Spam -> Base -> Spam : ",
y = spam.Spam_fromBase(x)
if y:
print "good swig"
else:
print "bad swig"
print " Foo -> Spam : ",
y = spam.Spam_fromBase(b)
if y:
print "bad swig"
else:
print "good swig"
from bar import Pkg2_Bar
from .bar import Pkg2_Bar
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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 < (2, 5):
print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'"
sys.exit(0)
if sys.version_info < (3, 0):
import py2.pkg2
print " Finished importing py2.pkg2"
commandline = sys.executable + " -m py2.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py2.pkg2.foo"
run_except_on_windows(commandline)
else:
import py3.pkg2
print " Finished importing py3.pkg2"
# commandline = sys.executable + " -m py3.pkg2.bar"
# run_except_on_windows(commandline)
# commandline = sys.executable + " -m py3.pkg2.foo"
# run_except_on_windows(commandline)
# TODO: Commented out code above results in (from python-3.6 onwards):
# RuntimeWarning: 'py3.pkg2.bar' found in sys.modules after import of package 'py3.pkg2', but prior to execution of 'py3.pkg2.bar'; this may result in unpredictable behaviour
from bar import Pkg2_Bar
from .bar import Pkg2_Bar
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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 < (2, 5):
print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'"
sys.exit(0)
if sys.version_info < (3, 0):
import py2.pkg2
print " Finished importing py2.pkg2"
commandline = sys.executable + " -m py2.pkg2.bar"
run_except_on_windows(commandline)
else:
import py3.pkg2
print " Finished importing py3.pkg2"
# commandline = sys.executable + " -m py3.pkg2.bar"
# run_except_on_windows(commandline)
# TODO: Commented out code above results in (from python-3.6 onwards):
# RuntimeWarning: 'py3.pkg2.bar' found in sys.modules after import of package 'py3.pkg2', but prior to execution of 'py3.pkg2.bar'; this may result in unpredictable behaviour
from bar import Pkg2_Bar
from .bar import Pkg2_Bar
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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 < (2, 5):
print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'"
sys.exit(0)
if sys.version_info < (3, 0):
import py2.pkg2
print " Finished importing py2.pkg2"
commandline = sys.executable + " -m py2.pkg2.bar"
run_except_on_windows(commandline)
else:
import py3.pkg2
print " Finished importing py3.pkg2"
# commandline = sys.executable + " -m py3.pkg2.bar"
# run_except_on_windows(commandline)
# TODO: Commented out code above results in (from python-3.6 onwards):
# RuntimeWarning: 'py3.pkg2.bar' found in sys.modules after import of package 'py3.pkg2', but prior to execution of 'py3.pkg2.bar'; this may result in unpredictable behaviour
import os.path
import sys
# Test import of a SWIG generated module renamed as the package's __init__.py
testname = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
print "Testing " + testname + " - module renamed as __init__.py"
if sys.version_info >= (3, 0, 0) and sys.version_info < (3, 3, 0):
print " Not importing as Python version is >= 3.0 and < 3.3"
# Package detection does not work in these versions.
# Can be fixed by using this in the interface file:
# %module(moduleimport="from . import $module") foo # without -builtin
# %module(moduleimport="from .$module import *") foo # with -builtin
sys.exit(0)
import pkg1
print " Finished importing pkg1"
if pkg1.foofunction(123) != 1230:
raise RuntimeError("foofunction failed")
fc = pkg1.FooClass()
if fc.foomethod(1) != 6:
raise RuntimeError("foomethod failed")
print " Finished testing pkg1"
import os
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
print(" Starting subtest " + os.path.basename(__file__))
# import robin as a module in the global namespace
import robin
print(" Finished importing robin")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m robin"
run_except_on_windows(commandline)
import os
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
print(" Starting subtest " + os.path.basename(__file__))
# Package brave found under one path
sys.path.insert(0, "path1")
from brave import robin
print(" Finished from brave import robin")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m brave.robin"
run_except_on_windows(commandline, env = {"PYTHONPATH": "path1"})
import sys
import os
import shutil
import subprocess
import zipfile
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
def copyMods():
dirs = ["path1", "path2", "path3"]
# Clean out any old package paths
for d in dirs:
if os.path.isdir(d):
shutil.rmtree(d)
for d in dirs:
os.mkdir(d)
os.mkdir(os.path.join(d, "brave"))
shutil.copy("robin.py", os.path.join("path1", "brave"))
subprocess.check_call("cp _robin.* " + os.path.join("path1", "brave"), shell=True)
shutil.copy("robin.py", os.path.join("path2", "brave"))
subprocess.check_call("cp _robin.* " + os.path.join("path3", "brave"), shell=True)
mkzip()
def mkzip():
zf = zipfile.ZipFile("path4.zip", "w")
zf.writestr("brave/", b"")
zf.write("robin.py", "brave/robin.py")
zf.close()
def main():
copyMods()
# Run each test with a separate interpreter
run_except_on_windows(sys.executable + " nonpkg.py")
run_except_on_windows(sys.executable + " normal.py")
run_except_on_windows(sys.executable + " split.py")
run_except_on_windows(sys.executable + " zipsplit.py")
if __name__ == "__main__":
main()
# These examples rely on namespace packages. Don't
# run them for old python interpreters.
import os.path
import subprocess
import sys
testname = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
print "Testing " + testname + " - namespace packages"
if sys.version_info < (3, 3, 0):
print " Not importing nstest as Python version is < 3.3"
sys.exit(0)
import nstest
print " Finished importing nstest"
nstest.main()
import os
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
print(" Starting subtest " + os.path.basename(__file__))
# Package brave split into two paths.
# path2/brave/robin.py and path3/brave/_robin.so
sys.path.insert(0, "path2")
sys.path.insert(0, "path3")
from brave import robin
print(" Finished from brave import robin")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m brave.robin"
run_except_on_windows(commandline , env = {"PYTHONPATH": "path2:path3"})
import os
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
print(" Starting subtest " + os.path.basename(__file__))
# Package brave split into two paths.
# brave/robin.py (in path4.zip) and path3/brave/_robin.so
sys.path.insert(0, "path4.zip")
sys.path.insert(0, "path3")
from brave import robin
print(" Finished from brave import robin")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m brave.robin"
run_except_on_windows(commandline, env = {"PYTHONPATH": "path3:path4.zip"})
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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 < (2, 5):
print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'"
sys.exit(0)
if sys.version_info < (3, 0):
import py2.pkg2.bar
print " Finished importing py2.pkg2.bar"
commandline = sys.executable + " -m py2.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py2.pkg2.pkg3.foo"
run_except_on_windows(commandline)
else:
import py3.pkg2.bar
print " Finished importing py3.pkg2.bar"
commandline = sys.executable + " -m py3.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py3.pkg2.pkg3.foo"
run_except_on_windows(commandline)
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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 < (2, 5):
print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'"
sys.exit(0)
if sys.version_info < (3, 0):
import py2.pkg2.bar
print " Finished importing py2.pkg2.bar"
commandline = sys.executable + " -m py2.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py2.pkg2.pkg3.pkg4.foo"
run_except_on_windows(commandline)
else:
import py3.pkg2.bar
print " Finished importing py3.pkg2.bar"
commandline = sys.executable + " -m py3.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py3.pkg2.pkg3.pkg4.foo"
run_except_on_windows(commandline)
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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 < (2, 5):
print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'"
sys.exit(0)
if sys.version_info < (3, 0):
import py2.pkg2.bar
print " Finished importing py2.pkg2.bar"
commandline = sys.executable + " -m py2.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py2.pkg2.pkg3.foo"
run_except_on_windows(commandline)
else:
import py3.pkg2.bar
print " Finished importing py3.pkg2.bar"
commandline = sys.executable + " -m py3.pkg2.bar"
run_except_on_windows(commandline)
commandline = sys.executable + " -m py3.pkg2.pkg3.foo"
run_except_on_windows(commandline)
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
# 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))
if classname.find("pkg2.foo.Pkg2_Foo") == -1:
raise RuntimeError("failed type checking: " + classname)
print " Successfully created object pkg2.foo.Pkg2_Foo"
commandline = sys.executable + " -m pkg2.foo"
run_except_on_windows(commandline)
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
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))
if classname.find("pkg1.pkg2.foo.Pkg2_Foo") == -1:
raise RuntimeError("failed type checking: " + classname)
print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo"
commandline = sys.executable + " -m pkg1.pkg2.foo"
run_except_on_windows(commandline)
# killroy was here
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
testname = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
print "Testing " + testname + " - split modules"
import pkg1.foo
print " Finished importing pkg1.foo"
if not(pkg1.foo.count() == 3):
raise RuntimeError("test failed")
commandline = sys.executable + " -m pkg1.foo"
run_except_on_windows(commandline)
# killroy was here
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
testname = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
print "Testing " + testname + " - split modules"
import pkg1.foo
print " Finished importing pkg1.foo"
if not(pkg1.foo.count() == 3):
raise RuntimeError("test failed")
commandline = sys.executable + " -m pkg1.foo"
run_except_on_windows(commandline)
# file: runme.py
# Test various properties of classes defined in separate modules
print "Testing the %import directive with templates"
import base
import foo
import bar
import spam
# Create some objects
print "Creating some objects"
a = base.intBase()
b = foo.intFoo()
c = bar.intBar()
d = spam.intSpam()
# Try calling some methods
print "Testing some methods"
print "",
print "Should see 'Base::A' ---> ",
a.A()
print "Should see 'Base::B' ---> ",
a.B()
print "Should see 'Foo::A' ---> ",
b.A()
print "Should see 'Foo::B' ---> ",
b.B()
print "Should see 'Bar::A' ---> ",
c.A()
print "Should see 'Bar::B' ---> ",
c.B()
print "Should see 'Spam::A' ---> ",
d.A()
print "Should see 'Spam::B' ---> ",
d.B()
# Try some casts
print "\nTesting some casts\n"
print "",
x = a.toBase()
print "Should see 'Base::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = b.toBase()
print "Should see 'Foo::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = c.toBase()
print "Should see 'Bar::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = d.toBase()
print "Should see 'Spam::A' ---> ",
x.A()
print "Should see 'Base::B' ---> ",
x.B()
x = d.toBar()
print "Should see 'Bar::B' ---> ",
x.B()
print "\nTesting some dynamic casts\n"
x = d.toBase()
print " Spam -> Base -> Foo : ",
y = foo.intFoo_fromBase(x)
if y:
print "bad swig"
else:
print "good swig"
print " Spam -> Base -> Bar : ",
y = bar.intBar_fromBase(x)
if y:
print "good swig"
else:
print "bad swig"
print " Spam -> Base -> Spam : ",
y = spam.intSpam_fromBase(x)
if y:
print "good swig"
else:
print "bad swig"
print " Foo -> Spam : ",
y = spam.intSpam_fromBase(b)
if y:
print "bad swig"
else:
print "good swig"
# file: runme.py
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)
# Call the gcdmain() function
example.gcdmain(["gcdmain", "42", "105"])
# Call the count function
print example.count("Hello World", "l")
# Call the capitalize function
print example.capitalize("hello world")
# Operator overloading example
import example
a = example.Complex(2, 3)
b = example.Complex(-5, 10)
print "a =", a
print "b =", b
c = a + b
print "c =", c
print "a*b =", a * b
print "a-c =", a - c
e = example.ComplexCopy(a - c)
print "e =", e
# Big expression
f = ((a + b) * (c + b * e)) + (-a)
print "f =", f
import sys
sys.path.append("..")
import harness
def proc(mod):
for i in range(1000000):
x = mod.MyClass()
harness.run(proc)
import sys
sys.path.append("..")
import harness
def proc(mod):
x = mod.MyClass()
for i in range(10000000):
x.func()
harness.run(proc)
import sys
import time
import imp
from subprocess import *
def run(proc):
try:
mod = imp.find_module(sys.argv[1])
mod = imp.load_module(sys.argv[1], *mod)
t1 = time.clock()
proc(mod)
t2 = time.clock()
print "%s took %f seconds" % (mod.__name__, t2 - t1)
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)
(stdout, stderr) = proc.communicate()
print stdout
proc = Popen(
[sys.executable, "runme.py", "Simple_builtin"], stdout=PIPE)
(stdout, stderr) = proc.communicate()
print stdout
import sys
sys.path.append("..")
import harness
def proc(mod):
x = mod.H()
for i in range(10000000):
x.func()
harness.run(proc)
import sys
sys.path.append("..")
import harness
def proc(mod):
x = mod.H()
for i in range(10000000):
x += i
harness.run(proc)
import sys
sys.path.append("..")
import harness
def proc(mod):
x = mod.MyClass()
for i in range(10000000):
x = x + i
harness.run(proc)
# file: runme.py
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 " a =", a
print " b =", b
print " c =", c
# Call the add() function with some pointers
example.add(a, b, c)
# Now get the result
r = example.intp_value(c)
print " 37 + 42 =", r
# Clean up the pointers
example.delete_intp(a)
example.delete_intp(b)
example.delete_intp(c)
# Now try the typemap library
# 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
# 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)
# file: runme.py
# This file illustrates the manipulation of C++ references in Python
import example
# ----- Object creation -----
print "Creating some objects:"
a = example.Vector(3, 4, 5)
b = example.Vector(10, 11, 12)
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 &)
#
# It returns a new allocated object.
print "Adding a+b"
c = example.addv(a, b)
print " a+b =", c.cprint()
# Note: Unless we free the result, a memory leak will occur
del c
# ----- Create a vector array -----
# Note: Using the high-level interface here
print "Creating an array of vectors"
va = example.VectorArray(10)
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(2, example.addv(a, b))
# Get some values from the array
print "Getting some array values"
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):
c = va.get(i % 10)
# ----- Clean up -----
print "Cleaning up"
del va
del a
del b
# file: runme.py
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)
# Manipulate the Foo global variable
# Output its current value
print "Foo = ", example.cvar.Foo
# Change its value
example.cvar.Foo = 3.1415926
# See if the change took effect
print "Foo = ", example.cvar.Foo
# file: runme.py
# This file illustrates the proxy class C++ interface generated
# by SWIG.
import example
# ----- Object creation -----
print "Creating some objects:"
cc = example.Circle(10)
c = example.ShapePtr(cc)
print " Created circle", c
ss = example.Square(10)
s = example.ShapePtr(ss)
print " Created square", s
# ----- Access a static member -----
print "\nA total of", example.cvar.Shape_nshapes, "shapes were created"
# ----- Member data access -----
# Set the location of the object
c.x = 20
c.y = 30
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)
# ----- 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()
print "\nGuess I'll clean up now"
# Note: this invokes the virtual destructor
del c
del s
del cc
del ss
s = 3
print example.cvar.Shape_nshapes, "shapes remain"
print "Goodbye"
# file: runme.py
import example
pmap = example.pymap()
pmap["hi"] = 1
pmap["hello"] = 2
dmap = {}
dmap["hello"] = 1.0
dmap["hi"] = 2.0
print dmap.items()
print dmap.keys()
print dmap.values()
print dmap
hmap = example.halfd(dmap)
dmap = hmap
print dmap
for i in dmap.iterkeys():
print "key", i
for i in dmap.itervalues():
print "val", i
for k, v in dmap.iteritems():
print "item", k, v
dmap = example.DoubleMap()
dmap["hello"] = 1.0
dmap["hi"] = 2.0
for i in dmap.iterkeys():
print "key", i
for i in dmap.itervalues():
print "val", i
for k, v in dmap.iteritems():
print "item", k, v
print dmap.items()
print dmap.keys()
print dmap.values()
hmap = example.halfd(dmap)
print hmap.keys()
print hmap.values()
dmap = {}
dmap["hello"] = 2
dmap["hi"] = 4
hmap = example.halfi(dmap)
print hmap
print hmap.keys()
print hmap.values()
dmap = hmap
for i in dmap.iterkeys():
print "key", i
for i in dmap.itervalues():
print "val", i
for i in dmap.iteritems():
print "item", i
for k, v in dmap.iteritems():
print "item", k, v
print dmap
# file: runme.py
import example
# Call average with a Python list...
print example.average([1, 2, 3, 4])
# ... or a wrapped std::vector<int>
v = example.IntVector(4)
for i in range(len(v)):
v[i] = i + 1
print example.average(v)
# half will return a Python list.
# Call it with a Python tuple...
print example.half((1.0, 1.5, 2.0, 2.5, 3.0))
# ... or a wrapped std::vector<double>
v = example.DoubleVector()
for i in [1, 2, 3, 4]:
v.append(i)
print example.half(v)
# now halve a wrapped std::vector<double> in place
example.halve_in_place(v)
for i in range(len(v)):
print v[i], "; ",
print
# file: runme.py
import example
# Call some templated functions
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, 1000):
dv.setitem(i, 1.0 / (i + 1))
sum = 0
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)
print sum
del iv
del dv
# file: runme.py
import sys
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):
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(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(stdout, "The value is %d\n")
# This function calls our NULL-terminated function
example.printv("Hello", "World", "this", "is", "a", "test.")
# file: runme.py
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"
# Now print out the values of the variables
print "Variables (values printed from Python)"
print "ivar =", example.cvar.ivar
print "svar =", example.cvar.svar
print "lvar =", example.cvar.lvar
print "uivar =", example.cvar.uivar
print "usvar =", example.cvar.usvar
print "ulvar =", example.cvar.ulvar
print "scvar =", example.cvar.scvar
print "ucvar =", example.cvar.ucvar
print "fvar =", example.cvar.fvar
print "dvar =", example.cvar.dvar
print "cvar =", example.cvar.cvar
print "strvar =", example.cvar.strvar
print "cstrvar =", example.cvar.cstrvar
print "iptrvar =", example.cvar.iptrvar
print "name =", example.cvar.name
print "ptptr =", example.cvar.ptptr, example.Point_print(example.cvar.ptptr)
print "pt =", example.cvar.pt, example.Point_print(example.cvar.pt)
print "\nVariables (values printed from C)"
example.print_vars()
print "\nNow I'm going to try and modify some read only variables"
print " Trying to set 'path'"
try:
example.cvar.path = "Whoa!"
print "Hey, what's going on?!?! This shouldn't work"
except Exception:
print "Good."
print " Trying to set 'status'"
try:
example.cvar.status = 0
print "Hey, what's going on?!?! This shouldn't work"
except Exception:
print "Good."
print "\nI'm going to try and update a structure variable.\n"
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)
# file: runme.rb
# This file illustrates the C++ interface created by SWIG.
# All of our C++ classes get converted into Ruby classes.
require 'example'
# ----- Object creation -----
print "Creating some objects:\n"
c = Example::Circle.new(10)
print " Created circle #{c}\n"
s = Example::Square.new(10)
print " Created square #{s}\n"
# ----- Access a static member -----
print "\nA total of #{Example::Shape.nshapes} shapes were created\n"
# ----- Member data access -----
# Set the location of the object
# Notice how we can do this using functions specific to
# the 'Circle' class.
c.x = 20
c.y = 30
# Now use the same functions in the base class
s.x = -10
s.y = 5
print "\nHere is their current position:\n"
print " Circle = (", c.x, ",", c.y, ")\n"
print " Square = (", s.x, ",", s.y, ")\n"
# ----- Call some methods -----
print "\nHere are some properties of the shapes:\n"
for o in [c, s]
print " #{o}\n"
print " area = ", o.area, "\n"
print " perimeter = ", o.perimeter, "\n"
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"
# file: runme.rb
require 'example'
print "ICONST = ", Example::ICONST, " (should be 42)\n"
print "FCONST = ", Example::FCONST, " (should be 2.1828)\n"
print "CCONST = ", Example::CCONST, " (should be 'x')\n"
print "CCONST2 = ", Example::CCONST2, " (this should be on a new line)\n"
print "SCONST = ", Example::SCONST, " (should be 'Hello World')\n"
print "SCONST2 = ", Example::SCONST2, " (should be '\"Hello World\"')\n"
print "EXPR = ", Example::EXPR, " (should be 48.5484)\n"
print "iconst = ", Example::Iconst, " (should be 37)\n"
print "fconst = ", Example::Fconst, " (should be 3.14)\n"
begin
print "EXTERN = ", Example::EXTERN, " (Arg! This shouldn't print anything)\n"
rescue NameError
print "EXTERN isn't defined (good)\n"
end
begin
print "FOO = ", Example::FOO, " (Arg! This shouldn't print anything)\n"
rescue NameError
print "FOO isn't defined (good)\n"
end
# file: runme.rb
require 'example'
# ----- Object creation -----
# Print out the value of some enums
print "*** color ***\n"
print " RED = #{Example::RED}\n"
print " BLUE = #{Example::BLUE}\n"
print " GREEN = #{Example::GREEN}\n"
print "\n*** Foo::speed ***\n"
print " Foo::IMPULSE = #{Example::Foo::IMPULSE}\n"
print " Foo::WARP = #{Example::Foo::WARP}\n"
print " Foo::LUDICROUS = #{Example::Foo::LUDICROUS}\n"
print "\nTesting use of enums with functions\n\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)
print "\nTesting use of enum with class method\n"
f = Example::Foo.new()
f.enum_test(Example::Foo::IMPULSE)
f.enum_test(Example::Foo::WARP)
f.enum_test(Example::Foo::LUDICROUS)
require 'example'
q = Example::IntQueue.new(10)
puts "Inserting items into intQueue"
begin
0.upto(100) do |i|
q.enqueue(i)
end
rescue Example::FullError => e
puts "Maxsize is: #{e.maxsize}"
end
puts "Removing items"
begin
loop do
q.dequeue()
end
rescue Example::EmptyError => e
## do nothing
end
q = Example::DoubleQueue.new(1000)
puts "Inserting items into doubleQueue"
begin
0.upto(100) do |i|
q.enqueue(i*1.5)
end
rescue Example::FullError => e
puts "Maxsize is: #{e.maxsize}"
end
puts "Removing items"
begin
loop do
q.dequeue()
end
rescue Example::EmptyError => e
# do nothing
end
require 'example'
begin
begin
# Create an animal and zoo
tiger1 = Example::Animal.new("tiger1")
zoo = Example::Zoo.new
# At the animal to the zoo - this will transfer ownership
# of the underlying C++ object to the C++ zoo object
zoo.add_animal(tiger1)
# get the id of the tiger
id1 = tiger1.object_id
# Unset the tiger
tiger1 = nil
end
# Force a gc
GC.start
# Get the tiger and its id
tiger2 = zoo.get_animal(0)
id2 = tiger2.object_id
# The ids should not be the same
if id1==id2
# Not working - needs checking/fixing
# raise RuntimeError, "Id's should not be the same"
end
zoo = nil
end
GC.start
# This method is no longer valid since the zoo freed the underlying
# C++ object
ok = false
begin
# Let's stress the GC a bit, a single pass might not be enough.
10.times {
GC.start
puts tiger2.get_name
}
rescue ObjectPreviouslyDeleted => error
ok = true
end
raise(RuntimeError, "Incorrect exception raised - should be ObjectPreviouslyDeleted") unless ok
# file: runme.rb
require 'example'
a = 37
b = 42
# Now call our C function with a bunch of callbacks
print "Trying some C callback functions\n"
print " a = #{a}\n"
print " b = #{b}\n"
print " ADD(a,b) = ", Example::do_op(a,b,Example::ADD),"\n"
print " SUB(a,b) = ", Example::do_op(a,b,Example::SUB),"\n"
print " MUL(a,b) = ", Example::do_op(a,b,Example::MUL),"\n"
print "Here is what the C callback function objects look like in Ruby\n"
print " ADD = #{Example::ADD}\n"
print " SUB = #{Example::SUB}\n"
print " MUL = #{Example::MUL}\n"
require 'example'
a = 37
b = 42
# Now call our C function with a bunch of callbacks
puts "Trying some C callback functions"
puts " a = #{a}"
puts " b = #{b}"
puts " ADD(a,b) = #{Example.do_op(a,b,Example::ADD)}"
puts " SUB(a,b) = #{Example.do_op(a,b,Example::SUB)}"
puts " MUL(a,b) = #{Example.do_op(a,b,Example::MUL)}"
puts "Here is what the C callback function objects look like in Ruby"
puts " ADD = #{Example::ADD}"
puts " SUB = #{Example::SUB}"
puts " MUL = #{Example::MUL}"
puts "Call the functions directly..."
puts " add(a,b) = #{Example.add(a,b)}"
puts " sub(a,b) = #{Example.sub(a,b)}"
# Operator overloading example
require 'example'
a = Example::IntSum.new(0)
b = Example::DoubleSum.new(100.0)
# Use the objects. They should be callable just like a normal
# Ruby function.
(0..100).each do |i|
a.call(i) # note: function call
b.call(Math.sqrt(i)) # note: function call
end
puts a.result
puts b.result
require 'example'
include Example
# Pass arguments in as one or more key-value pairs
setVitalStats("Fred",
'age' => 42,
'weight' => 270
)
# The order doesn't matter
setVitalStats("Sally",
'age' => 29,
'weight' => 115,
'height' => 72
)
# Can also pass a hash directly
params = {
'ears' => 2,
'eyes' => 2
}
setVitalStats("Bob", params)
# An empty hash is fine too
setVitalStats("Joe", {})
# file: runme.rb
# Test various properties of classes defined in separate modules
puts "Testing the %import directive"
require 'base'
require 'foo'
require 'bar'
require 'spam'
# Create some objects
puts "Creating some objects"
a = Base::Base.new
b = Foo::Foo.new
c = Bar::Bar.new
d = Spam::Spam.new
# Try calling some methods
puts "Testing some methods"
puts "Should see 'Base::A' ---> #{a.A}"
puts "Should see 'Base::B' ---> #{a.B}"
puts "Should see 'Foo::A' ---> #{b.A}"
puts "Should see 'Foo::B' ---> #{b.B}"
puts "Should see 'Bar::A' ---> #{c.A}"
puts "Should see 'Bar::B' ---> #{c.B}"
puts "Should see 'Spam::A' ---> #{d.A}"
puts "Should see 'Spam::B' ---> #{d.B}"
# Try some casts
puts "\nTesting some casts\n"
x = a.toBase
puts "Should see 'Base::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = b.toBase
puts "Should see 'Foo::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = c.toBase
puts "Should see 'Bar::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = d.toBase
puts "Should see 'Spam::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = d.toBar
puts "Should see 'Bar::B' ---> #{x.B}"
puts "\nTesting some dynamic casts\n"
x = d.toBase
puts " Spam -> Base -> Foo : "
y = Foo::Foo.fromBase(x)
if y != nil
puts "bad swig"
else
puts "good swig"
end
puts " Spam -> Base -> Bar : "
y = Bar::Bar.fromBase(x)
if y != nil
puts "good swig"
else
puts "bad swig"
end
puts " Spam -> Base -> Spam : "
y = Spam::Spam.fromBase(x)
if y != nil
puts "good swig"
else
puts "bad swig"
end
puts " Foo -> Spam : "
y = Spam::Spam.fromBase(b)
if y != nil
puts "bad swig"
else
puts "good swig"
end
# file: runme.rb
# Test various properties of classes defined in separate modules
puts "Testing the %import directive with templates"
require 'base'
require 'foo'
require 'bar'
require 'spam'
# Create some objects
puts "Creating some objects"
a = Base::IntBase.new
b = Foo::IntFoo.new
c = Bar::IntBar.new
d = Spam::IntSpam.new
# Try calling some methods
puts "Testing some methods"
puts ""
puts "Should see 'Base::A' ---> #{a.A}"
puts "Should see 'Base::B' ---> #{a.B}"
puts "Should see 'Foo::A' ---> #{b.A}"
puts "Should see 'Foo::B' ---> #{b.B}"
puts "Should see 'Bar::A' ---> #{c.A}"
puts "Should see 'Bar::B' ---> #{c.B}"
puts "Should see 'Spam::A' ---> #{d.A}"
puts "Should see 'Spam::B' ---> #{d.B}"
# Try some casts
puts "\nTesting some casts\n"
puts ""
x = a.toBase
puts "Should see 'Base::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = b.toBase
puts "Should see 'Foo::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = c.toBase
puts "Should see 'Bar::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = d.toBase
puts "Should see 'Spam::A' ---> #{x.A}"
puts "Should see 'Base::B' ---> #{x.B}"
x = d.toBar
puts "Should see 'Bar::B' ---> #{x.B}"
puts "\nTesting some dynamic casts\n"
x = d.toBase
puts " Spam -> Base -> Foo : "
y = Foo::IntFoo.fromBase(x)
if y != nil
puts "bad swig"
else
puts "good swig"
end
puts " Spam -> Base -> Bar : "
y = Bar::IntBar.fromBase(x)
if y != nil
puts "good swig"
else
puts "bad swig"
end
puts " Spam -> Base -> Spam : "
y = Spam::IntSpam.fromBase(x)
if y != nil
puts "good swig"
else
puts "bad swig"
end
puts " Foo -> Spam : "
y = Spam::IntSpam.fromBase(b)
if y != nil
puts "bad swig"
else
puts "good swig"
end
require 'example'
# create a zoo
zoo = Example::Zoo.new
begin
# Add in an couple of animals
tiger1 = Example::Animal.new("tiger1")
zoo.add_animal(tiger1)
# unset variables to force gc
tiger1 = nil
end
GC.start
# Now get the tiger again
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
# file: runme.rb
require 'example'
# Call our gcd() function
x = 42
y = 105
g = Example.gcd(x,y)
printf "The gcd of %d and %d is %d\n",x,y,g
# Call the gcdmain() function
Example.gcdmain(["gcdmain","42","105"])
# Call the count function
printf "%d\n",Example.count("Hello World","l")
# Call the capitalize function
printf "%s\n",Example.capitalize("hello world")
# Operator overloading example
require 'example'
include Example
a = Example::Complex.new(2, 3)
b = Example::Complex.new(-5, 10)
puts "a = #{a}"
puts "b = #{b}"
c = a + b
puts "c = #{c}"
puts "a*b = #{a*b}"
puts "a-c = #{a-c}"
# This should invoke Complex's copy constructor
e = Example::Complex.new(a-c)
e = a - c
puts "e = #{e}"
# Big expression
f = ((a+b)*(c+b*e)) + (-a)
puts "f = #{f}"
require 'example'
# This should invoke foo(double)
Example.foo(3.14159)
# This should invoke foo(double, char *)
Example.foo(3.14159, "Pi")
# This should invoke foo(int, int)
Example.foo(3, 4)
# This should invoke foo(char *)
Example.foo("This is a test")
# This should invoke foo(long)
Example.foo(42)
# This should invoke Bar::Bar() followed by foo(Bar *)
Example.foo(Example::Bar.new)
# Skip a line
puts ""
# Each of the following three calls should invoke spam(int, int, int)
Example.spam(3)
Example.spam(3, 4)
Example.spam(3, 4, 5)
# Skip a line
puts ""
# Each of the following three calls should invoke spam(double, int, int)
Example.spam(3.0)
Example.spam(3.0, 4)
Example.spam(3.0, 4, 5)
# Skip a line
puts ""
# This should invoke Bar::Bar(double)
Example::Bar.new(3.14159)
# This should invoke Bar::Bar(double, char *)
Example::Bar.new(3.14159, "Pi")
# This should invoke Bar::Bar(int, int)
Example::Bar.new(3, 4)
# This should invoke Bar::Bar(char *)
Example::Bar.new("This is a test")
# This should invoke Bar::Bar(int)
Example::Bar.new(42)
# This should invoke Bar::Bar() for the input argument,
# followed by Bar::Bar(const Bar&).
Example::Bar.new(Example::Bar.new)
# Skip a line
puts ""
# Construct a new Bar instance (invokes Bar::Bar())
bar = Example::Bar.new
# This should invoke Bar::foo(double)
bar.foo(3.14159)
# This should invoke Bar::foo(double, char *)
bar.foo(3.14159, "Pi")
# This should invoke Bar::foo(int, int)
bar.foo(3, 4)
# This should invoke Bar::foo(char *)
bar.foo("This is a test")
# This should invoke Bar::foo(int)
bar.foo(42)
# This should invoke Bar::Bar() to construct the input
# argument, followed by Bar::foo(Bar *).
bar.foo(Example::Bar.new)
# This should invoke Bar::spam(int x, int y, int z)
bar.spam(1)
# This should invoke Bar::spam(double x, int y, int z)
bar.spam(3.14159)
# file: runme.rb
require 'example'
# First create some objects using the pointer library.
print "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)
print " a = #{a}\n"
print " b = #{b}\n"
print " c = #{c}\n"
# Call the add() function with some pointers
Example::add(a, b, c)
# Now get the result
r = Example::intp_value(c)
print " 37 + 42 = #{r}\n"
# Clean up the pointers
Example::delete_intp(a)
Example::delete_intp(b)
Example::delete_intp(c)
# Now try the typemap library
# This should be much easier. Now how it is no longer
# necessary to manufacture pointers.
print "Trying the typemap library\n"
r = Example::sub(37, 42)
print " 37 - 42 = #{r}\n"
# Now try the version with multiple return values
print "Testing multiple return values\n"
q, r = Example::divide(42, 37)
print " 42/37 = #{q} remainder #{r}\n"
# file: runme.rb
# This file illustrates the manipulation of C++ references in Ruby.
require 'example'
# ----- Object creation -----
print "Creating some objects:\n"
a = Example::Vector.new(3,4,5)
b = Example::Vector.new(10,11,12)
print " Created ", a.print, "\n"
print " Created ", b.print, "\n"
# ----- Call an overloaded operator -----
# This calls the wrapper we placed around
#
# operator+(const Vector &a, const Vector &)
#
# It returns a new allocated object.
print "Adding a+b\n"
c = Example::addv(a, b)
print " a+b = ", c.print, "\n"
# ----- Create a vector array -----
print "Creating an array of vectors\n"
va = Example::VectorArray.new(10)
print " va = #{va}\n"
# ----- Set some values in the array -----
# These operators copy the value of a and b to the vector array
va.set(0, a)
va.set(1, b)
va.set(2, Example::addv(a,b))
c = Example::addv(a,b)
va.set(3, c)
=begin commented out due to GC issue
# Get some values from the array
print "Getting some array values\n"
for i in 0...5
print " va(#{i}) = ", va.get(i).print, "\n"
end
# Watch under resource meter to check on this
print "Making sure we don't leak memory.\n"
for i in 0...1000000
c = va.get(i % 10)
end
=end
# file: runme.rb
require 'example'
# Call our gcd() function
x = 42
y = 105
g = Example.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
print "Foo = ", Example.Foo, "\n"
# Change its value
Example.Foo = 3.1415926
# See if the change took effect
print "Foo = ", Example.Foo, "\n"
# file: runme.rb
require 'example'
# Call average with a Ruby array...
puts Example::average([1,2,3,4])
# ... or a wrapped std::vector<int>
v = Example::IntVector.new(4)
0.upto(v.size-1) { |i| v[i] = i+1 }
puts Example::average(v)
# half will return a Ruby array.
# Call it with a Ruby array...
w = Example::half([1.0, 1.5, 2.0, 2.5, 3.0])
0.upto(w.size-1) { |i| print w[i],"; " }
puts
# ... or a wrapped std::vector<double>
v = Example::DoubleVector.new
[1,2,3,4].each { |i| v.push(i) }
w = Example::half(v)
0.upto(w.size-1) { |i| print w[i],"; " }
puts
# now halve a wrapped std::vector<double> in place
Example::halve_in_place(v)
0.upto(v.size-1) { |i| print v[i],"; " }
puts
# file: runme.rb
require 'example'
# Call some templated functions
puts Example::maxint(3, 7)
puts Example::maxdouble(3.14, 2.18)
# Create some class
iv = Example::Vecint.new(100)
dv = Example::Vecdouble.new(1000)
100.times { |i| iv.setitem(i, 2*i) }
1000.times { |i| dv.setitem(i, 1.0/(i+1)) }
sum = 0
100.times { |i| sum = sum + iv.getitem(i) }
puts sum
sum = 0.0
1000.times { |i| sum = sum + dv.getitem(i) }
puts sum
# file: runme.rb
require 'example'
# Create a couple of a vectors
v = Example::new_Vector(1, 2, 3)
w = Example::new_Vector(10, 11, 12)
print "I just created the following vectors\n"
Example::vector_print(v)
Example::vector_print(w)
# Now call some of our functions
print "\nNow I'm going to compute the dot product\n"
d = Example::dot_product(v,w)
print "dot product = #{d} (should be 68)\n"
# Add the vectors together
print "\nNow I'm going to add the vectors together\n"
r = Example::vector_add(v,w)
Example::vector_print(r)
print "The value should be (11, 13, 15)\n"
# Now I'd better clean up the return result r
print "\nNow I'm going to clean up the return result\n"
Example::free(r)
print "Good\n"
# file: runme.rb
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 print out the values of the variables
puts "Variables (values printed from Ruby)"
puts "ivar = #{Example.ivar}"
puts "svar = #{Example.svar}"
puts "lvar = #{Example.lvar}"
puts "uivar = #{Example.uivar}"
puts "usvar = #{Example.usvar}"
puts "ulvar = #{Example.ulvar}"
puts "scvar = #{Example.scvar}"
puts "ucvar = #{Example.ucvar}"
puts "fvar = #{Example.fvar}"
puts "dvar = #{Example.dvar}"
puts "cvar = #{Example.cvar}"
puts "strvar = #{Example.strvar}"
puts "cstrvar = #{Example.cstrvar}"
puts "iptrvar = #{Example.iptrvar}"
puts "name = #{Example.name}"
puts "ptptr = #{Example.ptptr} (#{Example.Point_print(Example.ptptr)})"
puts "pt = #{Example.pt} (#{Example.Point_print(Example.pt)})"
puts "\nVariables (values printed from C)"
Example.print_vars()
puts "\nNow I'm going to try and modify some read only variables";
puts " Trying to set 'path'";
begin
Example.path = "Whoa!"
puts "Hey, what's going on?!?! This shouldn't work"
rescue NameError
puts "Good."
end
puts " Trying to set 'status'";
begin
Example.status = 0
puts "Hey, what's going on?!?! This shouldn't work"
rescue NameError
puts "Good."
end
puts "\nI'm going to try and update a structure variable.\n"
Example.pt = Example.ptptr
puts "The new value is"
Example.pt_print()
puts "You should see the value #{Example.Point_print(Example.ptptr)}"
using System;
using aggregateNamespace;
public class runme {
static void Main() {
// Confirm that move() returns correct results under normal use
int result = aggregate.move(aggregate.UP);
if (result != aggregate.UP) throw new Exception("UP failed");
result = aggregate.move(aggregate.DOWN);
if (result != aggregate.DOWN) throw new Exception("DOWN failed");
result = aggregate.move(aggregate.LEFT);
if (result != aggregate.LEFT) throw new Exception("LEFT failed");
result = aggregate.move(aggregate.RIGHT);
if (result != aggregate.RIGHT) throw new Exception("RIGHT failed");
// Confirm that move() raises an exception when the contract is violated
try {
aggregate.move(0);
throw new Exception("0 test failed");
}
catch (ArgumentOutOfRangeException) {
}
}
}
using System;
using allprotectedNamespace;
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
MyProtectedBase mpb = new MyProtectedBase("MyProtectedBase");
mpb.accessProtected();
try {
// C++ destructor is protected
mpb.Dispose();
throw new Exception("failed to catch MethodAccessException");
} catch (MethodAccessException) {
// Exception message: C++ destructor does not have public access
}
ProtectedDerived pd = new ProtectedDerived("ProtectedDerived");
// Destroying via the ProtectedDerived's destructor should work
pd.Dispose();
ProtectedBase pb = new ProtectedDerived("ProtectedDerived");
// ProtectedDerived's destructor should be called via the Dispose(disposing) virtual call
pb.Dispose();
}
}
class MyProtectedBase : ProtectedBase
{
public MyProtectedBase(string name) : base(name) {
}
public void accessProtected() {
string s = virtualMethod();
if (s != "ProtectedBase")
throw new Exception("Failed");
Klass k = instanceMethod(new Klass("xyz"));
if (k.getName() != "xyz")
throw new Exception("Failed");
k = instanceOverloaded(new Klass("xyz"));
if (k.getName() != "xyz")
throw new Exception("Failed");
k = instanceOverloaded(new Klass("xyz"), "abc");
if (k.getName() != "abc")
throw new Exception("Failed");
k = ProtectedBase.staticMethod(new Klass("abc"));
if (k.getName() != "abc")
throw new Exception("Failed");
k = ProtectedBase.staticOverloaded(new Klass("xyz"));
if (k.getName() != "xyz")
throw new Exception("Failed");
k = ProtectedBase.staticOverloaded(new Klass("xyz"), "abc");
if (k.getName() != "abc")
throw new Exception("Failed");
instanceMemberVariable = 30;
int i = instanceMemberVariable;
if (i != 30)
throw new Exception("Failed");
staticMemberVariable = 40;
i = staticMemberVariable;
if (i != 40)
throw new Exception("Failed");
i = staticConstMemberVariable;
if (i != 20)
throw new Exception("Failed");
anEnum = ProtectedBase.AnEnum.EnumVal1;
ProtectedBase.AnEnum ae = anEnum;
if (ae != ProtectedBase.AnEnum.EnumVal1)
throw new Exception("Failed");
}
}
using System;
using apply_stringsNamespace;
public class apply_strings_runme {
private static string TEST_MESSAGE = "A message from target language to the C++ world and back again.";
public static void Main() {
if (apply_strings.UCharFunction(TEST_MESSAGE) != TEST_MESSAGE) throw new Exception("UCharFunction failed");
if (apply_strings.SCharFunction(TEST_MESSAGE) != TEST_MESSAGE) throw new Exception("SCharFunction failed");
SWIGTYPE_p_char pChar = apply_strings.CharFunction(null);
if (pChar != null) throw new Exception("CharFunction failed");
}
}
// This is the bool runtime testcase. It checks that the C++ bool type works.
using System;
using boolsNamespace;
public class bools_runme {
public static void Main() {
bool t = true;
bool f = false;
check_bo(f);
check_bo(t);
}
public static void check_bo(bool input) {
for( int i=0; i<1000; i++ ) {
if( bools.bo(input) != input ) {
string ErrorMessage = "Runtime test check_bo failed.";
throw new Exception(ErrorMessage);
}
}
}
}
using System;
using catchesNamespace;
public class runme {
static void Main() {
// test_catches()
try {
catches.test_catches(1);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ int exception thrown, value: 1")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
catches.test_catches(2);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "two")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
catches.test_catches(3);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ ThreeException const & exception thrown")
throw new ApplicationException("bad exception order: " + e.Message);
}
// test_exception_specification()
try {
catches.test_exception_specification(1);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ int exception thrown, value: 1")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
catches.test_exception_specification(2);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "unknown exception")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
catches.test_exception_specification(3);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "unknown exception")
throw new ApplicationException("bad exception order: " + e.Message);
}
// test_catches_all()
try {
catches.test_catches_all(1);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "unknown exception")
throw new ApplicationException("bad exception order: " + e.Message);
}
}
}
using System;
using char_stringsNamespace;
public class char_strings_runme {
private static string CPLUSPLUS_MSG = "A message from the deep dark world of C++, where anything is possible.";
private static string OTHERLAND_MSG = "Little message from the safe world.";
public static void Main() {
uint count = 10000;
uint i = 0;
// get functions
for (i=0; i<count; i++) {
string str = char_strings.GetCharHeapString();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test char get 1 failed, iteration " + i);
char_strings.DeleteCharHeapString();
}
for (i=0; i<count; i++) {
string str = char_strings.GetConstCharProgramCodeString();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test char get 2 failed, iteration " + i);
char_strings.DeleteCharHeapString();
}
for (i=0; i<count; i++) {
string str = char_strings.GetCharStaticString();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test char get 3 failed, iteration " + i);
}
for (i=0; i<count; i++) {
string str = char_strings.GetCharStaticStringFixed();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test char get 4 failed, iteration " + i);
}
for (i=0; i<count; i++) {
string str = char_strings.GetConstCharStaticStringFixed();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test char get 5 failed, iteration " + i);
}
// set functions
for (i=0; i<count; i++) {
if (!char_strings.SetCharHeapString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 1 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetCharStaticString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 2 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetCharArrayStaticString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 3 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetConstCharHeapString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 4 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetConstCharStaticString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 5 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetConstCharArrayStaticString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 6 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetCharConstStaticString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 7 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetConstCharConstStaticString(OTHERLAND_MSG + i, i))
throw new Exception("Test char set 8 failed, iteration " + i);
}
// get set function
for (i=0; i<count*10; i++) {
string ping = OTHERLAND_MSG + i;
string pong = char_strings.CharPingPong(ping);
if (ping != pong)
throw new Exception("Test PingPong 1 failed.\nExpected:" + ping + "\nReceived:" + pong);
}
// variables
for (i=0; i<count; i++) {
char_strings.global_char = OTHERLAND_MSG + i;
if (char_strings.global_char != OTHERLAND_MSG + i)
throw new Exception("Test variables 1 failed, iteration " + i);
}
for (i=0; i<count; i++) {
char_strings.global_char_array1 = OTHERLAND_MSG + i;
if (char_strings.global_char_array1 != OTHERLAND_MSG + i)
throw new Exception("Test variables 2 failed, iteration " + i);
}
for (i=0; i<count; i++) {
char_strings.global_char_array2 = OTHERLAND_MSG + i;
if (char_strings.global_char_array2 != OTHERLAND_MSG + i)
throw new Exception("Test variables 3 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (char_strings.global_const_char != CPLUSPLUS_MSG)
throw new Exception("Test variables 4 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (char_strings.global_const_char_array1 != CPLUSPLUS_MSG)
throw new Exception("Test variables 5 failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (char_strings.global_const_char_array2 != CPLUSPLUS_MSG)
throw new Exception("Test variables 6 failed, iteration " + i);
}
// char *& tests
for (i=0; i<count; i++) {
String str = char_strings.GetCharPointerRef();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test char pointer ref get failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetCharPointerRef(OTHERLAND_MSG + i, i))
throw new Exception("Test char pointer ref set failed, iteration " + i);
}
for (i=0; i<count; i++) {
String str = char_strings.GetConstCharPointerRef();
if (str != CPLUSPLUS_MSG)
throw new Exception("Test const char pointer ref get failed, iteration " + i);
}
for (i=0; i<count; i++) {
if (!char_strings.SetConstCharPointerRef(OTHERLAND_MSG + i, i))
throw new Exception("Test const char pointer ref set failed, iteration " + i);
}
}
}
// This is the complex runtime testcase. It checks that the C++ std::complex type works.
// It requires .NET 4.0 as the previous versions didn't have System.Numerics.Complex type.
using System;
using System.Numerics;
using complextestNamespace;
public class complextest_runme {
public static void Main() {
var a = new Complex(-1, 2);
if ( complextest.Conj(a) != Complex.Conjugate(a) )
throw new Exception("std::complex<double> test failed");
if ( complextest.Conjf(a) != Complex.Conjugate(a) )
throw new Exception("std::complex<float> test failed");
if ( complextest.Conj2(a) != Complex.Conjugate(a) )
throw new Exception("std::complex<double> test failed");
if ( complextest.Conjf2(a) != Complex.Conjugate(a) )
throw new Exception("std::complex<float> test failed");
var vec = new VectorStdCplx();
vec.Add(new Complex(1, 2));
vec.Add(new Complex(2, 3));
vec.Add(new Complex(4, 3));
vec.Add(new Complex(1, 0));
if ( complextest.CopyHalf(vec).Count != 2 )
throw new Exception("CopyHalf test failed");
if ( complextest.CopyHalfRef(vec).Count != 2 )
throw new Exception("CopyHalfRef test failed");
var p = new ComplexPair();
p.z1 = new Complex(0, 1);
p.z2 = new Complex(0, -1);
if ( Complex.Conjugate(p.z2) != p.z1 )
throw new Exception("vector<complex> test failed");
}
}
using System;
using constoverNamespace;
public class runme
{
static void Main()
{
string p = constover.test("test");
if ( p != "test" )
throw new Exception( "test failed!" );
p = constover.test_pconst("test");
if ( p != "test_pconst" )
throw new Exception( "test_pconst failed!" );
Foo f = new Foo();
p = f.test("test");
if ( p != "test" )
throw new Exception( "member-test failed!" );
p = f.test_pconst("test");
if ( p != "test_pconst" )
throw new Exception( "member-test_pconst failed!" );
p = f.test_constm("test");
if ( p != "test_constmethod" )
throw new Exception( "member-test_constm failed!" );
p = f.test_pconstm("test");
if ( p != "test_pconstmethod" )
throw new Exception( "member-test_pconstm failed!" );
}
}
// This is the cpp11_shared_ptr_template_upcast runtime testcase. It checks that SWIG generates the appropriate upcasted shared_ptr type for a template instantiation deriving from a base class.
// For this case, the expected behavior is: given a cptr with underlying type shared_ptr<Printable<Derived> >, PrintableDerived_SWIGSmartPtrUpcast returns a cptr with
// underlying type std::shared_ptr< Derived >, where Printable<Derived> inherits from Derived.
using System;
using cpp11_shared_ptr_template_upcastNamespace;
public class cpp11_shared_ptr_template_upcast_runme
{
static void Main()
{
PrintableDerived pd = cpp11_shared_ptr_template_upcast.MakePrintableDerived(20);
pd.GetResult();
pd.GetFormatted();
}
}
// This test tests all the methods in the C# collection wrapper
using System;
using cpp11_std_arrayNamespace;
public class cpp11_std_array_runme
{
private static ArrayInt6 ToArray6(int[] a)
{
if (a.Length != 6)
throw new Exception("a is incorrect size");
return new ArrayInt6(a);
}
private static void compareContainers(ArrayInt6 actual, int[] expected)
{
if (actual.Count != expected.Length)
throw new Exception("Sizes are different: " + actual.Count + " " + expected.Length);
for (int i=0; i<actual.Count; ++i)
{
int actualValue = actual[i];
int expectedValue = expected[i];
if (actualValue != expectedValue)
throw new Exception("Value is wrong for element " + i + ". Expected " + expectedValue + " got: " + actualValue);
}
if (actual.IsEmpty)
throw new Exception("ai should not be empty");
}
static void Main()
{
ArrayInt6 ai = new ArrayInt6();
compareContainers(ai, new int[] { 0, 0, 0, 0, 0, 0 });
int[] vals = { 10, 20, 30, 40, 50, 60 };
for (int i = 0; i < ai.Count; ++i)
ai[i] = vals[i];
compareContainers(ai, vals);
// Check return
compareContainers(cpp11_std_array.arrayOutVal(), new int[] { -2, -1, 0, 0, 1, 2 });
compareContainers(cpp11_std_array.arrayOutConstRef(), new int[] { -2, -1, 0, 0, 1, 2 });
compareContainers(cpp11_std_array.arrayOutRef(), new int[] { -2, -1, 0, 0, 1, 2 });
compareContainers(cpp11_std_array.arrayOutPtr(), new int[] { -2, -1, 0, 0, 1, 2 });
// Check passing arguments
ai = cpp11_std_array.arrayInVal(ToArray6(new int[] { 9, 8, 7, 6, 5, 4 }));
compareContainers(ai, new int[] { 90, 80, 70, 60, 50, 40 });
ai = cpp11_std_array.arrayInConstRef(ToArray6(new int[] { 9, 8, 7, 6, 5, 4 }));
compareContainers(ai, new int[] { 90, 80, 70, 60, 50, 40 });
ai = new ArrayInt6(ToArray6(new int[] { 9, 8, 7, 6, 5, 4 }));
cpp11_std_array.arrayInRef(ai);
compareContainers(ai, new int[] { 90, 80, 70, 60, 50, 40 });
ai = new ArrayInt6(ToArray6(new int[] { 9, 8, 7, 6, 5, 4 }));
cpp11_std_array.arrayInPtr(ai);
compareContainers(ai, new int[] { 90, 80, 70, 60, 50, 40 });
// fill
ai.Fill(111);
compareContainers(ai, new int[] { 111, 111, 111, 111, 111, 111 });
// out of range errors
try
{
ai[ai.Count] = 0;
throw new Exception("Out of range exception not caught");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
ai[-1] = 0;
throw new Exception("Out of range exception not caught");
}
catch (ArgumentOutOfRangeException)
{
}
}
}
using System;
using cpp11_strongly_typed_enumerationsNamespace;
public class cpp11_strongly_typed_enumerations_runme {
public static int enumCheck(int actual, int expected) {
if (actual != expected)
throw new ApplicationException("Enum value mismatch. Expected " + expected + " Actual: " + actual);
return expected + 1;
}
public static void Main() {
int val = 0;
val = enumCheck((int)Enum1.Val1, val);
val = enumCheck((int)Enum1.Val2, val);
val = enumCheck((int)Enum1.Val3, 13);
val = enumCheck((int)Enum1.Val4, val);
val = enumCheck((int)Enum1.Val5a, 13);
val = enumCheck((int)Enum1.Val6a, val);
val = 0;
val = enumCheck((int)Enum2.Val1, val);
val = enumCheck((int)Enum2.Val2, val);
val = enumCheck((int)Enum2.Val3, 23);
val = enumCheck((int)Enum2.Val4, val);
val = enumCheck((int)Enum2.Val5b, 23);
val = enumCheck((int)Enum2.Val6b, val);
val = 0;
val = enumCheck((int)Enum4.Val1, val);
val = enumCheck((int)Enum4.Val2, val);
val = enumCheck((int)Enum4.Val3, 43);
val = enumCheck((int)Enum4.Val4, val);
val = 0;
val = enumCheck((int)Enum5.Val1, val);
val = enumCheck((int)Enum5.Val2, val);
val = enumCheck((int)Enum5.Val3, 53);
val = enumCheck((int)Enum5.Val4, val);
val = 0;
val = enumCheck((int)Enum6.Val1, val);
val = enumCheck((int)Enum6.Val2, val);
val = enumCheck((int)Enum6.Val3, 63);
val = enumCheck((int)Enum6.Val4, val);
val = 0;
val = enumCheck((int)Enum7td.Val1, val);
val = enumCheck((int)Enum7td.Val2, val);
val = enumCheck((int)Enum7td.Val3, 73);
val = enumCheck((int)Enum7td.Val4, val);
val = 0;
val = enumCheck((int)Enum8.Val1, val);
val = enumCheck((int)Enum8.Val2, val);
val = enumCheck((int)Enum8.Val3, 83);
val = enumCheck((int)Enum8.Val4, val);
val = 0;
val = enumCheck((int)Enum10.Val1, val);
val = enumCheck((int)Enum10.Val2, val);
val = enumCheck((int)Enum10.Val3, 103);
val = enumCheck((int)Enum10.Val4, val);
val = 0;
val = enumCheck((int)Class1.Enum12.Val1, 1121);
val = enumCheck((int)Class1.Enum12.Val2, 1122);
val = enumCheck((int)Class1.Enum12.Val3, val);
val = enumCheck((int)Class1.Enum12.Val4, val);
val = enumCheck((int)Class1.Enum12.Val5c, 1121);
val = enumCheck((int)Class1.Enum12.Val6c, val);
val = 0;
val = enumCheck((int)Class1.Enum13.Val1, 1131);
val = enumCheck((int)Class1.Enum13.Val2, 1132);
val = enumCheck((int)Class1.Enum13.Val3, val);
val = enumCheck((int)Class1.Enum13.Val4, val);
val = enumCheck((int)Class1.Enum13.Val5d, 1131);
val = enumCheck((int)Class1.Enum13.Val6d, val);
val = 0;
val = enumCheck((int)Class1.Enum14.Val1, 1141);
val = enumCheck((int)Class1.Enum14.Val2, 1142);
val = enumCheck((int)Class1.Enum14.Val3, val);
val = enumCheck((int)Class1.Enum14.Val4, val);
val = enumCheck((int)Class1.Enum14.Val5e, 1141);
val = enumCheck((int)Class1.Enum14.Val6e, val);
val = 0;
val = enumCheck((int)Class1.Struct1.Enum12.Val1, 3121);
val = enumCheck((int)Class1.Struct1.Enum12.Val2, 3122);
val = enumCheck((int)Class1.Struct1.Enum12.Val3, val);
val = enumCheck((int)Class1.Struct1.Enum12.Val4, val);
val = enumCheck((int)Class1.Struct1.Enum12.Val5f, 3121);
val = enumCheck((int)Class1.Struct1.Enum12.Val6f, val);
val = 0;
val = enumCheck((int)Class1.Struct1.Enum13.Val1, 3131);
val = enumCheck((int)Class1.Struct1.Enum13.Val2, 3132);
val = enumCheck((int)Class1.Struct1.Enum13.Val3, val);
val = enumCheck((int)Class1.Struct1.Enum13.Val4, val);
val = 0;
val = enumCheck((int)Class1.Struct1.Enum14.Val1, 3141);
val = enumCheck((int)Class1.Struct1.Enum14.Val2, 3142);
val = enumCheck((int)Class1.Struct1.Enum14.Val3, val);
val = enumCheck((int)Class1.Struct1.Enum14.Val4, val);
val = enumCheck((int)Class1.Struct1.Enum14.Val5g, 3141);
val = enumCheck((int)Class1.Struct1.Enum14.Val6g, val);
val = 0;
val = enumCheck((int)Class2.Enum12.Val1, 2121);
val = enumCheck((int)Class2.Enum12.Val2, 2122);
val = enumCheck((int)Class2.Enum12.Val3, val);
val = enumCheck((int)Class2.Enum12.Val4, val);
val = enumCheck((int)Class2.Enum12.Val5h, 2121);
val = enumCheck((int)Class2.Enum12.Val6h, val);
val = 0;
val = enumCheck((int)Class2.Enum13.Val1, 2131);
val = enumCheck((int)Class2.Enum13.Val2, 2132);
val = enumCheck((int)Class2.Enum13.Val3, val);
val = enumCheck((int)Class2.Enum13.Val4, val);
val = enumCheck((int)Class2.Enum13.Val5i, 2131);
val = enumCheck((int)Class2.Enum13.Val6i, val);
val = 0;
val = enumCheck((int)Class2.Enum14.Val1, 2141);
val = enumCheck((int)Class2.Enum14.Val2, 2142);
val = enumCheck((int)Class2.Enum14.Val3, val);
val = enumCheck((int)Class2.Enum14.Val4, val);
val = enumCheck((int)Class2.Enum14.Val5j, 2141);
val = enumCheck((int)Class2.Enum14.Val6j, val);
val = 0;
val = enumCheck((int)Class2.Struct1.Enum12.Val1, 4121);
val = enumCheck((int)Class2.Struct1.Enum12.Val2, 4122);
val = enumCheck((int)Class2.Struct1.Enum12.Val3, val);
val = enumCheck((int)Class2.Struct1.Enum12.Val4, val);
val = enumCheck((int)Class2.Struct1.Enum12.Val5k, 4121);
val = enumCheck((int)Class2.Struct1.Enum12.Val6k, val);
val = 0;
val = enumCheck((int)Class2.Struct1.Enum13.Val1, 4131);
val = enumCheck((int)Class2.Struct1.Enum13.Val2, 4132);
val = enumCheck((int)Class2.Struct1.Enum13.Val3, val);
val = enumCheck((int)Class2.Struct1.Enum13.Val4, val);
val = enumCheck((int)Class2.Struct1.Enum13.Val5l, 4131);
val = enumCheck((int)Class2.Struct1.Enum13.Val6l, val);
val = 0;
val = enumCheck((int)Class2.Struct1.Enum14.Val1, 4141);
val = enumCheck((int)Class2.Struct1.Enum14.Val2, 4142);
val = enumCheck((int)Class2.Struct1.Enum14.Val3, val);
val = enumCheck((int)Class2.Struct1.Enum14.Val4, val);
val = enumCheck((int)Class2.Struct1.Enum14.Val5m, 4141);
val = enumCheck((int)Class2.Struct1.Enum14.Val6m, val);
Class1 class1 = new Class1();
enumCheck((int)class1.class1Test1(Enum1.Val5a), 13);
enumCheck((int)class1.class1Test2(Class1.Enum12.Val5c), 1121);
enumCheck((int)class1.class1Test3(Class1.Struct1.Enum12.Val5f), 3121);
enumCheck((int)cpp11_strongly_typed_enumerations.globalTest1(Enum1.Val5a), 13);
enumCheck((int)cpp11_strongly_typed_enumerations.globalTest2(Class1.Enum12.Val5c), 1121);
enumCheck((int)cpp11_strongly_typed_enumerations.globalTest3(Class1.Struct1.Enum12.Val5f), 3121);
}
}
using System;
using cpp17_nested_namespacesNamespace;
public class cpp17_nested_namespaces_runme
{
static void Main()
{
new A1Struct().A1Method();
new B1Struct().B1Method();
new C1Struct().C1Method();
cpp17_nested_namespaces.createA1Struct().A1Method();
cpp17_nested_namespaces.createB1Struct().B1Method();
cpp17_nested_namespaces.createC1Struct().C1Method();
new B2Struct().B2Method();
new C2Struct().C2Method();
cpp17_nested_namespaces.createB2Struct().B2Method();
cpp17_nested_namespaces.createC2Struct().C2Method();
new B3Struct().B3Method();
new C3Struct().C3Method();
cpp17_nested_namespaces.createB3Struct().B3Method();
cpp17_nested_namespaces.createC3Struct().C3Method();
}
}
using System;
using cpp17_nspace_nested_namespacesNamespace;
public class cpp17_nspace_nested_namespaces_runme
{
static void Main()
{
new cpp17_nspace_nested_namespacesNamespace.A1.A1Struct().A1Method();
new cpp17_nspace_nested_namespacesNamespace.A1.B1.B1Struct().B1Method();
new cpp17_nspace_nested_namespacesNamespace.A1.B1.C1.C1Struct().C1Method();
cpp17_nspace_nested_namespaces.createA1Struct().A1Method();
cpp17_nspace_nested_namespaces.createB1Struct().B1Method();
cpp17_nspace_nested_namespaces.createC1Struct().C1Method();
new cpp17_nspace_nested_namespacesNamespace.A2.B2.B2Struct().B2Method();
new cpp17_nspace_nested_namespacesNamespace.A2.B2.C2.C2Struct().C2Method();
cpp17_nspace_nested_namespaces.createB2Struct().B2Method();
cpp17_nspace_nested_namespaces.createC2Struct().C2Method();
new cpp17_nspace_nested_namespacesNamespace.A3.B3.B3Struct().B3Method();
new cpp17_nspace_nested_namespacesNamespace.A3.B3.C3.C3Struct().C3Method();
cpp17_nspace_nested_namespaces.createB3Struct().B3Method();
cpp17_nspace_nested_namespaces.createC3Struct().C3Method();
}
}
using System;
using System.Reflection;
using System.ComponentModel;
using csharp_attributesNamespace;
public class runme
{
static void Main()
{
// Custom attributes typemap tests
//
// cstype typemap attributechecks
//
// Global function cstype typemap attributes check
Type globaltype = typeof(csharp_attributes);
{
MethodInfo member = (MethodInfo)globaltype.GetMember("GlobalFunction")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
throw new Exception("No IntOut attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
if (parameter.Name != "myInt")
throw new Exception("Incorrect parameter name");
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntInAttribute))
throw new Exception("Expecting IntIn attribute");
}
// Constant - cstype typemap attributes check
{
MemberInfo member = (MemberInfo)globaltype.GetMember("TESTMACRO")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
throw new Exception("No IntOut attribute for " + member.Name);
}
// Non-static method cstype typemap attributes check
Type type = typeof(Stations);
{
MethodInfo member = (MethodInfo)type.GetMember("Reading")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
throw new Exception("No IntOut attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
if (parameter.Name != "myInt")
throw new Exception("Incorrect parameter name");
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntInAttribute))
throw new Exception("Expecting IntIn attribute");
}
// Static method cstype typemap attributes check
{
MethodInfo member = (MethodInfo)type.GetMember("Swindon")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
throw new Exception("No IntOut attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
if (parameter.Name != "myInt")
throw new Exception("Incorrect parameter name");
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntInAttribute))
throw new Exception("Expecting IntIn attribute");
}
// Constructor cstype typemap attributes check
{
ConstructorInfo member = (ConstructorInfo)type.GetConstructors()[0];
ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
if (parameter.Name != "myInt")
throw new Exception("Incorrect parameter name");
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntInAttribute))
throw new Exception("Expecting IntIn attribute");
}
//
// imtype typemap attributechecks
//
// Global function imtype typemap attributes check
Type imclasstype = typeof(csharp_attributesPINVOKE);
{
MethodInfo member = (MethodInfo)imclasstype.GetMember("GlobalFunction")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
throw new Exception("No IntegerOut attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[0]; // checking 1st parameter
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntegerInAttribute))
throw new Exception("Expecting IntegerIn attribute");
}
// Constant - imtype typemap attributes check
{
MethodInfo member = (MethodInfo)imclasstype.GetMember("TESTMACRO_get")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
throw new Exception("No IntegerOut attribute for " + member.Name);
}
// Non-static method imtype typemap attributes check
{
MethodInfo member = (MethodInfo)imclasstype.GetMember("Stations_Reading")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
throw new Exception("No IntegerOut attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[1]; // checking 2nd parameter
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntegerInAttribute))
throw new Exception("Expecting IntegerIn attribute");
}
// Static method imtype typemap attributes check
{
MethodInfo member = (MethodInfo)imclasstype.GetMember("Stations_Swindon")[0];
if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
throw new Exception("No IntegerOut attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[0]; // checking 1st parameter
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(IntegerInAttribute))
throw new Exception("Expecting IntegerIn attribute");
}
//
// attributes feature
//
Type moretype = typeof(MoreStations);
// Constructor attributes feature check
{
ConstructorInfo member = (ConstructorInfo)moretype.GetConstructors()[0];
if (Attribute.GetCustomAttribute(member, typeof(InterCity1Attribute)) == null)
throw new Exception("MoreStations::MoreStations attribute failed");
}
// Non-static method attributes feature check
{
MethodInfo member = (MethodInfo)moretype.GetMember("Chippenham")[0];
if (Attribute.GetCustomAttribute(member, typeof(InterCity2Attribute)) == null)
throw new Exception("MoreStations::Chippenham attribute failed");
}
// Static method attributes feature check
{
MethodInfo member = (MethodInfo)moretype.GetMember("Bath")[0];
if (Attribute.GetCustomAttribute(member, typeof(InterCity3Attribute)) == null)
throw new Exception("MoreStations::Bath attribute failed");
}
// Non-static member variable attributes feature check
{
PropertyInfo member = (PropertyInfo)moretype.GetProperty("Bristol");
if (Attribute.GetCustomAttribute(member, typeof(InterCity4Attribute)) == null)
throw new Exception("MoreStations::Bristol attribute failed");
}
// Static member variable attributes feature check
{
PropertyInfo member = (PropertyInfo)moretype.GetProperty("WestonSuperMare");
if (Attribute.GetCustomAttribute(member, typeof(InterCity5Attribute)) == null)
throw new Exception("MoreStations::Bristol attribute failed");
}
// Global function attributes feature check
{
MethodInfo member = (MethodInfo)globaltype.GetMember("Paddington")[0];
if (Attribute.GetCustomAttribute(member, typeof(InterCity7Attribute)) == null)
throw new Exception("MoreStations::Paddington attribute failed");
}
// Global variables attributes feature check
{
PropertyInfo member = (PropertyInfo)globaltype.GetProperty("DidcotParkway");
if (Attribute.GetCustomAttribute(member, typeof(InterCity8Attribute)) == null)
throw new Exception("MoreStations::Paddington attribute failed");
}
//
// csattribute typemaps
//
// Class csattribute typemap
{
Object[] attribs = moretype.GetCustomAttributes(true);
Eurostar1Attribute tgv = (Eurostar1Attribute)attribs[0];
if (tgv == null)
throw new Exception("No attribute for MoreStations");
}
// Nested enum csattribute typemap
{
MemberInfo member = (MemberInfo)moretype.GetMember("Wales")[0];
if (Attribute.GetCustomAttribute(member, typeof(Eurostar2Attribute)) == null)
throw new Exception("No attribute for " + member.Name);
}
// Enum value attributes
Type walesType = typeof(MoreStations.Wales);
{
MemberInfo member = (MemberInfo)walesType.GetMember("Cardiff")[0];
DescriptionAttribute attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(System.ComponentModel.DescriptionAttribute));
if (attribute == null)
throw new Exception("No attribute for " + member.Name);
if (attribute.Description != "Cardiff city station")
throw new Exception("Incorrect attribute value for " + member.Name);
}
{
MemberInfo member = (MemberInfo)walesType.GetMember("Swansea")[0];
DescriptionAttribute attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(System.ComponentModel.DescriptionAttribute));
if (attribute == null)
throw new Exception("No attribute for " + member.Name);
if (attribute.Description != "Swansea city station")
throw new Exception("Incorrect attribute value for " + member.Name);
}
// Enum csattribute typemap
{
Type cymrutype = typeof(Cymru);
Object[] attribs = cymrutype.GetCustomAttributes(true);
Eurostar3Attribute tgv = (Eurostar3Attribute)attribs[0];
if (tgv == null)
throw new Exception("No attribute for Cymru");
}
// No runtime test for directorinattributes and directoroutattributes
}
}
// Custom attribute classes
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class IntInAttribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class IntOutAttribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class IntegerInAttribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class IntegerOutAttribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity1Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity2Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity3Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity4Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity5Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity6Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity7Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class InterCity8Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class Eurostar1Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class Eurostar2Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class Eurostar3Attribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class ThreadSafeAttribute : Attribute {
public ThreadSafeAttribute(bool safe) {}
public ThreadSafeAttribute() {}
}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class DirectorIntegerOutAttribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class DirectorIntegerInAttribute : Attribute {}
using System;
using System.Reflection;
using csharp_director_typemapsNamespace;
public class csharp_director_typemaps_runme {
class CSharpDirectorTypemaps_InStreamDerived : InStream
{
private int constant;
public CSharpDirectorTypemaps_InStreamDerived(int constant) { this.constant = constant; }
public override int Read(global::System.IntPtr buf, int len, out int readLen) {
readLen = (buf == global::System.IntPtr.Zero) ? -len - constant : len + constant;
return readLen;
}
public override int Write(global::System.IntPtr buf, int len, out int writeLen) {
writeLen = (buf == global::System.IntPtr.Zero) ? -len - constant : len + constant;
return writeLen;
}
}
public static void Main() {
int outLen = -1;
int k = 100;
int j = 23;
InStream instream = new CSharpDirectorTypemaps_InStreamDerived(k);
{
int ret = csharp_director_typemaps.callRead(instream, InStream.getCPtr(instream).Handle, j, out outLen);
Assert(outLen, j + k);
Assert(ret, j + k);
}
{
int ret = csharp_director_typemaps.callRead(instream, global::System.IntPtr.Zero, j, out outLen);
Assert(outLen, -j - k);
Assert(ret, -j - k);
}
{
int ret = csharp_director_typemaps.callWrite(instream, InStream.getCPtr(instream).Handle, j, out outLen);
Assert(outLen, j + k);
Assert(ret, j + k);
}
{
int ret = csharp_director_typemaps.callWrite(instream, global::System.IntPtr.Zero, j, out outLen);
Assert(outLen, -j - k);
Assert(ret, -j - k);
}
}
private static void Assert(int i1, int i2) {
if (i1 != i2)
throw new Exception("assertion failure. " + i1 + " != " + i2);
}
}
using System;
using System.Threading;
using csharp_exceptionsNamespace;
public class runme
{
static void Main()
{
// %exception tests
try {
csharp_exceptions.ThrowByValue();
throw new Exception("ThrowByValue not working");
} catch (DivideByZeroException) {
}
try {
csharp_exceptions.ThrowByReference();
throw new Exception("ThrowByReference not working");
} catch (DivideByZeroException) {
}
// %csnothrowexception
csharp_exceptions.NoThrowException();
csharp_exceptions.NullReference(new Ex("should not throw"));
// exception specifications
bool testFailed = false;
try {
csharp_exceptions.ExceptionSpecificationValue();
testFailed = true;
} catch (ApplicationException) {
}
if (testFailed) throw new Exception("ExceptionSpecificationValue not working");
try {
csharp_exceptions.ExceptionSpecificationReference();
testFailed = true;
} catch (ApplicationException) {
}
if (testFailed) throw new Exception("ExceptionSpecificationReference not working");
try {
csharp_exceptions.ExceptionSpecificationString();
testFailed = true;
} catch (ApplicationException e) {
if (e.Message != "ExceptionSpecificationString") throw new Exception("ExceptionSpecificationString unexpected message: " + e.Message);
}
if (testFailed) throw new Exception("ExceptionSpecificationString not working");
try {
csharp_exceptions.ExceptionSpecificationInteger();
testFailed = true;
} catch (ApplicationException) {
}
if (testFailed) throw new Exception("ExceptionSpecificationInteger not working");
// null reference exceptions
try {
csharp_exceptions.NullReference(null);
throw new Exception("NullReference not working");
} catch (ArgumentNullException) {
}
try {
csharp_exceptions.NullValue(null);
throw new Exception("NullValue not working");
} catch (ArgumentNullException) {
}
// enums
try {
csharp_exceptions.ExceptionSpecificationEnumValue();
testFailed = true;
} catch (ApplicationException) {
}
if (testFailed) throw new Exception("ExceptionSpecificationEnumValue not working");
try {
csharp_exceptions.ExceptionSpecificationEnumReference();
testFailed = true;
} catch (ApplicationException) {
}
if (testFailed) throw new Exception("ExceptionSpecificationEnumReference not working");
// std::string
try {
csharp_exceptions.NullStdStringValue(null);
throw new Exception("NullStdStringValue not working");
} catch (ArgumentNullException) {
}
try {
csharp_exceptions.NullStdStringReference(null);
throw new Exception("NullStdStringReference not working");
} catch (ArgumentNullException) {
}
try {
csharp_exceptions.ExceptionSpecificationStdStringValue();
testFailed = true;
} catch (ApplicationException e) {
if (e.Message != "ExceptionSpecificationStdStringValue") throw new Exception("ExceptionSpecificationStdStringValue unexpected message: " + e.Message);
}
if (testFailed) throw new Exception("ExceptionSpecificationStdStringValue not working");
try {
csharp_exceptions.ExceptionSpecificationStdStringReference();
testFailed = true;
} catch (ApplicationException e) {
if (e.Message != "ExceptionSpecificationStdStringReference") throw new Exception("ExceptionSpecificationStdStringReference unexpected message: " + e.Message);
}
if (testFailed) throw new Exception("ExceptionSpecificationStdStringReference not working");
// Memory leak check (The C++ exception stack was never unwound in the original approach to throwing exceptions from unmanaged code)
try {
csharp_exceptions.MemoryLeakCheck();
throw new Exception("MemoryLeakCheck not working");
} catch (DivideByZeroException) {
}
if (Counter.count != 0) throw new Exception("Memory leaks when throwing exception. count: " + Counter.count);
// test exception pending in the csconstruct typemap
try {
new constructor(null);
throw new Exception("constructor 1 not working");
} catch (ArgumentNullException) {
}
try {
new constructor();
throw new Exception("constructor 2 not working");
} catch (ApplicationException) {
}
// test exception pending in the csout typemaps
try {
csharp_exceptions.ushorttest();
throw new Exception("csout not working");
} catch (IndexOutOfRangeException) {
}
// test exception pending in the csvarout/csvarin typemaps and canthrow attribute in unmanaged code typemaps (1) global variables
// 1) global variables
int numberout = 0;
try {
csharp_exceptions.numberin = -1;
throw new Exception("global csvarin not working");
} catch (IndexOutOfRangeException) {
}
csharp_exceptions.numberin = 5;
if (csharp_exceptions.numberin != 5)
throw new Exception("global numberin not 5");
csharp_exceptions.numberout = 20;
try {
numberout += csharp_exceptions.numberout;
throw new Exception("global csvarout not working");
} catch (IndexOutOfRangeException) {
}
// 2) static member variables
try {
InOutStruct.staticnumberin = -1;
throw new Exception("static csvarin not working");
} catch (IndexOutOfRangeException) {
}
InOutStruct.staticnumberin = 5;
if (InOutStruct.staticnumberin != 5)
throw new Exception("static staticnumberin not 5");
InOutStruct.staticnumberout = 20;
try {
numberout += InOutStruct.staticnumberout;
throw new Exception("static csvarout not working");
} catch (IndexOutOfRangeException) {
}
// 3) member variables
InOutStruct io = new InOutStruct();
try {
io.numberin = -1;
throw new Exception("member csvarin not working");
} catch (IndexOutOfRangeException) {
}
io.numberin = 5;
if (io.numberin != 5)
throw new Exception("member numberin not 5");
io.numberout = 20;
try {
numberout += io.numberout;
throw new Exception("member csvarout not working");
} catch (IndexOutOfRangeException) {
}
// test SWIG_exception macro - it must return from unmanaged code without executing any further unmanaged code
try {
csharp_exceptions.exceptionmacrotest(-1);
throw new Exception("exception macro not working");
} catch (IndexOutOfRangeException) {
}
if (csharp_exceptions.exception_macro_run_flag)
throw new Exception("exceptionmacrotest was executed");
// test all the types of exceptions
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedApplicationException);
throw new Exception("ApplicationException not caught");
} catch (ApplicationException e) {
if (e.Message != "msg") throw new Exception("ApplicationException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArithmeticException);
throw new Exception("ArithmeticException not caught");
} catch (ArithmeticException e) {
if (e.Message != "msg") throw new Exception("ArithmeticException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedDivideByZeroException);
throw new Exception("DivideByZeroException not caught");
} catch (DivideByZeroException e) {
if (e.Message != "msg") throw new Exception("DivideByZeroException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIndexOutOfRangeException);
throw new Exception("IndexOutOfRangeException not caught");
} catch (IndexOutOfRangeException e) {
if (e.Message != "msg") throw new Exception("IndexOutOfRangeException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedInvalidOperationException);
throw new Exception("InvalidOperationException not caught");
} catch (InvalidOperationException e) {
if (e.Message != "msg") throw new Exception("InvalidOperationException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIOException);
throw new Exception("IOException not caught");
} catch (System.IO.IOException e) {
if (e.Message != "msg") throw new Exception("IOException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedNullReferenceException);
throw new Exception("NullReferenceException not caught");
} catch (NullReferenceException e) {
if (e.Message != "msg") throw new Exception("NullReferenceException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOutOfMemoryException);
throw new Exception("OutOfMemoryException not caught");
} catch (OutOfMemoryException e) {
if (e.Message != "msg") throw new Exception("OutOfMemoryException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOverflowException);
throw new Exception("OverflowException not caught");
} catch (OverflowException e) {
if (e.Message != "msg") throw new Exception("OverflowException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedSystemException);
throw new Exception("SystemException not caught");
} catch (SystemException e) {
if (e.Message != "msg") throw new Exception("SystemException msg incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentException);
throw new Exception("ArgumentException not caught");
} catch (ArgumentException e) {
if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentException msg incorrect");
if (e.ParamName != "parm") throw new Exception("ArgumentException parm incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentNullException);
throw new Exception("ArgumentNullException not caught");
} catch (ArgumentNullException e) {
if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentNullException msg incorrect");
if (e.ParamName != "parm") throw new Exception("ArgumentNullException parm incorrect");
}
try {
csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentOutOfRangeException);
throw new Exception("ArgumentOutOfRangeException not caught");
} catch (ArgumentOutOfRangeException e) {
if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentOutOfRangeException msg incorrect");
if (e.ParamName != "parm") throw new Exception("ArgumentOutOfRangeException parm incorrect");
}
// exceptions in multiple threads test
{
ThrowsClass throwsClass = new ThrowsClass(1234.5678);
const int NUM_THREADS = 8;
Thread[] threads = new Thread[NUM_THREADS];
TestThread[] testThreads = new TestThread[NUM_THREADS];
// invoke the threads
for (int i=0; i<NUM_THREADS; i++) {
testThreads[i] = new TestThread(throwsClass, i);
threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
threads[i].Start();
}
// wait for the threads to finish
for (int i=0; i<NUM_THREADS; i++) {
threads[i].Join();
}
for (int i=0; i<NUM_THREADS; i++) {
if (testThreads[i].Failed) throw new Exception("Test Failed");
}
}
// test inner exceptions
try {
csharp_exceptions.InnerExceptionTest();
throw new Exception("InnerExceptionTest exception not caught");
} catch (InvalidOperationException e) {
if (e.Message != "My OuterException message") throw new Exception("OuterException msg incorrect");
if (e.InnerException.Message != "My InnerException message") throw new Exception("InnerException msg incorrect");
}
}
public static string CRLF = "\r\n"; // Some CLR implementations use a CRLF instead of just CR
}
public class TestThread {
private int threadId;
private ThrowsClass throwsClass;
public bool Failed;
public TestThread(ThrowsClass t, int id) {
throwsClass = t;
threadId = id;
}
public void Run() {
Failed = false;
try {
for (int i=0; i<6000; i++) { // run test for about 10 seconds on a 1GHz machine (Mono)
try {
throwsClass.ThrowException(i);
throw new Exception("No exception thrown");
} catch (ArgumentOutOfRangeException e) {
String expectedMessage = "caught:" + i + "\n" + "Parameter name: input";
if (e.Message.Replace(runme.CRLF,"\n") != expectedMessage)
throw new Exception("Exception message incorrect. Expected:\n[" +
expectedMessage + "]\n" + "Received:\n[" +
e.Message + "]");
if (e.ParamName != "input")
throw new Exception("Exception ParamName incorrect. Expected:\n[input]\n" + "Received:\n[" + e.ParamName + "]");
if (e.InnerException != null)
throw new Exception("Unexpected inner exception");
}
if (throwsClass.dub != 1234.5678) // simple check which attempts to catch memory corruption
throw new Exception("throwsException.dub = " + throwsClass.dub + " expected: 1234.5678");
}
} catch (Exception e) {
Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message + "\n TestThread Inner stack trace: " + e.StackTrace);
Failed = true;
}
}
}
using System;
using csharp_lib_arrays_boolNamespace;
public class runme
{
static void Main()
{
{
bool[] source = { true, false, false, true, false, true, true, false };
bool[] target = new bool[ source.Length ];
csharp_lib_arrays_bool.myArrayCopyUsingFixedArraysBool( source, target, target.Length );
CompareArrays(source, target, "bool[] INPUT/OUTPUT Fixed");
}
{
bool[] source = { true, false, false, true, false, true, true, false };
bool[] target = { false, true, true, false, true, false, false, true };
csharp_lib_arrays_bool.myArraySwapUsingFixedArraysBool( source, target, target.Length );
for (int i=0; i<target.Length; ++i)
target[i] = !target[i];
CompareArrays(source, target, "bool[] INOUT");
}
if( runtimeIsMono() )
{
// Console.Error.WriteLine("Tests are running on mono, failing bool[] tests skipped");
// See Mono bug report https://github.com/mono/mono/issues/15592
return;
}
{
bool[] source = { true, false, false, true, false, true, true, false };
bool[] target = new bool[ source.Length ];
if( !csharp_lib_arrays_bool.checkBoolArrayCorrect( source, source.Length ) )
{
throw new Exception("bool[] INPUT incorrect");
}
csharp_lib_arrays_bool.myArrayCopyBool( source, target, target.Length );
CompareArrays(source, target, "bool[] INPUT/OUTPUT");
}
{
bool[] source = { true, false, false, true, false, true, true, false };
bool[] target = { false, true, true, false, true, false, false, true };
csharp_lib_arrays_bool.myArraySwapBool( source, target, target.Length );
for (int i=0; i<target.Length; ++i)
target[i] = !target[i];
CompareArrays(source, target, "bool[] INOUT");
}
}
static void CompareArrays<T>( T[] a, T[] b, string testName )
{
if (a.Length != b.Length)
throw new Exception("size mismatch");
for(int i=0; i<a.Length; ++i) {
if (a[i].Equals(b[i]) == false) {
Console.Error.WriteLine("C# Array mismatch: " + testName);
Console.Error.WriteLine("a:");
PrintArray(a);
Console.Error.WriteLine("b:");
PrintArray(b);
throw new Exception("element mismatch");
}
}
}
static void PrintArray<T>( T[] a )
{
foreach ( T i in a )
Console.Error.Write( "{0} ", i );
Console.Error.WriteLine();
}
static bool runtimeIsMono()
{
return Type.GetType ("Mono.Runtime") != null;
}
}
using System;
using csharp_lib_arraysNamespace;
public class runme
{
static void Main()
{
{
int[] source = { 1, 2, 3, 4, 5 };
int[] target = new int[ source.Length ];
csharp_lib_arrays.myArrayCopy( source, target, target.Length );
CompareArrays(source, target);
}
{
int[] source = { 1, 2, 3, 4, 5 };
int[] target = new int[ source.Length ];
csharp_lib_arrays.myArrayCopyUsingFixedArrays( source, target, target.Length );
CompareArrays(source, target);
}
{
int[] source = { 1, 2, 3, 4, 5 };
int[] target = new int[] { 6, 7, 8, 9, 10 };
csharp_lib_arrays.myArraySwap( source, target, target.Length );
for (int i=0; i<target.Length; ++i)
target[i] += 5;
CompareArrays(source, target);
}
{
int[] source = { 1, 2, 3, 4, 5 };
int[] target = new int[] { 6, 7, 8, 9, 10 };
csharp_lib_arrays.myArraySwapUsingFixedArrays( source, target, target.Length );
for (int i=0; i<target.Length; ++i)
target[i] += 5;
CompareArrays(source, target);
}
}
static void CompareArrays( int[] a, int[] b )
{
if (a.Length != b.Length)
throw new Exception("size mismatch");
for(int i=0; i<a.Length; ++i) {
if (a[i] != b[i]) {
Console.Error.WriteLine("a:");
PrintArray(a);
Console.Error.WriteLine("b:");
PrintArray(b);
throw new Exception("element mismatch");
}
}
}
static void PrintArray( int[] a )
{
foreach ( int i in a )
Console.Error.Write( "{0} ", i );
Console.Error.WriteLine();
}
}
using System;
using System.Reflection;
using csharp_prepostNamespace;
public class csharp_prepost_runme {
class PrePost3_Derived : PrePost3
{
public PrePost3_Derived(){}
public override void method(ref double[] vpre, DoubleVector vpost)
{
Assert(vpre[0], 1.0);
vpre[0] = 2.0;
Assert(vpost.Count, 2);
vpost.Add(1.0);
}
public override int methodint(ref double[] vpre, DoubleVector vpost)
{
method(ref vpre, vpost);
return vpost.Count;
}
}
public static void Main() {
{
double[] v;
csharp_prepost.globalfunction(out v);
Assert(v.Length, 3);
Assert(v[0], 0.0);
Assert(v[1], 1.1);
Assert(v[2], 2.2);
}
{
double[] v;
new PrePostTest(out v);
Assert(v.Length, 2);
Assert(v[0], 3.3);
Assert(v[1], 4.4);
}
{
double[] v;
PrePostTest p = new PrePostTest();
p.method(out v);
Assert(v.Length, 2);
Assert(v[0], 5.5);
Assert(v[1], 6.6);
}
{
double[] v;
PrePostTest.staticmethod(out v);
Assert(v.Length, 2);
Assert(v[0], 7.7);
Assert(v[1], 8.8);
}
{
PrePost3_Derived p = new PrePost3_Derived();
double[] vpre = new double[] { 1.0 };
DoubleVector vpost = new DoubleVector();
vpost.Add(3.0);
vpost.Add(4.0);
p.method(ref vpre, vpost);
Assert(vpre[0], 2.0);
Assert(vpost.Count, 3);
}
{
PrePost3_Derived p = new PrePost3_Derived();
double[] vpre = new double[] { 1.0 };
DoubleVector vpost = new DoubleVector();
vpost.Add(3.0);
vpost.Add(4.0);
int size = p.methodint(ref vpre, vpost);
Assert(vpre[0], 2.0);
Assert(vpost.Count, 3);
Assert(size, 3);
}
// Check attributes are generated for the constructor helper function
{
CsinAttributes c = new CsinAttributes(5);
Assert(c.getVal(), 500);
Type type = typeof(CsinAttributes);
{
MethodInfo member = (MethodInfo)type.GetMember("SwigConstructCsinAttributes", BindingFlags.NonPublic | BindingFlags.Static)[0];
if (Attribute.GetCustomAttribute(member, typeof(CustomIntPtrAttribute)) == null)
throw new Exception("No CustomIntPtr attribute for " + member.Name);
ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
if (parameter.Name != "val")
throw new Exception("Incorrect parameter name");
Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
if (attribute.GetType() != typeof(CustomIntAttribute))
throw new Exception("Expecting CustomInt attribute");
}
}
// Dates
{
// pre post typemap attributes example
System.DateTime dateIn = new System.DateTime(2011, 4, 13);
System.DateTime dateOut = new System.DateTime();
// Note in calls below, dateIn remains unchanged and dateOut
// is set to a new value by the C++ call
csharp_prepostNamespace.Action action = new csharp_prepostNamespace.Action(dateIn, out dateOut);
if (dateOut != dateIn)
throw new Exception("dates wrong");
dateIn = new System.DateTime(2012, 7, 14);
action.doSomething(dateIn, out dateOut);
if (dateOut != dateIn)
throw new Exception("dates wrong");
System.DateTime refDate = new System.DateTime(1999, 12, 31);
if (csharp_prepost.ImportantDate != refDate)
throw new Exception("dates wrong");
refDate = new System.DateTime(1999, 12, 31);
csharp_prepost.ImportantDate = refDate;
System.DateTime importantDate = csharp_prepost.ImportantDate;
if (importantDate != refDate)
throw new Exception("dates wrong");
System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
csharp_prepost.addYears(ref christmasEve, 10);
if (christmasEve != new System.DateTime(2010, 12, 24))
throw new Exception("dates wrong");
Person person = new Person();
person.Birthday = christmasEve;
if (person.Birthday != christmasEve)
throw new Exception("dates wrong");
}
}
private static void Assert(double d1, double d2) {
if (d1 != d2)
throw new Exception("assertion failure. " + d1 + " != " + d2);
}
}
// Custom attribute classes
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class CustomIntAttribute : Attribute {}
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class CustomIntPtrAttribute : Attribute {}
using System;
using System.Threading;
using csharp_typemapsNamespace;
public class runme
{
static void Main()
{
// Test the C# types customisation by modifying the default char * typemaps to return a single char
Things things = new Things();
System.Text.StringBuilder initialLetters = new System.Text.StringBuilder();
char myChar = things.start("boo");
initialLetters.Append(myChar);
myChar = Things.stop("hiss");
initialLetters.Append(myChar);
myChar = csharp_typemaps.partyon("off");
initialLetters.Append(myChar);
if (initialLetters.ToString() != "bho")
throw new Exception("initial letters failed");
// $csinput expansion
csharp_typemaps.myInt = 1;
try {
csharp_typemaps.myInt = -1;
throw new Exception("oops");
} catch (ApplicationException) {
}
// Eager garbage collector test
{
const int NUM_THREADS = 8;
Thread[] threads = new Thread[NUM_THREADS];
TestThread[] testThreads = new TestThread[NUM_THREADS];
// invoke the threads
for (int i=0; i<NUM_THREADS; i++) {
testThreads[i] = new TestThread(i);
threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
threads[i].Start();
}
// wait for the threads to finish
for (int i=0; i<NUM_THREADS; i++) {
threads[i].Join();
}
for (int i=0; i<NUM_THREADS; i++) {
if (testThreads[i].Failed) throw new Exception("Test Failed");
}
}
}
}
public class TestThread {
private int threadId;
public bool Failed;
public TestThread(int id) {
threadId = id;
}
public void Run() {
Failed = false;
try {
// Older versions of SWIG used IntPtr instead of HandleRef to hold the underlying
// C++ pointer, so this test would (usually) fail as the garbage collector would
// sometimes collect the Number class while it was being used in unmanaged code
for (int i=0; i<5000; i++) { // run test for a few seconds
{
Obj obj = new Obj();
Number n = new Number(i);
Number triple = obj.triple(n);
if (triple.Value != i*3)
throw new ApplicationException("triple failed: " + triple.Value);
}
{
Obj obj = new Obj();
Number n = new Number(i);
Number times6 = obj.times6(n);
if (times6.Value != i*6)
throw new ApplicationException("times6 failed: " + times6.Value);
}
{
Obj obj = new Obj();
Number n = new Number(i);
Number times9 = obj.times9(n);
if (times9.Value != i*9)
throw new ApplicationException("times9 failed: " + times9.Value);
}
{
Number n = new Number(i);
Number quadruple = csharp_typemaps.quadruple(n);
if (quadruple.Value != i*4)
throw new ApplicationException("quadruple failed: " + quadruple.Value);
}
{
Number n = new Number(i);
Number times8 = csharp_typemaps.times8(n);
if (times8.Value != i*8)
throw new ApplicationException("times8 failed: " + times8.Value);
}
{
Number n = new Number(i);
Number times12 = csharp_typemaps.times12(n);
if (times12.Value != i*12)
throw new ApplicationException("times12 failed: " + times12.Value);
}
}
} catch (Exception e) {
Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message);
Failed = true;
}
}
}
using System;
using default_argsNamespace;
public class runme
{
static void Main()
{
if (default_args.anonymous() != 7771)
throw new Exception("anonymous (1) failed");
if (default_args.anonymous(1234) != 1234)
throw new Exception("anonymous (2) failed");
if (default_args.booltest() != true)
throw new Exception("booltest (1) failed");
if (default_args.booltest(true) != true)
throw new Exception("booltest (2) failed");
if (default_args.booltest(false) != false)
throw new Exception("booltest (3) failed");
EnumClass ec = new EnumClass();
if (ec.blah() != true)
throw new Exception("EnumClass failed");
if (default_args.casts1() != null)
throw new Exception("casts1 failed");
if (default_args.casts2() != "Hello")
throw new Exception("casts2 failed");
if (default_args.casts1("Ciao") != "Ciao")
throw new Exception("casts1 not default failed");
if (default_args.chartest1() != 'x')
throw new Exception("chartest1 failed");
if (default_args.chartest2() != '\0')
throw new Exception("chartest2 failed");
if (default_args.chartest1('y') != 'y')
throw new Exception("chartest1 not default failed");
if (default_args.chartest1('y') != 'y')
throw new Exception("chartest1 not default failed");
if (default_args.reftest1() != 42)
throw new Exception("reftest1 failed");
if (default_args.reftest1(400) != 400)
throw new Exception("reftest1 not default failed");
if (default_args.reftest2() != "hello")
throw new Exception("reftest2 failed");
// rename
Foo foo = new Foo();
foo.newname();
foo.newname(10);
foo.renamed3arg(10, 10.0);
foo.renamed2arg(10);
foo.renamed1arg();
// exception specifications
try {
default_args.exceptionspec();
throw new Exception("exceptionspec 1 failed");
} catch (Exception) {
}
try {
default_args.exceptionspec(-1);
throw new Exception("exceptionspec 2 failed");
} catch (Exception) {
}
try {
default_args.exceptionspec(100);
throw new Exception("exceptionspec 3 failed");
} catch (Exception) {
}
Except ex = new Except(false);
try {
ex.exspec();
throw new Exception("exspec 1 failed");
} catch (Exception) {
}
try {
ex.exspec(-1);
throw new Exception("exspec 2 failed");
} catch (Exception) {
}
try {
ex.exspec(100);
throw new Exception("exspec 3 failed");
} catch (Exception) {
}
try {
ex = new Except(true);
throw new Exception("Except constructor 1 failed");
} catch (Exception) {
}
try {
ex = new Except(true, -2);
throw new Exception("Except constructor 2 failed");
} catch (Exception) {
}
// Default parameters in static class methods
if (Statics.staticmethod() != 10+20+30)
throw new Exception("staticmethod 1 failed");
if (Statics.staticmethod(100) != 100+20+30)
throw new Exception("staticmethod 2 failed");
if (Statics.staticmethod(100,200,300) != 100+200+300)
throw new Exception("staticmethod 3 failed");
Tricky tricky = new Tricky();
if (tricky.privatedefault() != 200)
throw new Exception("privatedefault failed");
if (tricky.protectedint() != 2000)
throw new Exception("protectedint failed");
if (tricky.protecteddouble() != 987.654)
throw new Exception("protecteddouble failed");
if (tricky.functiondefault() != 500)
throw new Exception("functiondefault failed");
if (tricky.contrived() != 'X')
throw new Exception("contrived failed");
if (default_args.constructorcall().val != -1)
throw new Exception("constructorcall test 1 failed");
if (default_args.constructorcall(new Klass(2222)).val != 2222)
throw new Exception("constructorcall test 2 failed");
if (default_args.constructorcall(new Klass()).val != -1)
throw new Exception("constructorcall test 3 failed");
// const methods
ConstMethods cm = new ConstMethods();
if (cm.coo() != 20)
throw new Exception("coo test 1 failed");
if (cm.coo(1.0) != 20)
throw new Exception("coo test 2 failed");
}
}
using System;
using default_constructorNamespace;
public class runme
{
static void Main()
{
// calling protected destructor test
try {
using (G g = new G()) {
}
throw new Exception("Protected destructor exception should have been thrown");
} catch (MethodAccessException) {
}
}
}
using System;
using director_alternatingNamespace;
public class director_alternating_runme {
public static void Main() {
if (director_alternating.getBar().id() != director_alternating.idFromGetBar())
throw new Exception("idFromGetBar failed");
}
}
using System;
namespace director_basicNamespace {
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
director_basic_MyFoo a = new director_basic_MyFoo();
if (a.ping() != "director_basic_MyFoo::ping()") {
throw new Exception ( "a.ping()" );
}
if (a.pong() != "Foo::pong();director_basic_MyFoo::ping()") {
throw new Exception ( "a.pong()" );
}
Foo b = new Foo();
if (b.ping() != "Foo::ping()") {
throw new Exception ( "b.ping()" );
}
if (b.pong() != "Foo::pong();Foo::ping()") {
throw new Exception ( "b.pong()" );
}
A1 a1 = new A1(1, false);
a1.Dispose();
{
MyOverriddenClass my = new MyOverriddenClass();
my.expectNull = true;
if (MyClass.call_pmethod(my, null) != null)
throw new Exception("null pointer marshalling problem");
Bar myBar = new Bar();
my.expectNull = false;
Bar myNewBar = MyClass.call_pmethod(my, myBar);
if (myNewBar == null)
throw new Exception("non-null pointer marshalling problem");
myNewBar.x = 10;
// Low level implementation check
// my.testSwigDerivedClassHasMethod();
// These should not call the C# implementations as they are not overridden
int v;
v = MyClass.call_nonVirtual(my);
if (v != 100) throw new Exception("call_nonVirtual broken() " + v);
v = MyClass.call_nonOverride(my);
if (v != 101) throw new Exception("call_nonOverride broken() " + v);
// A mix of overridden and non-overridden
MyClassEnd myend = new MyClassEnd();
MyClass mc = myend;
v = mc.nonVirtual();
if (v != 202) throw new Exception("mc.nonVirtual() broken " + v);
v = MyClass.call_nonVirtual(mc);
if (v != 202) throw new Exception("call_nonVirtual(mc) broken " + v);
v = MyClass.call_nonVirtual(myend);
if (v != 202) throw new Exception("call_nonVirtual(myend) broken" + v);
v = MyClass.call_nonOverride(mc);
if (v != 101) throw new Exception("call_nonOverride(mc) broken" + v);
v = MyClass.call_nonOverride(myend);
if (v != 101) throw new Exception("call_nonOverride(myend) broken" + v);
}
}
}
class director_basic_MyFoo : Foo {
public director_basic_MyFoo() : base() {
}
public override string ping() {
return "director_basic_MyFoo::ping()";
}
}
class MyOverriddenClass : MyClass {
public bool expectNull = false;
public bool nonNullReceived = false;
public override Bar pmethod(Bar b) {
if ( expectNull && (b != null) )
throw new Exception("null not received as expected");
return b;
}
public new bool nonVirtual() {
throw new Exception("non-virtual overrides virtual method");
}
public new virtual bool nonOverride() {
throw new Exception("non-override overrides virtual method");
}
}
class MyClassMiddle : MyClass {
public override int nonVirtual() {
return 202;
}
}
class MyClassEnd : MyClassMiddle {
public new bool nonVirtual() {
throw new Exception("non-virtual overrides virtual method");
}
public new virtual bool nonOverride() {
throw new Exception("non-override overrides virtual method");
}
}
}
/*
This test demonstrates director classes when the types are classes.
Shown are virtual function calls which use classes passed by:
- Value
- Reference
- Pointer
as both parameters and return values.
The test also demonstrates directors used with:
- method overloading
- default parameters
Note: Methods with default parameters that call up from C++ cannot call
the overloaded C# methods, see DefaultParms method.
Expected output if PrintDebug enabled:
------------ Start ------------
Base - Val(444.555)
Base - Ref(444.555)
Base - Ptr(444.555)
Base - ConstPtrRef(444.555)
Base - FullyOverloaded(int 10)
Base - FullyOverloaded(bool 1)
Base - SemiOverloaded(int -678)
Base - SemiOverloaded(bool 1)
Base - DefaultParms(10, 2.2)
Base - DefaultParms(10, 1.1)
--------------------------------
Derived - Val(444.555)
Derived - Ref(444.555)
Derived - Ptr(444.555)
Derived - ConstPtrRef(444.555)
Derived - FullyOverloaded(int 10)
Derived - FullyOverloaded(bool 1)
Derived - SemiOverloaded(int -678)
Base - SemiOverloaded(bool 1)
Derived - DefaultParms(10, 2.2)
Derived - DefaultParms(10, 1.1)
--------------------------------
CSharpDerived - Val(444.555)
CSharpDerived - Ref(444.555)
CSharpDerived - Ptr(444.555)
CSharpDerived - ConstPtrRef(444.555)
CSharpDerived - FullyOverloaded(int 10)
CSharpDerived - FullyOverloaded(bool True)
CSharpDerived - SemiOverloaded(-678)
Base - SemiOverloaded(bool 1)
CSharpDerived - DefaultParms(10, 2.2)
CSharpDerived - DefaultParms(10, 1.1)
------------ Finish ------------
*/
using System;
namespace director_classesNamespace {
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
if (director_classes.PrintDebug) Console.WriteLine("------------ Start ------------");
Caller myCaller = new Caller();
// test C++ base class
using (Base myBase = new Base(100.0))
{
makeCalls(myCaller, myBase);
}
if (director_classes.PrintDebug) Console.WriteLine("--------------------------------");
// test vanilla C++ wrapped derived class
using (Base myBase = new Derived(200.0))
{
makeCalls(myCaller, myBase);
}
if (director_classes.PrintDebug) Console.WriteLine("--------------------------------");
// test director / C# derived class
using (Base myBase = new CSharpDerived(300.0))
{
makeCalls(myCaller, myBase);
}
if (director_classes.PrintDebug) Console.WriteLine("------------ Finish ------------");
}
void makeCalls(Caller myCaller, Base myBase)
{
string NAMESPACE = "director_classesNamespace.";
myCaller.set(myBase);
DoubleHolder dh = new DoubleHolder(444.555);
// Class pointer, reference and pass by value tests
if (myCaller.ValCall(dh).val != dh.val) throw new Exception("failed");
if (myCaller.RefCall(dh).val != dh.val) throw new Exception("failed");
if (myCaller.PtrCall(dh).val != dh.val) throw new Exception("failed");
if (myCaller.ConstPtrRefCall(dh).val != dh.val) throw new Exception("failed");
// Fully overloaded method test (all methods in base class are overloaded)
if (NAMESPACE + myCaller.FullyOverloadedCall(10) != myBase.GetType() + "::FullyOverloaded(int)") throw new Exception("failed");
if (NAMESPACE + myCaller.FullyOverloadedCall(true) != myBase.GetType() + "::FullyOverloaded(bool)") throw new Exception("failed");
// Semi overloaded method test (some methods in base class are overloaded)
if (NAMESPACE + myCaller.SemiOverloadedCall(-678) != myBase.GetType() + "::SemiOverloaded(int)") throw new Exception("failed");
if (myCaller.SemiOverloadedCall(true) != "Base" + "::SemiOverloaded(bool)") throw new Exception("failed");
// Default parameters methods test
if (NAMESPACE + myCaller.DefaultParmsCall(10, 2.2) != myBase.GetType() + "::DefaultParms(int, double)") throw new Exception("failed");
if (myBase.GetType() == typeof(CSharpDerived)) { // special handling for C# derived classes, there is no way to do this any other way
if (NAMESPACE + myCaller.DefaultParmsCall(10) != myBase.GetType() + "::DefaultParms(int, double)") throw new Exception("failed");
} else {
if (NAMESPACE + myCaller.DefaultParmsCall(10) != myBase.GetType() + "::DefaultParms(int)") throw new Exception("failed");
}
myCaller.reset();
}
}
public class CSharpDerived : Base
{
public CSharpDerived(double dd)
: base(dd)
{
}
public override DoubleHolder Val(DoubleHolder x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - Val({0})", x.val);
return x;
}
public override DoubleHolder Ref(DoubleHolder x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - Ref({0})", x.val);
return x;
}
public override DoubleHolder Ptr(DoubleHolder x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - Ptr({0})", x.val);
return x;
}
public override DoubleHolder ConstPtrRef(DoubleHolder x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - ConstPtrRef({0})", x.val);
return x;
}
public override String FullyOverloaded(int x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - FullyOverloaded(int {0})", x);
return "CSharpDerived::FullyOverloaded(int)";
}
public override String FullyOverloaded(bool x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - FullyOverloaded(bool {0})", x);
return "CSharpDerived::FullyOverloaded(bool)";
}
// Note no SemiOverloaded(bool x) method
public override String SemiOverloaded(int x)
{
String ret = "CSharpDerived::SemiOverloaded(int)";
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - SemiOverloaded({0})", x);
return ret;
}
public override String DefaultParms(int x, double y)
{
String ret = "CSharpDerived::DefaultParms(int, double)";
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - DefaultParms({0}, {1})", x, y);
return ret;
}
// Note the following method can never be called from unmanaged code.
// It is here only for code that calls it directly from managed code.
// But should always be defined to ensure behaviour is consistent
// independent of where DefaultParsms is called from (managed or unmanaged code).
// Note this method can never be called from unmanaged code
public override String DefaultParms(int x)
{
if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - DefaultParms({0})", x);
return DefaultParms(x, 1.1/*use C++ default here*/);
}
}
}
using System;
namespace director_classicNamespace {
public class runme
{
static void Main()
{
{
Person person = new Person();
check(person, "Person");
person.Dispose();
}
{
Person person = new Child();
check(person, "Child");
person.Dispose();
}
{
Person person = new GrandChild();
check(person, "GrandChild");
person.Dispose();
}
{
Person person = new TargetLangPerson();
check(person, "TargetLangPerson");
person.Dispose();
}
{
Person person = new TargetLangChild();
check(person, "TargetLangChild");
person.Dispose();
}
{
Person person = new TargetLangGrandChild();
check(person, "TargetLangGrandChild");
person.Dispose();
}
// Semis - don't override id() in target language
{
Person person = new TargetLangSemiPerson();
check(person, "Person");
person.Dispose();
}
{
Person person = new TargetLangSemiChild();
check(person, "Child");
person.Dispose();
}
{
Person person = new TargetLangSemiGrandChild();
check(person, "GrandChild");
person.Dispose();
}
// Orphans - don't override id() in C++
{
Person person = new OrphanPerson();
check(person, "Person");
person.Dispose();
}
{
Person person = new OrphanChild();
check(person, "Child");
person.Dispose();
}
{
Person person = new TargetLangOrphanPerson();
check(person, "TargetLangOrphanPerson");
person.Dispose();
}
{
Person person = new TargetLangOrphanChild();
check(person, "TargetLangOrphanChild");
person.Dispose();
}
// Duals - id() makes an upcall to the base id()
{
Person person = new TargetLangDualPerson();
check(person, "TargetLangDualPerson + Person");
person.Dispose();
}
{
Person person = new TargetLangDualChild();
check(person, "TargetLangDualChild + Child");
person.Dispose();
}
{
Person person = new TargetLangDualGrandChild();
check(person, "TargetLangDualGrandChild + GrandChild");
person.Dispose();
}
// Mix Orphans and Duals
{
Person person = new TargetLangDualOrphanPerson();
check(person, "TargetLangDualOrphanPerson + Person");
person.Dispose();
}
{
Person person = new TargetLangDualOrphanChild();
check(person, "TargetLangDualOrphanChild + Child");
person.Dispose();
}
}
static void check(Person person, String expected) {
String ret;
// Normal target language polymorphic call
ret = person.id();
if (debug)
Console.WriteLine(ret);
if (ret != expected)
throw new Exception("Failed. Received: " + ret + " Expected: " + expected);
// Polymorphic call from C++
Caller caller = new Caller();
caller.setCallback(person);
ret = caller.call();
if (debug)
Console.WriteLine(ret);
if (ret != expected)
throw new Exception("Failed. Received: " + ret + " Expected: " + expected);
// Polymorphic call of object created in target language and passed to C++ and back again
Person baseclass = caller.baseClass();
ret = baseclass.id();
if (debug)
Console.WriteLine(ret);
if (ret != expected)
throw new Exception("Failed. Received: " + ret + " Expected: " + expected);
caller.resetCallback();
if (debug)
Console.WriteLine("----------------------------------------");
}
static bool debug = false;
}
public class TargetLangPerson : Person
{
public TargetLangPerson()
: base()
{
}
public override String id()
{
String identifier = "TargetLangPerson";
return identifier;
}
}
public class TargetLangChild : Child
{
public TargetLangChild()
: base()
{
}
public override String id()
{
String identifier = "TargetLangChild";
return identifier;
}
}
public class TargetLangGrandChild : GrandChild
{
public TargetLangGrandChild()
: base()
{
}
public override String id()
{
String identifier = "TargetLangGrandChild";
return identifier;
}
}
// Semis - don't override id() in target language
public class TargetLangSemiPerson : Person
{
public TargetLangSemiPerson()
: base()
{
}
// No id() override
}
public class TargetLangSemiChild : Child
{
public TargetLangSemiChild()
: base()
{
}
// No id() override
}
public class TargetLangSemiGrandChild : GrandChild
{
public TargetLangSemiGrandChild()
: base()
{
}
// No id() override
}
// Orphans - don't override id() in C++
class TargetLangOrphanPerson : OrphanPerson
{
public TargetLangOrphanPerson()
: base()
{
}
public override String id()
{
String identifier = "TargetLangOrphanPerson";
return identifier;
}
}
class TargetLangOrphanChild : OrphanChild
{
public TargetLangOrphanChild()
: base()
{
}
public override String id()
{
String identifier = "TargetLangOrphanChild";
return identifier;
}
}
// Duals - id() makes an upcall to the base id()
class TargetLangDualPerson : Person
{
public TargetLangDualPerson()
: base()
{
}
public override String id()
{
String identifier = "TargetLangDualPerson + " + base.id();
return identifier;
}
}
class TargetLangDualChild : Child
{
public TargetLangDualChild()
: base()
{
}
public override String id()
{
String identifier = "TargetLangDualChild + " + base.id();
return identifier;
}
}
class TargetLangDualGrandChild : GrandChild
{
public TargetLangDualGrandChild()
: base()
{
}
public override String id()
{
String identifier = "TargetLangDualGrandChild + " + base.id();
return identifier;
}
}
// Mix Orphans and Duals
class TargetLangDualOrphanPerson : OrphanPerson
{
public TargetLangDualOrphanPerson()
: base()
{
}
public override String id()
{
String identifier = "TargetLangDualOrphanPerson + " + base.id();
return identifier;
}
}
class TargetLangDualOrphanChild : OrphanChild
{
public TargetLangDualOrphanChild()
: base()
{
}
public override String id()
{
String identifier = "TargetLangDualOrphanChild + " + base.id();
return identifier;
}
}
}
using System;
namespace director_ignoreNamespace {
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
// Just check the classes can be instantiated and other methods work as expected
DIgnoresDerived a = new DIgnoresDerived();
if (a.Triple(5) != 15)
throw new Exception("Triple failed");
DAbstractIgnoresDerived b = new DAbstractIgnoresDerived();
if (b.Quadruple(5) != 20)
throw new Exception("Quadruple failed");
}
}
class DIgnoresDerived : DIgnores
{
public DIgnoresDerived() : base()
{
}
// These will give a warning if the %ignore is not working
public virtual int OverloadedMethod(int n, int xoffset, int yoffset) { return 0; }
public virtual int OverloadedMethod(int n, int xoffset) { return 0; }
public virtual int OverloadedMethod(int n) { return 0; }
public virtual int OverloadedProtectedMethod(int n, int xoffset, int yoffset) { return 0; }
public virtual int OverloadedProtectedMethod(int n, int xoffset) { return 0; }
public virtual int OverloadedProtectedMethod(int n) { return 0; }
}
class DAbstractIgnoresDerived : DAbstractIgnores
{
public DAbstractIgnoresDerived() : base()
{
}
// These will give a warning if the %ignore is not working
public virtual int OverloadedMethod(int n, int xoffset, int yoffset) { return 0; }
public virtual int OverloadedMethod(int n, int xoffset) { return 0; }
public virtual int OverloadedMethod(int n) { return 0; }
public virtual int OverloadedProtectedMethod(int n, int xoffset, int yoffset) { return 0; }
public virtual int OverloadedProtectedMethod(int n, int xoffset) { return 0; }
public virtual int OverloadedProtectedMethod(int n) { return 0; }
}
}
using System;
using director_nspaceNamespace;
public class bools_runme {
public static void Main() {
}
}
class director_nspace_MyBarFoo : director_nspaceNamespace.TopLevel.Bar.Foo {
public override String ping() {
return "director_nspace_MyBarFoo.ping();";
}
public override String pong() {
return "director_nspace_MyBarFoo.pong();" + ping();
}
public override String fooBar(director_nspaceNamespace.TopLevel.Bar.FooBar fooBar) {
return fooBar.FooBarDo();
}
public override director_nspaceNamespace.TopLevel.Bar.Foo makeFoo() {
return new director_nspaceNamespace.TopLevel.Bar.Foo();
}
public override director_nspaceNamespace.TopLevel.Bar.FooBar makeFooBar() {
return new director_nspaceNamespace.TopLevel.Bar.FooBar();
}
}
using System;
using director_pass_by_valueNamespace;
public class runme
{
private static void WaitForGC()
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(10);
}
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
Caller caller = new Caller();
caller.call_virtualMethod(new director_pass_by_value_Derived());
{
int countdown = 5;
while (true) {
WaitForGC();
if (--countdown == 0)
break;
};
}
// bug was the passByVal 'global' object was destroyed after the call to virtualMethod had finished.
int ret = runme.passByVal.getVal();
if (ret != 0x12345678)
throw new Exception("Bad return value, got " + ret.ToString("x"));
}
public static PassedByValue passByVal;
}
class director_pass_by_value_Derived : DirectorPassByValueAbstractBase {
public override void virtualMethod(PassedByValue pbv) {
runme.passByVal = pbv;
}
}
/*
This test program shows a C# class CSharpDerived inheriting from Base. Three types of classes are created
and the virtual methods called to demonstrate:
1) Wide variety of primitive types
2) Calling methods with zero, one or more parameters
3) Director methods that are not overridden in C#
4) Director classes that are not overridden at all in C#, ie non-director behaviour is as expected for director classes
5) Inheritance hierarchy using director methods
6) Return types working as well as parameters
The Caller class is a tester class, which calls the virtual functions from C++.
*/
using System;
using director_primitivesNamespace;
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
if (director_primitives.PrintDebug) Console.WriteLine("------------ Start ------------ ");
Caller myCaller = new Caller();
// test C++ base class
using (Base myBase = new Base(100.0))
{
makeCalls(myCaller, myBase);
}
if (director_primitives.PrintDebug) Console.WriteLine("--------------------------------");
// test vanilla C++ wrapped derived class
using (Base myBase = new Derived(200.0))
{
makeCalls(myCaller, myBase);
}
if (director_primitives.PrintDebug) Console.WriteLine("--------------------------------");
// test director / C# derived class
using (Base myBase = new CSharpDerived(300.0))
{
makeCalls(myCaller, myBase);
}
if (director_primitives.PrintDebug) Console.WriteLine("------------ Finish ------------ ");
}
void makeCalls(Caller myCaller, Base myBase)
{
myCaller.set(myBase);
myCaller.NoParmsMethodCall();
if (myCaller.BoolMethodCall(true) != true) throw new Exception("failed");
if (myCaller.BoolMethodCall(false) != false) throw new Exception("failed");
if (myCaller.IntMethodCall(-123) != -123) throw new Exception("failed");
if (myCaller.UIntMethodCall(123) != 123) throw new Exception("failed");
if (myCaller.FloatMethodCall((float)-123.456) != (float)-123.456) throw new Exception("failed");
if (myCaller.CharPtrMethodCall("test string") != "test string") throw new Exception("failed");
if (myCaller.ConstCharPtrMethodCall("another string") != "another string") throw new Exception("failed");
if (myCaller.EnumMethodCall(HShadowMode.HShadowHard) != HShadowMode.HShadowHard) throw new Exception("failed");
myCaller.ManyParmsMethodCall(true, -123, 123, (float)123.456, "test string", "another string", HShadowMode.HShadowHard);
myCaller.NotOverriddenMethodCall();
myCaller.reset();
}
}
public class CSharpDerived : Base
{
public CSharpDerived(double dd)
: base(dd)
{
}
public override void NoParmsMethod()
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - NoParmsMethod()");
}
public override bool BoolMethod(bool x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - BoolMethod({0})", x);
return x;
}
public override int IntMethod(int x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - IntMethod({0})", x);
return x;
}
public override uint UIntMethod(uint x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
return x;
}
public override float FloatMethod(float x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - FloatMethod({0})", x);
return x;
}
public override string CharPtrMethod(string x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - CharPtrMethod({0})", x);
return x;
}
public override string ConstCharPtrMethod(string x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - ConstCharPtrMethod({0})", x);
return x;
}
public override HShadowMode EnumMethod(HShadowMode x)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - EnumMethod({0})", x);
return x;
}
public override void ManyParmsMethod(bool b, int i, uint u, float f, string c, string cc, HShadowMode h)
{
if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - ManyParmsMethod({0}, {1}, {2}, {3}, {4}, {5}, {6})", b, i, u, f, c, cc, h);
}
}
using System;
namespace director_protectedNamespace {
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
Bar b = new Bar();
Foo f = b.create();
FooBar fb = new FooBar();
FooBar2 fb2 = new FooBar2();
FooBar3 fb3 = new FooBar3();
String s;
s = fb.used();
if ( s != ("Foo::pang();Bar::pong();Foo::pong();FooBar::ping();"))
throw new Exception("bad FooBar::used" + " - " + s);
s = fb2.used();
if ( s != ("FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();"))
throw new Exception("bad FooBar2::used");
s = b.pong();
if ( s != ("Bar::pong();Foo::pong();Bar::ping();"))
throw new Exception("bad Bar::pong");
s = f.pong();
if ( s != ("Bar::pong();Foo::pong();Bar::ping();"))
throw new Exception("bad Foo::pong");
s = fb.pong();
if ( s != ("Bar::pong();Foo::pong();FooBar::ping();"))
throw new Exception("bad FooBar::pong");
// if (fb3.cheer() != "FooBar3::cheer();")
// throw new Exception("bad fb3::cheer");
if (fb2.callping() != "FooBar2::ping();")
throw new Exception("bad fb2.callping");
if (fb2.callcheer() != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();")
throw new Exception("bad fb2.callcheer");
if (fb3.callping() != "Bar::ping();")
throw new Exception("bad fb3.callping");
if (fb3.callcheer() != "FooBar3::cheer();")
throw new Exception("bad fb3.callcheer");
}
}
class FooBar : Bar
{
public FooBar() : base()
{
}
protected override String ping()
{
return "FooBar::ping();";
}
}
class FooBar2 : Bar
{
public FooBar2() : base()
{
}
protected override String ping()
{
return "FooBar2::ping();";
}
protected override String pang()
{
return "FooBar2::pang();";
}
}
class FooBar3 : Bar
{
public FooBar3() : base()
{
}
protected override String cheer()
{
return "FooBar3::cheer();";
}
}
}
using director_smartptrNamespace;
using System;
public class runme
{
private class director_smartptr_MyBarFoo : Foo
{
public override string ping()
{
return "director_smartptr_MyBarFoo.ping()";
}
public override string pong()
{
return "director_smartptr_MyBarFoo.pong();" + ping();
}
public override string upcall(FooBar fooBarPtr)
{
return "override;" + fooBarPtr.FooBarDo();
}
public override Foo makeFoo()
{
return new Foo();
}
}
private class director_smartptr_MyBarFooDerived : FooDerived
{
public override string ping()
{
return "director_smartptr_MyBarFooDerived.ping()";
}
public override string pong()
{
return "director_smartptr_MyBarFooDerived.pong();" + ping();
}
public override string upcall(FooBar fooBarPtr)
{
return "overrideDerived;" + fooBarPtr.FooBarDo();
}
public override Foo makeFoo()
{
return new Foo();
}
}
private static void check(string got, string expected)
{
if (got != expected)
throw new ApplicationException("Failed, got: " + got + " expected: " + expected);
}
static void Main()
{
FooBar fooBar = new FooBar();
Foo myBarFoo = new director_smartptr_MyBarFoo();
check(myBarFoo.ping(), "director_smartptr_MyBarFoo.ping()");
check(Foo.callPong(myBarFoo), "director_smartptr_MyBarFoo.pong();director_smartptr_MyBarFoo.ping()");
check(Foo.callUpcall(myBarFoo, fooBar), "override;Bar::Foo2::Foo2Bar()");
Foo myFoo = myBarFoo.makeFoo();
check(myFoo.pong(), "Foo::pong();Foo::ping()");
check(Foo.callPong(myFoo), "Foo::pong();Foo::ping()");
check(myFoo.upcall(new FooBar()), "Bar::Foo2::Foo2Bar()");
Foo myFoo2 = new Foo().makeFoo();
check(myFoo2.pong(), "Foo::pong();Foo::ping()");
check(Foo.callPong(myFoo2), "Foo::pong();Foo::ping()");
FooDerived myBarFooDerived = new director_smartptr_MyBarFooDerived();
check(myBarFooDerived.ping(), "director_smartptr_MyBarFooDerived.ping()");
check(FooDerived.callPong(myBarFooDerived), "director_smartptr_MyBarFooDerived.pong();director_smartptr_MyBarFooDerived.ping()");
check(FooDerived.callUpcall(myBarFooDerived, fooBar), "overrideDerived;Bar::Foo2::Foo2Bar()");
}
}
using System;
using director_stringNamespace;
public class runme
{
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
String s;
director_string_A c = new director_string_A("hi");
for (int i=0; i<3; i++) {
s = c.call_get(i);
Object ii = i;
if (s != ii.ToString()) throw new Exception("director_string_A.get(" + i + ") failed. Got:" + s);
}
director_string_B b = new director_string_B("hello");
s = b.call_get_first();
if (s != "director_string_B.get_first") throw new Exception("call_get_first() failed");
s = b.call_get(0);
if (s != "director_string_B.get: hello") throw new Exception("get(0) failed");
}
}
class director_string_B : A {
public director_string_B(String first) : base(first) {
}
public override String get_first() {
return "director_string_B.get_first";
}
public override String get(int n) {
return "director_string_B.get: " + base.get(n);
}
}
class director_string_A : A {
public director_string_A(String first) : base(first) {
}
public override String get(int n) {
Object nn = n;
return nn.ToString();
}
}
using System;
using director_voidNamespace;
public class runme
{
private static void WaitForGC()
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(10);
}
static void Main()
{
runme r = new runme();
r.run();
}
void run()
{
Caller caller = new Caller();
{
DirectorVoidPointer dvp = new DirectorVoidPointer(5);
int x = caller.callVirtualIn(dvp, 6);
if (x != 106)
throw new Exception("Fail1 should be 106, got " + x);
global::System.IntPtr ptr = dvp.nonVirtualVoidPtrOut();
x = Caller.VoidToInt(ptr);
if (x != 106)
throw new Exception("Fail2 should be 106, got " + x);
x = Caller.VoidToInt(dvp.voidPtrOut());
if (x != 106)
throw new Exception("Fail3 should be 106, got " + x);
}
{
DirectorVoidPointer dvp = new director_void_VoidPointer(5);
int x = caller.callVirtualIn(dvp, 6);
if (x != 12)
throw new Exception("Fail1 should be 12, got " + x);
global::System.IntPtr ptr = dvp.nonVirtualVoidPtrOut();
x = Caller.VoidToInt(ptr);
if (x != 25)
throw new Exception("Fail2 should be 25, got " + x);
x = Caller.VoidToInt(dvp.voidPtrOut());
if (x != 1234)
throw new Exception("Fail3 should be 1234, got " + x);
}
{
DirectorVoidPointer dvp = new DirectorVoidPointer(10);
int x = caller.callVirtualOut(dvp);
if (x != 10)
throw new Exception("Bad1 should be 10, got " + x);
global::System.IntPtr ptr = dvp.nonVirtualVoidPtrOut();
x = dvp.nonVirtualVoidPtrIn(ptr);
if (x != 110)
throw new Exception("Bad2 should be 110, got " + x);
}
{
DirectorVoidPointer dvp = new director_void_VoidPointer(10);
int x = caller.callVirtualOut(dvp);
if (x != 1234)
throw new Exception("Bad3 should be 1234, got " + x);
global::System.IntPtr ptr = dvp.nonVirtualVoidPtrOut();
x = dvp.nonVirtualVoidPtrIn(ptr);
if (x != 1334)
throw new Exception("Bad4 should be 1334, got " + x);
}
}
}
class director_void_VoidPointer : DirectorVoidPointer {
public director_void_VoidPointer(int num) : base(num*num) {
}
public override int voidPtrIn(global::System.IntPtr p) {
return Caller.VoidToInt(p) * 2;
}
public override global::System.IntPtr voidPtrOut() {
setNewValue(1234);
return nonVirtualVoidPtrOut();
}
}
using System;
using enum_forwardNamespace;
public class runme {
static void Main() {
ForwardEnum1 f1 = enum_forward.get_enum1();
f1 = enum_forward.test_function1(f1);
ForwardEnum2 f2 = enum_forward.get_enum2();
f2 = enum_forward.test_function2(f2);
ForwardEnum3 f3 = enum_forward.get_enum3();
f3 = enum_forward.test_function3(f3);
}
}
using System;
using enum_thoroughNamespace;
public class runme {
static void Main() {
{
// Anonymous enums
int i = enum_thorough.AnonEnum1;
if (enum_thorough.ReallyAnInteger != 200) throw new Exception("Test Anon 1 failed");
i += enum_thorough.AnonSpaceEnum1;
i += AnonStruct.AnonStructEnum1;
}
{
colour red = colour.red;
enum_thorough.colourTest1(red);
enum_thorough.colourTest2(red);
enum_thorough.colourTest3(red);
enum_thorough.colourTest4(red);
enum_thorough.myColour = red;
}
{
SpeedClass s = new SpeedClass();
SpeedClass.speed speed = SpeedClass.speed.slow;
if (s.speedTest1(speed) != speed) throw new Exception("speedTest 1 failed");
if (s.speedTest2(speed) != speed) throw new Exception("speedTest 2 failed");
if (s.speedTest3(speed) != speed) throw new Exception("speedTest 3 failed");
if (s.speedTest4(speed) != speed) throw new Exception("speedTest 4 failed");
if (s.speedTest5(speed) != speed) throw new Exception("speedTest 5 failed");
if (s.speedTest6(speed) != speed) throw new Exception("speedTest 6 failed");
if (s.speedTest7(speed) != speed) throw new Exception("speedTest 7 failed");
if (s.speedTest8(speed) != speed) throw new Exception("speedTest 8 failed");
if (enum_thorough.speedTest1(speed) != speed) throw new Exception("speedTest Global 1 failed");
if (enum_thorough.speedTest2(speed) != speed) throw new Exception("speedTest Global 2 failed");
if (enum_thorough.speedTest3(speed) != speed) throw new Exception("speedTest Global 3 failed");
if (enum_thorough.speedTest4(speed) != speed) throw new Exception("speedTest Global 4 failed");
if (enum_thorough.speedTest5(speed) != speed) throw new Exception("speedTest Global 5 failed");
}
{
SpeedClass s = new SpeedClass();
SpeedClass.speed slow = SpeedClass.speed.slow;
SpeedClass.speed lightning = SpeedClass.speed.lightning;
if (s.mySpeedtd1 != slow) throw new Exception("mySpeedtd1 1 failed");
if ((int)s.mySpeedtd1 != 10) throw new Exception("mySpeedtd1 2 failed");
s.mySpeedtd1 = lightning;
if (s.mySpeedtd1 != lightning) throw new Exception("mySpeedtd1 3 failed");
if ((int)s.mySpeedtd1 != 31) throw new Exception("mySpeedtd1 4 failed");
}
{
if (enum_thorough.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest 1 failed");
}
{
twonames val = twonames.TwoNames2;
if (enum_thorough.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
if (enum_thorough.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
if (enum_thorough.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
}
{
TwoNamesStruct t = new TwoNamesStruct();
TwoNamesStruct.twonames val = TwoNamesStruct.twonames.TwoNamesStruct1;
if (t.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
if (t.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
if (t.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
}
{
namedanonspace val = namedanonspace.NamedAnonSpace2;
if (enum_thorough.namedanonspaceTest1(val) != val) throw new Exception("namedanonspaceTest 1 failed");
if (enum_thorough.namedanonspaceTest2(val) != val) throw new Exception("namedanonspaceTest 2 failed");
if (enum_thorough.namedanonspaceTest3(val) != val) throw new Exception("namedanonspaceTest 3 failed");
if (enum_thorough.namedanonspaceTest4(val) != val) throw new Exception("namedanonspaceTest 4 failed");
}
{
TemplateClassInt t = new TemplateClassInt();
TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
if (t.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest 1 failed");
if (t.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest 2 failed");
if (t.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest 3 failed");
if (t.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest 4 failed");
if (t.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest 5 failed");
if (t.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest 6 failed");
if (t.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest 7 failed");
if (t.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest 8 failed");
if (t.scientistsTest9(galileo) != galileo) throw new Exception("scientistsTest 9 failed");
// if (t.scientistsTestA(galileo) != galileo) throw new Exception("scientistsTest A failed");
if (t.scientistsTestB(galileo) != galileo) throw new Exception("scientistsTest B failed");
// if (t.scientistsTestC(galileo) != galileo) throw new Exception("scientistsTest C failed");
if (t.scientistsTestD(galileo) != galileo) throw new Exception("scientistsTest D failed");
if (t.scientistsTestE(galileo) != galileo) throw new Exception("scientistsTest E failed");
if (t.scientistsTestF(galileo) != galileo) throw new Exception("scientistsTest F failed");
if (t.scientistsTestG(galileo) != galileo) throw new Exception("scientistsTest G failed");
if (t.scientistsTestH(galileo) != galileo) throw new Exception("scientistsTest H failed");
if (t.scientistsTestI(galileo) != galileo) throw new Exception("scientistsTest I failed");
if (t.scientistsTestJ(galileo) != galileo) throw new Exception("scientistsTest J failed");
if (enum_thorough.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest Global 1 failed");
if (enum_thorough.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest Global 2 failed");
if (enum_thorough.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest Global 3 failed");
if (enum_thorough.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest Global 4 failed");
if (enum_thorough.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest Global 5 failed");
if (enum_thorough.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest Global 6 failed");
if (enum_thorough.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest Global 7 failed");
if (enum_thorough.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest Global 8 failed");
}
{
TClassInt t = new TClassInt();
TClassInt.scientists bell = TClassInt.scientists.bell;
TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
if (t.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest 1 failed");
if (t.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest 2 failed");
if (t.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest 3 failed");
if (t.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest 4 failed");
if (t.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest 5 failed");
if (t.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest 6 failed");
if (t.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest 7 failed");
if (t.scientistsNameTest8(bell) != bell) throw new Exception("scientistsNameTest 8 failed");
if (t.scientistsNameTest9(bell) != bell) throw new Exception("scientistsNameTest 9 failed");
// if (t.scientistsNameTestA(bell) != bell) throw new Exception("scientistsNameTest A failed");
if (t.scientistsNameTestB(bell) != bell) throw new Exception("scientistsNameTest B failed");
// if (t.scientistsNameTestC(bell) != bell) throw new Exception("scientistsNameTest C failed");
if (t.scientistsNameTestD(bell) != bell) throw new Exception("scientistsNameTest D failed");
if (t.scientistsNameTestE(bell) != bell) throw new Exception("scientistsNameTest E failed");
if (t.scientistsNameTestF(bell) != bell) throw new Exception("scientistsNameTest F failed");
if (t.scientistsNameTestG(bell) != bell) throw new Exception("scientistsNameTest G failed");
if (t.scientistsNameTestH(bell) != bell) throw new Exception("scientistsNameTest H failed");
if (t.scientistsNameTestI(bell) != bell) throw new Exception("scientistsNameTest I failed");
if (t.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest 1 failed");
if (t.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest 2 failed");
if (t.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest 3 failed");
if (t.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest 4 failed");
if (t.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest 5 failed");
if (t.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest 6 failed");
if (t.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest 7 failed");
if (t.scientistsOtherTest1(galileo) != galileo) throw new Exception("scientistsOtherTest 1 failed");
if (t.scientistsOtherTest2(galileo) != galileo) throw new Exception("scientistsOtherTest 2 failed");
if (t.scientistsOtherTest3(galileo) != galileo) throw new Exception("scientistsOtherTest 3 failed");
if (t.scientistsOtherTest4(galileo) != galileo) throw new Exception("scientistsOtherTest 4 failed");
if (t.scientistsOtherTest5(galileo) != galileo) throw new Exception("scientistsOtherTest 5 failed");
if (t.scientistsOtherTest6(galileo) != galileo) throw new Exception("scientistsOtherTest 6 failed");
if (t.scientistsOtherTest7(galileo) != galileo) throw new Exception("scientistsOtherTest 7 failed");
if (enum_thorough.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest Global 1 failed");
if (enum_thorough.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest Global 2 failed");
if (enum_thorough.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest Global 3 failed");
if (enum_thorough.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest Global 4 failed");
if (enum_thorough.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest Global 5 failed");
if (enum_thorough.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest Global 6 failed");
if (enum_thorough.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest Global 7 failed");
if (enum_thorough.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 1 failed");
if (enum_thorough.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 2 failed");
if (enum_thorough.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 3 failed");
if (enum_thorough.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 4 failed");
if (enum_thorough.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 5 failed");
if (enum_thorough.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 6 failed");
if (enum_thorough.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 7 failed");
if (enum_thorough.scientistsNameSpaceTest8(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 8 failed");
if (enum_thorough.scientistsNameSpaceTest9(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 9 failed");
if (enum_thorough.scientistsNameSpaceTestA(bell) != bell) throw new Exception("scientistsNameSpaceTest Global A failed");
if (enum_thorough.scientistsNameSpaceTestB(bell) != bell) throw new Exception("scientistsNameSpaceTest Global B failed");
if (enum_thorough.scientistsNameSpaceTestC(bell) != bell) throw new Exception("scientistsNameSpaceTest Global C failed");
if (enum_thorough.scientistsNameSpaceTestD(bell) != bell) throw new Exception("scientistsNameSpaceTest Global D failed");
if (enum_thorough.scientistsNameSpaceTestE(bell) != bell) throw new Exception("scientistsNameSpaceTest Global E failed");
if (enum_thorough.scientistsNameSpaceTestF(bell) != bell) throw new Exception("scientistsNameSpaceTest Global F failed");
if (enum_thorough.scientistsNameSpaceTestG(bell) != bell) throw new Exception("scientistsNameSpaceTest Global G failed");
if (enum_thorough.scientistsNameSpaceTestH(bell) != bell) throw new Exception("scientistsNameSpaceTest Global H failed");
if (enum_thorough.scientistsNameSpaceTestI(bell) != bell) throw new Exception("scientistsNameSpaceTest Global I failed");
if (enum_thorough.scientistsNameSpaceTestJ(bell) != bell) throw new Exception("scientistsNameSpaceTest Global J failed");
if (enum_thorough.scientistsNameSpaceTestK(bell) != bell) throw new Exception("scientistsNameSpaceTest Global K failed");
if (enum_thorough.scientistsNameSpaceTestL(bell) != bell) throw new Exception("scientistsNameSpaceTest Global L failed");
}
{
newname val = newname.argh;
if (enum_thorough.renameTest1(val) != val) throw new Exception("renameTest Global 1 failed");
if (enum_thorough.renameTest2(val) != val) throw new Exception("renameTest Global 2 failed");
}
{
NewNameStruct n = new NewNameStruct();
if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 1 failed");
if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 2 failed");
if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest 3 failed");
if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 4 failed");
if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 5 failed");
if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest 6 failed");
}
{
if (enum_thorough.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest Global 3 failed");
if (enum_thorough.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest Global 4 failed");
if (enum_thorough.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 5 failed");
if (enum_thorough.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 6 failed");
if (enum_thorough.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest Global 7 failed");
}
{
TreesClass t = new TreesClass();
TreesClass.trees pine = TreesClass.trees.pine;
if (t.treesTest1(pine) != pine) throw new Exception("treesTest 1 failed");
if (t.treesTest2(pine) != pine) throw new Exception("treesTest 2 failed");
if (t.treesTest3(pine) != pine) throw new Exception("treesTest 3 failed");
if (t.treesTest4(pine) != pine) throw new Exception("treesTest 4 failed");
if (t.treesTest5(pine) != pine) throw new Exception("treesTest 5 failed");
if (t.treesTest6(pine) != pine) throw new Exception("treesTest 6 failed");
if (t.treesTest7(pine) != pine) throw new Exception("treesTest 7 failed");
if (t.treesTest8(pine) != pine) throw new Exception("treesTest 8 failed");
if (t.treesTest9(pine) != pine) throw new Exception("treesTest 9 failed");
if (t.treesTestA(pine) != pine) throw new Exception("treesTest A failed");
if (t.treesTestB(pine) != pine) throw new Exception("treesTest B failed");
if (t.treesTestC(pine) != pine) throw new Exception("treesTest C failed");
if (t.treesTestD(pine) != pine) throw new Exception("treesTest D failed");
if (t.treesTestE(pine) != pine) throw new Exception("treesTest E failed");
if (t.treesTestF(pine) != pine) throw new Exception("treesTest F failed");
if (t.treesTestG(pine) != pine) throw new Exception("treesTest G failed");
if (t.treesTestH(pine) != pine) throw new Exception("treesTest H failed");
if (t.treesTestI(pine) != pine) throw new Exception("treesTest I failed");
if (t.treesTestJ(pine) != pine) throw new Exception("treesTest J failed");
if (t.treesTestK(pine) != pine) throw new Exception("treesTest K failed");
if (t.treesTestL(pine) != pine) throw new Exception("treesTest L failed");
if (t.treesTestM(pine) != pine) throw new Exception("treesTest M failed");
if (t.treesTestN(pine) != pine) throw new Exception("treesTest N failed");
if (t.treesTestO(pine) != pine) throw new Exception("treesTest O failed");
if (enum_thorough.treesTest1(pine) != pine) throw new Exception("treesTest Global 1 failed");
if (enum_thorough.treesTest2(pine) != pine) throw new Exception("treesTest Global 2 failed");
if (enum_thorough.treesTest3(pine) != pine) throw new Exception("treesTest Global 3 failed");
if (enum_thorough.treesTest4(pine) != pine) throw new Exception("treesTest Global 4 failed");
if (enum_thorough.treesTest5(pine) != pine) throw new Exception("treesTest Global 5 failed");
if (enum_thorough.treesTest6(pine) != pine) throw new Exception("treesTest Global 6 failed");
if (enum_thorough.treesTest7(pine) != pine) throw new Exception("treesTest Global 7 failed");
if (enum_thorough.treesTest8(pine) != pine) throw new Exception("treesTest Global 8 failed");
if (enum_thorough.treesTest9(pine) != pine) throw new Exception("treesTest Global 9 failed");
if (enum_thorough.treesTestA(pine) != pine) throw new Exception("treesTest Global A failed");
if (enum_thorough.treesTestB(pine) != pine) throw new Exception("treesTest Global B failed");
if (enum_thorough.treesTestC(pine) != pine) throw new Exception("treesTest Global C failed");
if (enum_thorough.treesTestD(pine) != pine) throw new Exception("treesTest Global D failed");
if (enum_thorough.treesTestE(pine) != pine) throw new Exception("treesTest Global E failed");
if (enum_thorough.treesTestF(pine) != pine) throw new Exception("treesTest Global F failed");
if (enum_thorough.treesTestG(pine) != pine) throw new Exception("treesTest Global G failed");
if (enum_thorough.treesTestH(pine) != pine) throw new Exception("treesTest Global H failed");
if (enum_thorough.treesTestI(pine) != pine) throw new Exception("treesTest Global I failed");
if (enum_thorough.treesTestJ(pine) != pine) throw new Exception("treesTest Global J failed");
if (enum_thorough.treesTestK(pine) != pine) throw new Exception("treesTest Global K failed");
if (enum_thorough.treesTestL(pine) != pine) throw new Exception("treesTest Global L failed");
if (enum_thorough.treesTestM(pine) != pine) throw new Exception("treesTest Global M failed");
// if (enum_thorough.treesTestN(pine) != pine) throw new Exception("treesTest Global N failed");
if (enum_thorough.treesTestO(pine) != pine) throw new Exception("treesTest Global O failed");
if (enum_thorough.treesTestP(pine) != pine) throw new Exception("treesTest Global P failed");
if (enum_thorough.treesTestQ(pine) != pine) throw new Exception("treesTest Global Q failed");
if (enum_thorough.treesTestR(pine) != pine) throw new Exception("treesTest Global R failed");
}
{
HairStruct h = new HairStruct();
HairStruct.hair ginger = HairStruct.hair.ginger;
if (h.hairTest1(ginger) != ginger) throw new Exception("hairTest 1 failed");
if (h.hairTest2(ginger) != ginger) throw new Exception("hairTest 2 failed");
if (h.hairTest3(ginger) != ginger) throw new Exception("hairTest 3 failed");
if (h.hairTest4(ginger) != ginger) throw new Exception("hairTest 4 failed");
if (h.hairTest5(ginger) != ginger) throw new Exception("hairTest 5 failed");
if (h.hairTest6(ginger) != ginger) throw new Exception("hairTest 6 failed");
if (h.hairTest7(ginger) != ginger) throw new Exception("hairTest 7 failed");
if (h.hairTest8(ginger) != ginger) throw new Exception("hairTest 8 failed");
if (h.hairTest9(ginger) != ginger) throw new Exception("hairTest 9 failed");
if (h.hairTestA(ginger) != ginger) throw new Exception("hairTest A failed");
if (h.hairTestB(ginger) != ginger) throw new Exception("hairTest B failed");
colour red = colour.red;
if (h.colourTest1(red) != red) throw new Exception("colourTest HairStruct 1 failed");
if (h.colourTest2(red) != red) throw new Exception("colourTest HairStruct 2 failed");
if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest HairStruct 1 failed");
if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new Exception("namedanonspaceTest HairStruct 1 failed");
TreesClass.trees fir = TreesClass.trees.fir;
if (h.treesGlobalTest1(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 1 failed");
if (h.treesGlobalTest2(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 2 failed");
if (h.treesGlobalTest3(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 3 failed");
if (h.treesGlobalTest4(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 4 failed");
}
{
HairStruct.hair blonde = HairStruct.hair.blonde;
if (enum_thorough.hairTest1(blonde) != blonde) throw new Exception("hairTest Global 1 failed");
if (enum_thorough.hairTest2(blonde) != blonde) throw new Exception("hairTest Global 2 failed");
if (enum_thorough.hairTest3(blonde) != blonde) throw new Exception("hairTest Global 3 failed");
if (enum_thorough.hairTest4(blonde) != blonde) throw new Exception("hairTest Global 4 failed");
if (enum_thorough.hairTest5(blonde) != blonde) throw new Exception("hairTest Global 5 failed");
if (enum_thorough.hairTest6(blonde) != blonde) throw new Exception("hairTest Global 6 failed");
if (enum_thorough.hairTest7(blonde) != blonde) throw new Exception("hairTest Global 7 failed");
if (enum_thorough.hairTest8(blonde) != blonde) throw new Exception("hairTest Global 8 failed");
if (enum_thorough.hairTest9(blonde) != blonde) throw new Exception("hairTest Global 9 failed");
if (enum_thorough.hairTestA(blonde) != blonde) throw new Exception("hairTest Global A failed");
if (enum_thorough.hairTestB(blonde) != blonde) throw new Exception("hairTest Global B failed");
if (enum_thorough.hairTestC(blonde) != blonde) throw new Exception("hairTest Global C failed");
if (enum_thorough.hairTestA1(blonde) != blonde) throw new Exception("hairTest Global A1 failed");
if (enum_thorough.hairTestA2(blonde) != blonde) throw new Exception("hairTest Global A2 failed");
if (enum_thorough.hairTestA3(blonde) != blonde) throw new Exception("hairTest Global A3 failed");
if (enum_thorough.hairTestA4(blonde) != blonde) throw new Exception("hairTest Global A4 failed");
if (enum_thorough.hairTestA5(blonde) != blonde) throw new Exception("hairTest Global A5 failed");
if (enum_thorough.hairTestA6(blonde) != blonde) throw new Exception("hairTest Global A6 failed");
if (enum_thorough.hairTestA7(blonde) != blonde) throw new Exception("hairTest Global A7 failed");
if (enum_thorough.hairTestA8(blonde) != blonde) throw new Exception("hairTest Global A8 failed");
if (enum_thorough.hairTestA9(blonde) != blonde) throw new Exception("hairTest Global A9 failed");
if (enum_thorough.hairTestAA(blonde) != blonde) throw new Exception("hairTest Global AA failed");
if (enum_thorough.hairTestAB(blonde) != blonde) throw new Exception("hairTest Global AB failed");
if (enum_thorough.hairTestAC(blonde) != blonde) throw new Exception("hairTest Global AC failed");
if (enum_thorough.hairTestB1(blonde) != blonde) throw new Exception("hairTest Global B1 failed");
if (enum_thorough.hairTestB2(blonde) != blonde) throw new Exception("hairTest Global B2 failed");
if (enum_thorough.hairTestB3(blonde) != blonde) throw new Exception("hairTest Global B3 failed");
if (enum_thorough.hairTestB4(blonde) != blonde) throw new Exception("hairTest Global B4 failed");
if (enum_thorough.hairTestB5(blonde) != blonde) throw new Exception("hairTest Global B5 failed");
if (enum_thorough.hairTestB6(blonde) != blonde) throw new Exception("hairTest Global B6 failed");
if (enum_thorough.hairTestB7(blonde) != blonde) throw new Exception("hairTest Global B7 failed");
if (enum_thorough.hairTestB8(blonde) != blonde) throw new Exception("hairTest Global B8 failed");
if (enum_thorough.hairTestB9(blonde) != blonde) throw new Exception("hairTest Global B9 failed");
if (enum_thorough.hairTestBA(blonde) != blonde) throw new Exception("hairTest Global BA failed");
if (enum_thorough.hairTestBB(blonde) != blonde) throw new Exception("hairTest Global BB failed");
if (enum_thorough.hairTestBC(blonde) != blonde) throw new Exception("hairTest Global BC failed");
if (enum_thorough.hairTestC1(blonde) != blonde) throw new Exception("hairTest Global C1 failed");
if (enum_thorough.hairTestC2(blonde) != blonde) throw new Exception("hairTest Global C2 failed");
if (enum_thorough.hairTestC3(blonde) != blonde) throw new Exception("hairTest Global C3 failed");
if (enum_thorough.hairTestC4(blonde) != blonde) throw new Exception("hairTest Global C4 failed");
if (enum_thorough.hairTestC5(blonde) != blonde) throw new Exception("hairTest Global C5 failed");
if (enum_thorough.hairTestC6(blonde) != blonde) throw new Exception("hairTest Global C6 failed");
if (enum_thorough.hairTestC7(blonde) != blonde) throw new Exception("hairTest Global C7 failed");
if (enum_thorough.hairTestC8(blonde) != blonde) throw new Exception("hairTest Global C8 failed");
if (enum_thorough.hairTestC9(blonde) != blonde) throw new Exception("hairTest Global C9 failed");
if (enum_thorough.hairTestCA(blonde) != blonde) throw new Exception("hairTest Global CA failed");
if (enum_thorough.hairTestCB(blonde) != blonde) throw new Exception("hairTest Global CB failed");
if (enum_thorough.hairTestCC(blonde) != blonde) throw new Exception("hairTest Global CC failed");
}
{
FirStruct f = new FirStruct();
HairStruct.hair blonde = HairStruct.hair.blonde;
if (f.hairTestFir1(blonde) != blonde) throw new Exception("hairTestFir 1 failed");
if (f.hairTestFir2(blonde) != blonde) throw new Exception("hairTestFir 2 failed");
if (f.hairTestFir3(blonde) != blonde) throw new Exception("hairTestFir 3 failed");
if (f.hairTestFir4(blonde) != blonde) throw new Exception("hairTestFir 4 failed");
if (f.hairTestFir5(blonde) != blonde) throw new Exception("hairTestFir 5 failed");
if (f.hairTestFir6(blonde) != blonde) throw new Exception("hairTestFir 6 failed");
if (f.hairTestFir7(blonde) != blonde) throw new Exception("hairTestFir 7 failed");
if (f.hairTestFir8(blonde) != blonde) throw new Exception("hairTestFir 8 failed");
if (f.hairTestFir9(blonde) != blonde) throw new Exception("hairTestFir 9 failed");
if (f.hairTestFirA(blonde) != blonde) throw new Exception("hairTestFir A failed");
}
{
enum_thorough.GlobalInstance = enum_thorough.globalinstance2;
if (enum_thorough.GlobalInstance != enum_thorough.globalinstance2) throw new Exception("GlobalInstance 1 failed");
Instances i = new Instances();
i.MemberInstance = Instances.memberinstance3;
if (i.MemberInstance != Instances.memberinstance3) throw new Exception("MemberInstance 1 failed");
}
// ignore enum item tests start
{
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_zero) != 0) throw new Exception("ignoreATest 0 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_three) != 3) throw new Exception("ignoreATest 3 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_ten) != 10) throw new Exception("ignoreATest 10 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_eleven) != 11) throw new Exception("ignoreATest 11 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirteen) != 13) throw new Exception("ignoreATest 13 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_fourteen) != 14) throw new Exception("ignoreATest 14 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_twenty) != 20) throw new Exception("ignoreATest 20 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirty) != 30) throw new Exception("ignoreATest 30 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirty_two) != 32) throw new Exception("ignoreATest 32 failed");
if ((int)enum_thorough.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirty_three) != 33) throw new Exception("ignoreATest 33 failed");
}
{
if ((int)enum_thorough.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_eleven) != 11) throw new Exception("ignoreBTest 11 failed");
if ((int)enum_thorough.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_twelve) != 12) throw new Exception("ignoreBTest 12 failed");
if ((int)enum_thorough.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_thirty_one) != 31) throw new Exception("ignoreBTest 31 failed");
if ((int)enum_thorough.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_thirty_two) != 32) throw new Exception("ignoreBTest 32 failed");
if ((int)enum_thorough.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_forty_one) != 41) throw new Exception("ignoreBTest 41 failed");
if ((int)enum_thorough.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_forty_two) != 42) throw new Exception("ignoreBTest 42 failed");
}
{
if ((int)enum_thorough.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_ten) != 10) throw new Exception("ignoreCTest 10 failed");
if ((int)enum_thorough.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_twelve) != 12) throw new Exception("ignoreCTest 12 failed");
if ((int)enum_thorough.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_thirty) != 30) throw new Exception("ignoreCTest 30 failed");
if ((int)enum_thorough.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_thirty_two) != 32) throw new Exception("ignoreCTest 32 failed");
if ((int)enum_thorough.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_forty) != 40) throw new Exception("ignoreCTest 40 failed");
if ((int)enum_thorough.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_forty_two) != 42) throw new Exception("ignoreCTest 42 failed");
}
{
if ((int)enum_thorough.ignoreDTest(IgnoreTest.IgnoreD.ignoreD_twenty_one) != 21) throw new Exception("ignoreDTest 21 failed");
if ((int)enum_thorough.ignoreDTest(IgnoreTest.IgnoreD.ignoreD_twenty_two) != 22) throw new Exception("ignoreDTest 22 failed");
}
{
if ((int)enum_thorough.ignoreETest(IgnoreTest.IgnoreE.ignoreE_zero) != 0) throw new Exception("ignoreETest 0 failed");
if ((int)enum_thorough.ignoreETest(IgnoreTest.IgnoreE.ignoreE_twenty_one) != 21) throw new Exception("ignoreETest 21 failed");
if ((int)enum_thorough.ignoreETest(IgnoreTest.IgnoreE.ignoreE_twenty_two) != 22) throw new Exception("ignoreETest 22 failed");
}
// ignore enum item tests end
{
if ((int)enum_thorough.repeatTest(repeat.one) != 1) throw new Exception("repeatTest 1 failed");
if ((int)enum_thorough.repeatTest(repeat.initial) != 1) throw new Exception("repeatTest 2 failed");
if ((int)enum_thorough.repeatTest(repeat.two) != 2) throw new Exception("repeatTest 3 failed");
if ((int)enum_thorough.repeatTest(repeat.three) != 3) throw new Exception("repeatTest 4 failed");
if ((int)enum_thorough.repeatTest(repeat.llast) != 3) throw new Exception("repeatTest 5 failed");
if ((int)enum_thorough.repeatTest(repeat.end) != 3) throw new Exception("repeatTest 6 failed");
}
// different types
{
if ((int)enum_thorough.differentTypesTest(DifferentTypes.typeint) != 10) throw new Exception("differentTypes 1 failed");
if ((int)enum_thorough.differentTypesTest(DifferentTypes.typeboolfalse) != 0) throw new Exception("differentTypes 2 failed");
if ((int)enum_thorough.differentTypesTest(DifferentTypes.typebooltrue) != 1) throw new Exception("differentTypes 3 failed");
if ((int)enum_thorough.differentTypesTest(DifferentTypes.typebooltwo) != 2) throw new Exception("differentTypes 4 failed");
if ((int)enum_thorough.differentTypesTest(DifferentTypes.typechar) != 'C') throw new Exception("differentTypes 5 failed");
if ((int)enum_thorough.differentTypesTest(DifferentTypes.typedefaultint) != 'D') throw new Exception("differentTypes 6 failed");
int global_enum = enum_thorough.global_typeint;
if ((int)enum_thorough.globalDifferentTypesTest(global_enum) != 10) throw new Exception("global differentTypes 1 failed");
global_enum = enum_thorough.global_typeboolfalse;
if ((int)enum_thorough.globalDifferentTypesTest(global_enum) != 0) throw new Exception("global differentTypes 2 failed");
global_enum = enum_thorough.global_typebooltrue;
if ((int)enum_thorough.globalDifferentTypesTest(global_enum) != 1) throw new Exception("global differentTypes 3 failed");
global_enum = enum_thorough.global_typebooltwo;
if ((int)enum_thorough.globalDifferentTypesTest(global_enum) != 2) throw new Exception("global differentTypes 4 failed");
global_enum = enum_thorough.global_typechar;
if ((int)enum_thorough.globalDifferentTypesTest(global_enum) != 'C') throw new Exception("global differentTypes 5 failed");
global_enum = enum_thorough.global_typedefaultint;
if ((int)enum_thorough.globalDifferentTypesTest(global_enum) != 'D') throw new Exception("global differentTypes 6 failed");
}
}
}
using System;
using enum_thorough_simpleNamespace;
public class runme {
static void Main() {
{
// Anonymous enums
int i = enum_thorough_simple.AnonEnum1;
if (enum_thorough_simple.ReallyAnInteger != 200) throw new Exception("Test Anon 1 failed");
i += enum_thorough_simple.AnonSpaceEnum1;
i += AnonStruct.AnonStructEnum1;
}
{
int red = enum_thorough_simple.red;
enum_thorough_simple.colourTest1(red);
enum_thorough_simple.colourTest2(red);
enum_thorough_simple.colourTest3(red);
enum_thorough_simple.colourTest4(red);
enum_thorough_simple.myColour = red;
}
{
SpeedClass s = new SpeedClass();
int speed = SpeedClass.slow;
if (s.speedTest1(speed) != speed) throw new Exception("speedTest 1 failed");
if (s.speedTest2(speed) != speed) throw new Exception("speedTest 2 failed");
if (s.speedTest3(speed) != speed) throw new Exception("speedTest 3 failed");
if (s.speedTest4(speed) != speed) throw new Exception("speedTest 4 failed");
if (s.speedTest5(speed) != speed) throw new Exception("speedTest 5 failed");
if (s.speedTest6(speed) != speed) throw new Exception("speedTest 6 failed");
if (s.speedTest7(speed) != speed) throw new Exception("speedTest 7 failed");
if (s.speedTest8(speed) != speed) throw new Exception("speedTest 8 failed");
if (enum_thorough_simple.speedTest1(speed) != speed) throw new Exception("speedTest Global 1 failed");
if (enum_thorough_simple.speedTest2(speed) != speed) throw new Exception("speedTest Global 2 failed");
if (enum_thorough_simple.speedTest3(speed) != speed) throw new Exception("speedTest Global 3 failed");
if (enum_thorough_simple.speedTest4(speed) != speed) throw new Exception("speedTest Global 4 failed");
if (enum_thorough_simple.speedTest5(speed) != speed) throw new Exception("speedTest Global 5 failed");
}
{
SpeedClass s = new SpeedClass();
int slow = SpeedClass.slow;
int lightning = SpeedClass.lightning;
if (s.mySpeedtd1 != slow) throw new Exception("mySpeedtd1 1 failed");
if (s.mySpeedtd1 != 10) throw new Exception("mySpeedtd1 2 failed");
s.mySpeedtd1 = lightning;
if (s.mySpeedtd1 != lightning) throw new Exception("mySpeedtd1 3 failed");
if (s.mySpeedtd1 != 31) throw new Exception("mySpeedtd1 4 failed");
}
{
if (enum_thorough_simple.namedanonTest1(enum_thorough_simple.NamedAnon2) != enum_thorough_simple.NamedAnon2) throw new Exception("namedanonTest 1 failed");
}
{
int val = enum_thorough_simple.TwoNames2;
if (enum_thorough_simple.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
if (enum_thorough_simple.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
if (enum_thorough_simple.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
}
{
TwoNamesStruct t = new TwoNamesStruct();
int val = TwoNamesStruct.TwoNamesStruct1;
if (t.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
if (t.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
if (t.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
}
{
int val = enum_thorough_simple.NamedAnonSpace2;
if (enum_thorough_simple.namedanonspaceTest1(val) != val) throw new Exception("namedanonspaceTest 1 failed");
if (enum_thorough_simple.namedanonspaceTest2(val) != val) throw new Exception("namedanonspaceTest 2 failed");
if (enum_thorough_simple.namedanonspaceTest3(val) != val) throw new Exception("namedanonspaceTest 3 failed");
if (enum_thorough_simple.namedanonspaceTest4(val) != val) throw new Exception("namedanonspaceTest 4 failed");
}
{
TemplateClassInt t = new TemplateClassInt();
int galileo = TemplateClassInt.galileo;
if (t.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest 1 failed");
if (t.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest 2 failed");
if (t.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest 3 failed");
if (t.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest 4 failed");
if (t.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest 5 failed");
if (t.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest 6 failed");
if (t.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest 7 failed");
if (t.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest 8 failed");
if (t.scientistsTest9(galileo) != galileo) throw new Exception("scientistsTest 9 failed");
// if (t.scientistsTestA(galileo) != galileo) throw new Exception("scientistsTest A failed");
if (t.scientistsTestB(galileo) != galileo) throw new Exception("scientistsTest B failed");
// if (t.scientistsTestC(galileo) != galileo) throw new Exception("scientistsTest C failed");
if (t.scientistsTestD(galileo) != galileo) throw new Exception("scientistsTest D failed");
if (t.scientistsTestE(galileo) != galileo) throw new Exception("scientistsTest E failed");
if (t.scientistsTestF(galileo) != galileo) throw new Exception("scientistsTest F failed");
if (t.scientistsTestG(galileo) != galileo) throw new Exception("scientistsTest G failed");
if (t.scientistsTestH(galileo) != galileo) throw new Exception("scientistsTest H failed");
if (t.scientistsTestI(galileo) != galileo) throw new Exception("scientistsTest I failed");
if (t.scientistsTestJ(galileo) != galileo) throw new Exception("scientistsTest J failed");
if (enum_thorough_simple.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest Global 1 failed");
if (enum_thorough_simple.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest Global 2 failed");
if (enum_thorough_simple.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest Global 3 failed");
if (enum_thorough_simple.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest Global 4 failed");
if (enum_thorough_simple.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest Global 5 failed");
if (enum_thorough_simple.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest Global 6 failed");
if (enum_thorough_simple.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest Global 7 failed");
if (enum_thorough_simple.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest Global 8 failed");
}
{
TClassInt t = new TClassInt();
int bell = TClassInt.bell;
int galileo = TemplateClassInt.galileo;
if (t.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest 1 failed");
if (t.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest 2 failed");
if (t.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest 3 failed");
if (t.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest 4 failed");
if (t.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest 5 failed");
if (t.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest 6 failed");
if (t.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest 7 failed");
if (t.scientistsNameTest8(bell) != bell) throw new Exception("scientistsNameTest 8 failed");
if (t.scientistsNameTest9(bell) != bell) throw new Exception("scientistsNameTest 9 failed");
// if (t.scientistsNameTestA(bell) != bell) throw new Exception("scientistsNameTest A failed");
if (t.scientistsNameTestB(bell) != bell) throw new Exception("scientistsNameTest B failed");
// if (t.scientistsNameTestC(bell) != bell) throw new Exception("scientistsNameTest C failed");
if (t.scientistsNameTestD(bell) != bell) throw new Exception("scientistsNameTest D failed");
if (t.scientistsNameTestE(bell) != bell) throw new Exception("scientistsNameTest E failed");
if (t.scientistsNameTestF(bell) != bell) throw new Exception("scientistsNameTest F failed");
if (t.scientistsNameTestG(bell) != bell) throw new Exception("scientistsNameTest G failed");
if (t.scientistsNameTestH(bell) != bell) throw new Exception("scientistsNameTest H failed");
if (t.scientistsNameTestI(bell) != bell) throw new Exception("scientistsNameTest I failed");
if (t.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest 1 failed");
if (t.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest 2 failed");
if (t.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest 3 failed");
if (t.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest 4 failed");
if (t.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest 5 failed");
if (t.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest 6 failed");
if (t.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest 7 failed");
if (t.scientistsOtherTest1(galileo) != galileo) throw new Exception("scientistsOtherTest 1 failed");
if (t.scientistsOtherTest2(galileo) != galileo) throw new Exception("scientistsOtherTest 2 failed");
if (t.scientistsOtherTest3(galileo) != galileo) throw new Exception("scientistsOtherTest 3 failed");
if (t.scientistsOtherTest4(galileo) != galileo) throw new Exception("scientistsOtherTest 4 failed");
if (t.scientistsOtherTest5(galileo) != galileo) throw new Exception("scientistsOtherTest 5 failed");
if (t.scientistsOtherTest6(galileo) != galileo) throw new Exception("scientistsOtherTest 6 failed");
if (t.scientistsOtherTest7(galileo) != galileo) throw new Exception("scientistsOtherTest 7 failed");
if (enum_thorough_simple.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest Global 1 failed");
if (enum_thorough_simple.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest Global 2 failed");
if (enum_thorough_simple.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest Global 3 failed");
if (enum_thorough_simple.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest Global 4 failed");
if (enum_thorough_simple.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest Global 5 failed");
if (enum_thorough_simple.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest Global 6 failed");
if (enum_thorough_simple.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest Global 7 failed");
if (enum_thorough_simple.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 1 failed");
if (enum_thorough_simple.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 2 failed");
if (enum_thorough_simple.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 3 failed");
if (enum_thorough_simple.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 4 failed");
if (enum_thorough_simple.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 5 failed");
if (enum_thorough_simple.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 6 failed");
if (enum_thorough_simple.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 7 failed");
if (enum_thorough_simple.scientistsNameSpaceTest8(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 8 failed");
if (enum_thorough_simple.scientistsNameSpaceTest9(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 9 failed");
if (enum_thorough_simple.scientistsNameSpaceTestA(bell) != bell) throw new Exception("scientistsNameSpaceTest Global A failed");
if (enum_thorough_simple.scientistsNameSpaceTestB(bell) != bell) throw new Exception("scientistsNameSpaceTest Global B failed");
if (enum_thorough_simple.scientistsNameSpaceTestC(bell) != bell) throw new Exception("scientistsNameSpaceTest Global C failed");
if (enum_thorough_simple.scientistsNameSpaceTestD(bell) != bell) throw new Exception("scientistsNameSpaceTest Global D failed");
if (enum_thorough_simple.scientistsNameSpaceTestE(bell) != bell) throw new Exception("scientistsNameSpaceTest Global E failed");
if (enum_thorough_simple.scientistsNameSpaceTestF(bell) != bell) throw new Exception("scientistsNameSpaceTest Global F failed");
if (enum_thorough_simple.scientistsNameSpaceTestG(bell) != bell) throw new Exception("scientistsNameSpaceTest Global G failed");
if (enum_thorough_simple.scientistsNameSpaceTestH(bell) != bell) throw new Exception("scientistsNameSpaceTest Global H failed");
if (enum_thorough_simple.scientistsNameSpaceTestI(bell) != bell) throw new Exception("scientistsNameSpaceTest Global I failed");
if (enum_thorough_simple.scientistsNameSpaceTestJ(bell) != bell) throw new Exception("scientistsNameSpaceTest Global J failed");
if (enum_thorough_simple.scientistsNameSpaceTestK(bell) != bell) throw new Exception("scientistsNameSpaceTest Global K failed");
if (enum_thorough_simple.scientistsNameSpaceTestL(bell) != bell) throw new Exception("scientistsNameSpaceTest Global L failed");
}
{
int val = enum_thorough_simple.argh;
if (enum_thorough_simple.renameTest1(val) != val) throw new Exception("renameTest Global 1 failed");
if (enum_thorough_simple.renameTest2(val) != val) throw new Exception("renameTest Global 2 failed");
}
{
NewNameStruct n = new NewNameStruct();
if (n.renameTest1(NewNameStruct.bang) != NewNameStruct.bang) throw new Exception("renameTest 1 failed");
if (n.renameTest2(NewNameStruct.bang) != NewNameStruct.bang) throw new Exception("renameTest 2 failed");
if (n.renameTest3(NewNameStruct.simple1) != NewNameStruct.simple1) throw new Exception("renameTest 3 failed");
if (n.renameTest4(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest 4 failed");
if (n.renameTest5(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest 5 failed");
if (n.renameTest6(NewNameStruct.singlename1) != NewNameStruct.singlename1) throw new Exception("renameTest 6 failed");
}
{
if (enum_thorough_simple.renameTest3(NewNameStruct.bang) != NewNameStruct.bang) throw new Exception("renameTest Global 3 failed");
if (enum_thorough_simple.renameTest4(NewNameStruct.simple1) != NewNameStruct.simple1) throw new Exception("renameTest Global 4 failed");
if (enum_thorough_simple.renameTest5(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest Global 5 failed");
if (enum_thorough_simple.renameTest6(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest Global 6 failed");
if (enum_thorough_simple.renameTest7(NewNameStruct.singlename1) != NewNameStruct.singlename1) throw new Exception("renameTest Global 7 failed");
}
{
TreesClass t = new TreesClass();
int pine = TreesClass.pine;
if (t.treesTest1(pine) != pine) throw new Exception("treesTest 1 failed");
if (t.treesTest2(pine) != pine) throw new Exception("treesTest 2 failed");
if (t.treesTest3(pine) != pine) throw new Exception("treesTest 3 failed");
if (t.treesTest4(pine) != pine) throw new Exception("treesTest 4 failed");
if (t.treesTest5(pine) != pine) throw new Exception("treesTest 5 failed");
if (t.treesTest6(pine) != pine) throw new Exception("treesTest 6 failed");
if (t.treesTest7(pine) != pine) throw new Exception("treesTest 7 failed");
if (t.treesTest8(pine) != pine) throw new Exception("treesTest 8 failed");
if (t.treesTest9(pine) != pine) throw new Exception("treesTest 9 failed");
if (t.treesTestA(pine) != pine) throw new Exception("treesTest A failed");
if (t.treesTestB(pine) != pine) throw new Exception("treesTest B failed");
if (t.treesTestC(pine) != pine) throw new Exception("treesTest C failed");
if (t.treesTestD(pine) != pine) throw new Exception("treesTest D failed");
if (t.treesTestE(pine) != pine) throw new Exception("treesTest E failed");
if (t.treesTestF(pine) != pine) throw new Exception("treesTest F failed");
if (t.treesTestG(pine) != pine) throw new Exception("treesTest G failed");
if (t.treesTestH(pine) != pine) throw new Exception("treesTest H failed");
if (t.treesTestI(pine) != pine) throw new Exception("treesTest I failed");
if (t.treesTestJ(pine) != pine) throw new Exception("treesTest J failed");
if (t.treesTestK(pine) != pine) throw new Exception("treesTest K failed");
if (t.treesTestL(pine) != pine) throw new Exception("treesTest L failed");
if (t.treesTestM(pine) != pine) throw new Exception("treesTest M failed");
if (t.treesTestN(pine) != pine) throw new Exception("treesTest N failed");
if (t.treesTestO(pine) != pine) throw new Exception("treesTest O failed");
if (enum_thorough_simple.treesTest1(pine) != pine) throw new Exception("treesTest Global 1 failed");
if (enum_thorough_simple.treesTest2(pine) != pine) throw new Exception("treesTest Global 2 failed");
if (enum_thorough_simple.treesTest3(pine) != pine) throw new Exception("treesTest Global 3 failed");
if (enum_thorough_simple.treesTest4(pine) != pine) throw new Exception("treesTest Global 4 failed");
if (enum_thorough_simple.treesTest5(pine) != pine) throw new Exception("treesTest Global 5 failed");
if (enum_thorough_simple.treesTest6(pine) != pine) throw new Exception("treesTest Global 6 failed");
if (enum_thorough_simple.treesTest7(pine) != pine) throw new Exception("treesTest Global 7 failed");
if (enum_thorough_simple.treesTest8(pine) != pine) throw new Exception("treesTest Global 8 failed");
if (enum_thorough_simple.treesTest9(pine) != pine) throw new Exception("treesTest Global 9 failed");
if (enum_thorough_simple.treesTestA(pine) != pine) throw new Exception("treesTest Global A failed");
if (enum_thorough_simple.treesTestB(pine) != pine) throw new Exception("treesTest Global B failed");
if (enum_thorough_simple.treesTestC(pine) != pine) throw new Exception("treesTest Global C failed");
if (enum_thorough_simple.treesTestD(pine) != pine) throw new Exception("treesTest Global D failed");
if (enum_thorough_simple.treesTestE(pine) != pine) throw new Exception("treesTest Global E failed");
if (enum_thorough_simple.treesTestF(pine) != pine) throw new Exception("treesTest Global F failed");
if (enum_thorough_simple.treesTestG(pine) != pine) throw new Exception("treesTest Global G failed");
if (enum_thorough_simple.treesTestH(pine) != pine) throw new Exception("treesTest Global H failed");
if (enum_thorough_simple.treesTestI(pine) != pine) throw new Exception("treesTest Global I failed");
if (enum_thorough_simple.treesTestJ(pine) != pine) throw new Exception("treesTest Global J failed");
if (enum_thorough_simple.treesTestK(pine) != pine) throw new Exception("treesTest Global K failed");
if (enum_thorough_simple.treesTestL(pine) != pine) throw new Exception("treesTest Global L failed");
if (enum_thorough_simple.treesTestM(pine) != pine) throw new Exception("treesTest Global M failed");
// if (enum_thorough_simple.treesTestN(pine) != pine) throw new Exception("treesTest Global N failed");
if (enum_thorough_simple.treesTestO(pine) != pine) throw new Exception("treesTest Global O failed");
if (enum_thorough_simple.treesTestP(pine) != pine) throw new Exception("treesTest Global P failed");
if (enum_thorough_simple.treesTestQ(pine) != pine) throw new Exception("treesTest Global Q failed");
if (enum_thorough_simple.treesTestR(pine) != pine) throw new Exception("treesTest Global R failed");
}
{
HairStruct h = new HairStruct();
int ginger = HairStruct.ginger;
if (h.hairTest1(ginger) != ginger) throw new Exception("hairTest 1 failed");
if (h.hairTest2(ginger) != ginger) throw new Exception("hairTest 2 failed");
if (h.hairTest3(ginger) != ginger) throw new Exception("hairTest 3 failed");
if (h.hairTest4(ginger) != ginger) throw new Exception("hairTest 4 failed");
if (h.hairTest5(ginger) != ginger) throw new Exception("hairTest 5 failed");
if (h.hairTest6(ginger) != ginger) throw new Exception("hairTest 6 failed");
if (h.hairTest7(ginger) != ginger) throw new Exception("hairTest 7 failed");
if (h.hairTest8(ginger) != ginger) throw new Exception("hairTest 8 failed");
if (h.hairTest9(ginger) != ginger) throw new Exception("hairTest 9 failed");
if (h.hairTestA(ginger) != ginger) throw new Exception("hairTest A failed");
if (h.hairTestB(ginger) != ginger) throw new Exception("hairTest B failed");
int red = enum_thorough_simple.red;
if (h.colourTest1(red) != red) throw new Exception("colourTest HairStruct 1 failed");
if (h.colourTest2(red) != red) throw new Exception("colourTest HairStruct 2 failed");
if (h.namedanonTest1(enum_thorough_simple.NamedAnon2) != enum_thorough_simple.NamedAnon2) throw new Exception("namedanonTest HairStruct 1 failed");
if (h.namedanonspaceTest1(enum_thorough_simple.NamedAnonSpace2) != enum_thorough_simple.NamedAnonSpace2) throw new Exception("namedanonspaceTest HairStruct 1 failed");
int fir = TreesClass.fir;
if (h.treesGlobalTest1(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 1 failed");
if (h.treesGlobalTest2(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 2 failed");
if (h.treesGlobalTest3(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 3 failed");
if (h.treesGlobalTest4(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 4 failed");
}
{
int blonde = HairStruct.blonde;
if (enum_thorough_simple.hairTest1(blonde) != blonde) throw new Exception("hairTest Global 1 failed");
if (enum_thorough_simple.hairTest2(blonde) != blonde) throw new Exception("hairTest Global 2 failed");
if (enum_thorough_simple.hairTest3(blonde) != blonde) throw new Exception("hairTest Global 3 failed");
if (enum_thorough_simple.hairTest4(blonde) != blonde) throw new Exception("hairTest Global 4 failed");
if (enum_thorough_simple.hairTest5(blonde) != blonde) throw new Exception("hairTest Global 5 failed");
if (enum_thorough_simple.hairTest6(blonde) != blonde) throw new Exception("hairTest Global 6 failed");
if (enum_thorough_simple.hairTest7(blonde) != blonde) throw new Exception("hairTest Global 7 failed");
if (enum_thorough_simple.hairTest8(blonde) != blonde) throw new Exception("hairTest Global 8 failed");
if (enum_thorough_simple.hairTest9(blonde) != blonde) throw new Exception("hairTest Global 9 failed");
if (enum_thorough_simple.hairTestA(blonde) != blonde) throw new Exception("hairTest Global A failed");
if (enum_thorough_simple.hairTestB(blonde) != blonde) throw new Exception("hairTest Global B failed");
if (enum_thorough_simple.hairTestC(blonde) != blonde) throw new Exception("hairTest Global C failed");
if (enum_thorough_simple.hairTestA1(blonde) != blonde) throw new Exception("hairTest Global A1 failed");
if (enum_thorough_simple.hairTestA2(blonde) != blonde) throw new Exception("hairTest Global A2 failed");
if (enum_thorough_simple.hairTestA3(blonde) != blonde) throw new Exception("hairTest Global A3 failed");
if (enum_thorough_simple.hairTestA4(blonde) != blonde) throw new Exception("hairTest Global A4 failed");
if (enum_thorough_simple.hairTestA5(blonde) != blonde) throw new Exception("hairTest Global A5 failed");
if (enum_thorough_simple.hairTestA6(blonde) != blonde) throw new Exception("hairTest Global A6 failed");
if (enum_thorough_simple.hairTestA7(blonde) != blonde) throw new Exception("hairTest Global A7 failed");
if (enum_thorough_simple.hairTestA8(blonde) != blonde) throw new Exception("hairTest Global A8 failed");
if (enum_thorough_simple.hairTestA9(blonde) != blonde) throw new Exception("hairTest Global A9 failed");
if (enum_thorough_simple.hairTestAA(blonde) != blonde) throw new Exception("hairTest Global AA failed");
if (enum_thorough_simple.hairTestAB(blonde) != blonde) throw new Exception("hairTest Global AB failed");
if (enum_thorough_simple.hairTestAC(blonde) != blonde) throw new Exception("hairTest Global AC failed");
if (enum_thorough_simple.hairTestB1(blonde) != blonde) throw new Exception("hairTest Global B1 failed");
if (enum_thorough_simple.hairTestB2(blonde) != blonde) throw new Exception("hairTest Global B2 failed");
if (enum_thorough_simple.hairTestB3(blonde) != blonde) throw new Exception("hairTest Global B3 failed");
if (enum_thorough_simple.hairTestB4(blonde) != blonde) throw new Exception("hairTest Global B4 failed");
if (enum_thorough_simple.hairTestB5(blonde) != blonde) throw new Exception("hairTest Global B5 failed");
if (enum_thorough_simple.hairTestB6(blonde) != blonde) throw new Exception("hairTest Global B6 failed");
if (enum_thorough_simple.hairTestB7(blonde) != blonde) throw new Exception("hairTest Global B7 failed");
if (enum_thorough_simple.hairTestB8(blonde) != blonde) throw new Exception("hairTest Global B8 failed");
if (enum_thorough_simple.hairTestB9(blonde) != blonde) throw new Exception("hairTest Global B9 failed");
if (enum_thorough_simple.hairTestBA(blonde) != blonde) throw new Exception("hairTest Global BA failed");
if (enum_thorough_simple.hairTestBB(blonde) != blonde) throw new Exception("hairTest Global BB failed");
if (enum_thorough_simple.hairTestBC(blonde) != blonde) throw new Exception("hairTest Global BC failed");
if (enum_thorough_simple.hairTestC1(blonde) != blonde) throw new Exception("hairTest Global C1 failed");
if (enum_thorough_simple.hairTestC2(blonde) != blonde) throw new Exception("hairTest Global C2 failed");
if (enum_thorough_simple.hairTestC3(blonde) != blonde) throw new Exception("hairTest Global C3 failed");
if (enum_thorough_simple.hairTestC4(blonde) != blonde) throw new Exception("hairTest Global C4 failed");
if (enum_thorough_simple.hairTestC5(blonde) != blonde) throw new Exception("hairTest Global C5 failed");
if (enum_thorough_simple.hairTestC6(blonde) != blonde) throw new Exception("hairTest Global C6 failed");
if (enum_thorough_simple.hairTestC7(blonde) != blonde) throw new Exception("hairTest Global C7 failed");
if (enum_thorough_simple.hairTestC8(blonde) != blonde) throw new Exception("hairTest Global C8 failed");
if (enum_thorough_simple.hairTestC9(blonde) != blonde) throw new Exception("hairTest Global C9 failed");
if (enum_thorough_simple.hairTestCA(blonde) != blonde) throw new Exception("hairTest Global CA failed");
if (enum_thorough_simple.hairTestCB(blonde) != blonde) throw new Exception("hairTest Global CB failed");
if (enum_thorough_simple.hairTestCC(blonde) != blonde) throw new Exception("hairTest Global CC failed");
}
{
FirStruct f = new FirStruct();
int blonde = HairStruct.blonde;
if (f.hairTestFir1(blonde) != blonde) throw new Exception("hairTestFir 1 failed");
if (f.hairTestFir2(blonde) != blonde) throw new Exception("hairTestFir 2 failed");
if (f.hairTestFir3(blonde) != blonde) throw new Exception("hairTestFir 3 failed");
if (f.hairTestFir4(blonde) != blonde) throw new Exception("hairTestFir 4 failed");
if (f.hairTestFir5(blonde) != blonde) throw new Exception("hairTestFir 5 failed");
if (f.hairTestFir6(blonde) != blonde) throw new Exception("hairTestFir 6 failed");
if (f.hairTestFir7(blonde) != blonde) throw new Exception("hairTestFir 7 failed");
if (f.hairTestFir8(blonde) != blonde) throw new Exception("hairTestFir 8 failed");
if (f.hairTestFir9(blonde) != blonde) throw new Exception("hairTestFir 9 failed");
if (f.hairTestFirA(blonde) != blonde) throw new Exception("hairTestFir A failed");
}
{
enum_thorough_simple.GlobalInstance = enum_thorough_simple.globalinstance2;
if (enum_thorough_simple.GlobalInstance != enum_thorough_simple.globalinstance2) throw new Exception("GlobalInstance 1 failed");
Instances i = new Instances();
i.MemberInstance = Instances.memberinstance3;
if (i.MemberInstance != Instances.memberinstance3) throw new Exception("MemberInstance 1 failed");
}
// ignore enum item tests start
{
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_zero) != 0) throw new Exception("ignoreATest 0 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_three) != 3) throw new Exception("ignoreATest 3 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_ten) != 10) throw new Exception("ignoreATest 10 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_eleven) != 11) throw new Exception("ignoreATest 11 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_thirteen) != 13) throw new Exception("ignoreATest 13 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_fourteen) != 14) throw new Exception("ignoreATest 14 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_twenty) != 20) throw new Exception("ignoreATest 20 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_thirty) != 30) throw new Exception("ignoreATest 30 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_thirty_two) != 32) throw new Exception("ignoreATest 32 failed");
if (enum_thorough_simple.ignoreATest(IgnoreTest.ignoreA_thirty_three) != 33) throw new Exception("ignoreATest 33 failed");
}
{
if (enum_thorough_simple.ignoreBTest(IgnoreTest.ignoreB_eleven) != 11) throw new Exception("ignoreBTest 11 failed");
if (enum_thorough_simple.ignoreBTest(IgnoreTest.ignoreB_twelve) != 12) throw new Exception("ignoreBTest 12 failed");
if (enum_thorough_simple.ignoreBTest(IgnoreTest.ignoreB_thirty_one) != 31) throw new Exception("ignoreBTest 31 failed");
if (enum_thorough_simple.ignoreBTest(IgnoreTest.ignoreB_thirty_two) != 32) throw new Exception("ignoreBTest 32 failed");
if (enum_thorough_simple.ignoreBTest(IgnoreTest.ignoreB_forty_one) != 41) throw new Exception("ignoreBTest 41 failed");
if (enum_thorough_simple.ignoreBTest(IgnoreTest.ignoreB_forty_two) != 42) throw new Exception("ignoreBTest 42 failed");
}
{
if (enum_thorough_simple.ignoreCTest(IgnoreTest.ignoreC_ten) != 10) throw new Exception("ignoreCTest 10 failed");
if (enum_thorough_simple.ignoreCTest(IgnoreTest.ignoreC_twelve) != 12) throw new Exception("ignoreCTest 12 failed");
if (enum_thorough_simple.ignoreCTest(IgnoreTest.ignoreC_thirty) != 30) throw new Exception("ignoreCTest 30 failed");
if (enum_thorough_simple.ignoreCTest(IgnoreTest.ignoreC_thirty_two) != 32) throw new Exception("ignoreCTest 32 failed");
if (enum_thorough_simple.ignoreCTest(IgnoreTest.ignoreC_forty) != 40) throw new Exception("ignoreCTest 40 failed");
if (enum_thorough_simple.ignoreCTest(IgnoreTest.ignoreC_forty_two) != 42) throw new Exception("ignoreCTest 42 failed");
}
{
if (enum_thorough_simple.ignoreDTest(IgnoreTest.ignoreD_twenty_one) != 21) throw new Exception("ignoreDTest 21 failed");
if (enum_thorough_simple.ignoreDTest(IgnoreTest.ignoreD_twenty_two) != 22) throw new Exception("ignoreDTest 22 failed");
}
{
if (enum_thorough_simple.ignoreETest(IgnoreTest.ignoreE_zero) != 0) throw new Exception("ignoreETest 0 failed");
if (enum_thorough_simple.ignoreETest(IgnoreTest.ignoreE_twenty_one) != 21) throw new Exception("ignoreETest 21 failed");
if (enum_thorough_simple.ignoreETest(IgnoreTest.ignoreE_twenty_two) != 22) throw new Exception("ignoreETest 22 failed");
}
// ignore enum item tests end
{
if (enum_thorough_simple.repeatTest(enum_thorough_simple.one) != 1) throw new Exception("repeatTest 1 failed");
if (enum_thorough_simple.repeatTest(enum_thorough_simple.initial) != 1) throw new Exception("repeatTest 2 failed");
if (enum_thorough_simple.repeatTest(enum_thorough_simple.two) != 2) throw new Exception("repeatTest 3 failed");
if (enum_thorough_simple.repeatTest(enum_thorough_simple.three) != 3) throw new Exception("repeatTest 4 failed");
if (enum_thorough_simple.repeatTest(enum_thorough_simple.llast) != 3) throw new Exception("repeatTest 5 failed");
if (enum_thorough_simple.repeatTest(enum_thorough_simple.end) != 3) throw new Exception("repeatTest 6 failed");
}
// different types
{
if (enum_thorough_simple.differentTypesTest(enum_thorough_simple.typeint) != 10) throw new Exception("differentTypes 1 failed");
if (enum_thorough_simple.differentTypesTest(enum_thorough_simple.typeboolfalse) != 0) throw new Exception("differentTypes 2 failed");
if (enum_thorough_simple.differentTypesTest(enum_thorough_simple.typebooltrue) != 1) throw new Exception("differentTypes 3 failed");
if (enum_thorough_simple.differentTypesTest(enum_thorough_simple.typebooltwo) != 2) throw new Exception("differentTypes 4 failed");
if (enum_thorough_simple.differentTypesTest(enum_thorough_simple.typechar) != 'C') throw new Exception("differentTypes 5 failed");
if (enum_thorough_simple.differentTypesTest(enum_thorough_simple.typedefaultint) != 'D') throw new Exception("differentTypes 6 failed");
int global_enum = enum_thorough_simple.global_typeint;
if (enum_thorough_simple.globalDifferentTypesTest(global_enum) != 10) throw new Exception("global differentTypes 1 failed");
global_enum = enum_thorough_simple.global_typeboolfalse;
if (enum_thorough_simple.globalDifferentTypesTest(global_enum) != 0) throw new Exception("global differentTypes 2 failed");
global_enum = enum_thorough_simple.global_typebooltrue;
if (enum_thorough_simple.globalDifferentTypesTest(global_enum) != 1) throw new Exception("global differentTypes 3 failed");
global_enum = enum_thorough_simple.global_typebooltwo;
if (enum_thorough_simple.globalDifferentTypesTest(global_enum) != 2) throw new Exception("global differentTypes 4 failed");
global_enum = enum_thorough_simple.global_typechar;
if (enum_thorough_simple.globalDifferentTypesTest(global_enum) != 'C') throw new Exception("global differentTypes 5 failed");
global_enum = enum_thorough_simple.global_typedefaultint;
if (enum_thorough_simple.globalDifferentTypesTest(global_enum) != 'D') throw new Exception("global differentTypes 6 failed");
}
}
}
using System;
using enum_thorough_typesafeNamespace;
public class runme {
static void Main() {
{
// Anonymous enums
int i = enum_thorough_typesafe.AnonEnum1;
if (enum_thorough_typesafe.ReallyAnInteger != 200) throw new Exception("Test Anon 1 failed");
i += enum_thorough_typesafe.AnonSpaceEnum1;
i += AnonStruct.AnonStructEnum1;
}
{
colour red = colour.red;
enum_thorough_typesafe.colourTest1(red);
enum_thorough_typesafe.colourTest2(red);
enum_thorough_typesafe.colourTest3(red);
enum_thorough_typesafe.colourTest4(red);
enum_thorough_typesafe.myColour = red;
}
{
SpeedClass s = new SpeedClass();
SpeedClass.speed speed = SpeedClass.speed.slow;
if (s.speedTest1(speed) != speed) throw new Exception("speedTest 1 failed");
if (s.speedTest2(speed) != speed) throw new Exception("speedTest 2 failed");
if (s.speedTest3(speed) != speed) throw new Exception("speedTest 3 failed");
if (s.speedTest4(speed) != speed) throw new Exception("speedTest 4 failed");
if (s.speedTest5(speed) != speed) throw new Exception("speedTest 5 failed");
if (s.speedTest6(speed) != speed) throw new Exception("speedTest 6 failed");
if (s.speedTest7(speed) != speed) throw new Exception("speedTest 7 failed");
if (s.speedTest8(speed) != speed) throw new Exception("speedTest 8 failed");
if (enum_thorough_typesafe.speedTest1(speed) != speed) throw new Exception("speedTest Global 1 failed");
if (enum_thorough_typesafe.speedTest2(speed) != speed) throw new Exception("speedTest Global 2 failed");
if (enum_thorough_typesafe.speedTest3(speed) != speed) throw new Exception("speedTest Global 3 failed");
if (enum_thorough_typesafe.speedTest4(speed) != speed) throw new Exception("speedTest Global 4 failed");
if (enum_thorough_typesafe.speedTest5(speed) != speed) throw new Exception("speedTest Global 5 failed");
}
{
SpeedClass s = new SpeedClass();
SpeedClass.speed slow = SpeedClass.speed.slow;
SpeedClass.speed lightning = SpeedClass.speed.lightning;
if (s.mySpeedtd1 != slow) throw new Exception("mySpeedtd1 1 failed");
if (s.mySpeedtd1.swigValue != 10) throw new Exception("mySpeedtd1 2 failed");
s.mySpeedtd1 = lightning;
if (s.mySpeedtd1 != lightning) throw new Exception("mySpeedtd1 3 failed");
if (s.mySpeedtd1.swigValue != 31) throw new Exception("mySpeedtd1 4 failed");
}
{
if (enum_thorough_typesafe.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest 1 failed");
}
{
twonames val = twonames.TwoNames2;
if (enum_thorough_typesafe.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
if (enum_thorough_typesafe.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
if (enum_thorough_typesafe.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
}
{
TwoNamesStruct t = new TwoNamesStruct();
TwoNamesStruct.twonames val = TwoNamesStruct.twonames.TwoNamesStruct1;
if (t.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
if (t.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
if (t.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
}
{
namedanonspace val = namedanonspace.NamedAnonSpace2;
if (enum_thorough_typesafe.namedanonspaceTest1(val) != val) throw new Exception("namedanonspaceTest 1 failed");
if (enum_thorough_typesafe.namedanonspaceTest2(val) != val) throw new Exception("namedanonspaceTest 2 failed");
if (enum_thorough_typesafe.namedanonspaceTest3(val) != val) throw new Exception("namedanonspaceTest 3 failed");
if (enum_thorough_typesafe.namedanonspaceTest4(val) != val) throw new Exception("namedanonspaceTest 4 failed");
}
{
TemplateClassInt t = new TemplateClassInt();
TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
if (t.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest 1 failed");
if (t.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest 2 failed");
if (t.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest 3 failed");
if (t.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest 4 failed");
if (t.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest 5 failed");
if (t.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest 6 failed");
if (t.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest 7 failed");
if (t.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest 8 failed");
if (t.scientistsTest9(galileo) != galileo) throw new Exception("scientistsTest 9 failed");
// if (t.scientistsTestA(galileo) != galileo) throw new Exception("scientistsTest A failed");
if (t.scientistsTestB(galileo) != galileo) throw new Exception("scientistsTest B failed");
// if (t.scientistsTestC(galileo) != galileo) throw new Exception("scientistsTest C failed");
if (t.scientistsTestD(galileo) != galileo) throw new Exception("scientistsTest D failed");
if (t.scientistsTestE(galileo) != galileo) throw new Exception("scientistsTest E failed");
if (t.scientistsTestF(galileo) != galileo) throw new Exception("scientistsTest F failed");
if (t.scientistsTestG(galileo) != galileo) throw new Exception("scientistsTest G failed");
if (t.scientistsTestH(galileo) != galileo) throw new Exception("scientistsTest H failed");
if (t.scientistsTestI(galileo) != galileo) throw new Exception("scientistsTest I failed");
if (t.scientistsTestJ(galileo) != galileo) throw new Exception("scientistsTest J failed");
if (enum_thorough_typesafe.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest Global 1 failed");
if (enum_thorough_typesafe.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest Global 2 failed");
if (enum_thorough_typesafe.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest Global 3 failed");
if (enum_thorough_typesafe.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest Global 4 failed");
if (enum_thorough_typesafe.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest Global 5 failed");
if (enum_thorough_typesafe.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest Global 6 failed");
if (enum_thorough_typesafe.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest Global 7 failed");
if (enum_thorough_typesafe.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest Global 8 failed");
}
{
TClassInt t = new TClassInt();
TClassInt.scientists bell = TClassInt.scientists.bell;
TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
if (t.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest 1 failed");
if (t.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest 2 failed");
if (t.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest 3 failed");
if (t.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest 4 failed");
if (t.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest 5 failed");
if (t.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest 6 failed");
if (t.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest 7 failed");
if (t.scientistsNameTest8(bell) != bell) throw new Exception("scientistsNameTest 8 failed");
if (t.scientistsNameTest9(bell) != bell) throw new Exception("scientistsNameTest 9 failed");
// if (t.scientistsNameTestA(bell) != bell) throw new Exception("scientistsNameTest A failed");
if (t.scientistsNameTestB(bell) != bell) throw new Exception("scientistsNameTest B failed");
// if (t.scientistsNameTestC(bell) != bell) throw new Exception("scientistsNameTest C failed");
if (t.scientistsNameTestD(bell) != bell) throw new Exception("scientistsNameTest D failed");
if (t.scientistsNameTestE(bell) != bell) throw new Exception("scientistsNameTest E failed");
if (t.scientistsNameTestF(bell) != bell) throw new Exception("scientistsNameTest F failed");
if (t.scientistsNameTestG(bell) != bell) throw new Exception("scientistsNameTest G failed");
if (t.scientistsNameTestH(bell) != bell) throw new Exception("scientistsNameTest H failed");
if (t.scientistsNameTestI(bell) != bell) throw new Exception("scientistsNameTest I failed");
if (t.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest 1 failed");
if (t.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest 2 failed");
if (t.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest 3 failed");
if (t.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest 4 failed");
if (t.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest 5 failed");
if (t.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest 6 failed");
if (t.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest 7 failed");
if (t.scientistsOtherTest1(galileo) != galileo) throw new Exception("scientistsOtherTest 1 failed");
if (t.scientistsOtherTest2(galileo) != galileo) throw new Exception("scientistsOtherTest 2 failed");
if (t.scientistsOtherTest3(galileo) != galileo) throw new Exception("scientistsOtherTest 3 failed");
if (t.scientistsOtherTest4(galileo) != galileo) throw new Exception("scientistsOtherTest 4 failed");
if (t.scientistsOtherTest5(galileo) != galileo) throw new Exception("scientistsOtherTest 5 failed");
if (t.scientistsOtherTest6(galileo) != galileo) throw new Exception("scientistsOtherTest 6 failed");
if (t.scientistsOtherTest7(galileo) != galileo) throw new Exception("scientistsOtherTest 7 failed");
if (enum_thorough_typesafe.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest Global 1 failed");
if (enum_thorough_typesafe.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest Global 2 failed");
if (enum_thorough_typesafe.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest Global 3 failed");
if (enum_thorough_typesafe.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest Global 4 failed");
if (enum_thorough_typesafe.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest Global 5 failed");
if (enum_thorough_typesafe.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest Global 6 failed");
if (enum_thorough_typesafe.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest Global 7 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 1 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 2 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 3 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 4 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 5 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 6 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 7 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest8(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 8 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTest9(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 9 failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestA(bell) != bell) throw new Exception("scientistsNameSpaceTest Global A failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestB(bell) != bell) throw new Exception("scientistsNameSpaceTest Global B failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestC(bell) != bell) throw new Exception("scientistsNameSpaceTest Global C failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestD(bell) != bell) throw new Exception("scientistsNameSpaceTest Global D failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestE(bell) != bell) throw new Exception("scientistsNameSpaceTest Global E failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestF(bell) != bell) throw new Exception("scientistsNameSpaceTest Global F failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestG(bell) != bell) throw new Exception("scientistsNameSpaceTest Global G failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestH(bell) != bell) throw new Exception("scientistsNameSpaceTest Global H failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestI(bell) != bell) throw new Exception("scientistsNameSpaceTest Global I failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestJ(bell) != bell) throw new Exception("scientistsNameSpaceTest Global J failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestK(bell) != bell) throw new Exception("scientistsNameSpaceTest Global K failed");
if (enum_thorough_typesafe.scientistsNameSpaceTestL(bell) != bell) throw new Exception("scientistsNameSpaceTest Global L failed");
}
{
newname val = newname.argh;
if (enum_thorough_typesafe.renameTest1(val) != val) throw new Exception("renameTest Global 1 failed");
if (enum_thorough_typesafe.renameTest2(val) != val) throw new Exception("renameTest Global 2 failed");
}
{
NewNameStruct n = new NewNameStruct();
if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 1 failed");
if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 2 failed");
if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest 3 failed");
if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 4 failed");
if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 5 failed");
if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest 6 failed");
}
{
if (enum_thorough_typesafe.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest Global 3 failed");
if (enum_thorough_typesafe.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest Global 4 failed");
if (enum_thorough_typesafe.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 5 failed");
if (enum_thorough_typesafe.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 6 failed");
if (enum_thorough_typesafe.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest Global 7 failed");
}
{
TreesClass t = new TreesClass();
TreesClass.trees pine = TreesClass.trees.pine;
if (t.treesTest1(pine) != pine) throw new Exception("treesTest 1 failed");
if (t.treesTest2(pine) != pine) throw new Exception("treesTest 2 failed");
if (t.treesTest3(pine) != pine) throw new Exception("treesTest 3 failed");
if (t.treesTest4(pine) != pine) throw new Exception("treesTest 4 failed");
if (t.treesTest5(pine) != pine) throw new Exception("treesTest 5 failed");
if (t.treesTest6(pine) != pine) throw new Exception("treesTest 6 failed");
if (t.treesTest7(pine) != pine) throw new Exception("treesTest 7 failed");
if (t.treesTest8(pine) != pine) throw new Exception("treesTest 8 failed");
if (t.treesTest9(pine) != pine) throw new Exception("treesTest 9 failed");
if (t.treesTestA(pine) != pine) throw new Exception("treesTest A failed");
if (t.treesTestB(pine) != pine) throw new Exception("treesTest B failed");
if (t.treesTestC(pine) != pine) throw new Exception("treesTest C failed");
if (t.treesTestD(pine) != pine) throw new Exception("treesTest D failed");
if (t.treesTestE(pine) != pine) throw new Exception("treesTest E failed");
if (t.treesTestF(pine) != pine) throw new Exception("treesTest F failed");
if (t.treesTestG(pine) != pine) throw new Exception("treesTest G failed");
if (t.treesTestH(pine) != pine) throw new Exception("treesTest H failed");
if (t.treesTestI(pine) != pine) throw new Exception("treesTest I failed");
if (t.treesTestJ(pine) != pine) throw new Exception("treesTest J failed");
if (t.treesTestK(pine) != pine) throw new Exception("treesTest K failed");
if (t.treesTestL(pine) != pine) throw new Exception("treesTest L failed");
if (t.treesTestM(pine) != pine) throw new Exception("treesTest M failed");
if (t.treesTestN(pine) != pine) throw new Exception("treesTest N failed");
if (t.treesTestO(pine) != pine) throw new Exception("treesTest O failed");
if (enum_thorough_typesafe.treesTest1(pine) != pine) throw new Exception("treesTest Global 1 failed");
if (enum_thorough_typesafe.treesTest2(pine) != pine) throw new Exception("treesTest Global 2 failed");
if (enum_thorough_typesafe.treesTest3(pine) != pine) throw new Exception("treesTest Global 3 failed");
if (enum_thorough_typesafe.treesTest4(pine) != pine) throw new Exception("treesTest Global 4 failed");
if (enum_thorough_typesafe.treesTest5(pine) != pine) throw new Exception("treesTest Global 5 failed");
if (enum_thorough_typesafe.treesTest6(pine) != pine) throw new Exception("treesTest Global 6 failed");
if (enum_thorough_typesafe.treesTest7(pine) != pine) throw new Exception("treesTest Global 7 failed");
if (enum_thorough_typesafe.treesTest8(pine) != pine) throw new Exception("treesTest Global 8 failed");
if (enum_thorough_typesafe.treesTest9(pine) != pine) throw new Exception("treesTest Global 9 failed");
if (enum_thorough_typesafe.treesTestA(pine) != pine) throw new Exception("treesTest Global A failed");
if (enum_thorough_typesafe.treesTestB(pine) != pine) throw new Exception("treesTest Global B failed");
if (enum_thorough_typesafe.treesTestC(pine) != pine) throw new Exception("treesTest Global C failed");
if (enum_thorough_typesafe.treesTestD(pine) != pine) throw new Exception("treesTest Global D failed");
if (enum_thorough_typesafe.treesTestE(pine) != pine) throw new Exception("treesTest Global E failed");
if (enum_thorough_typesafe.treesTestF(pine) != pine) throw new Exception("treesTest Global F failed");
if (enum_thorough_typesafe.treesTestG(pine) != pine) throw new Exception("treesTest Global G failed");
if (enum_thorough_typesafe.treesTestH(pine) != pine) throw new Exception("treesTest Global H failed");
if (enum_thorough_typesafe.treesTestI(pine) != pine) throw new Exception("treesTest Global I failed");
if (enum_thorough_typesafe.treesTestJ(pine) != pine) throw new Exception("treesTest Global J failed");
if (enum_thorough_typesafe.treesTestK(pine) != pine) throw new Exception("treesTest Global K failed");
if (enum_thorough_typesafe.treesTestL(pine) != pine) throw new Exception("treesTest Global L failed");
if (enum_thorough_typesafe.treesTestM(pine) != pine) throw new Exception("treesTest Global M failed");
// if (enum_thorough_typesafe.treesTestN(pine) != pine) throw new Exception("treesTest Global N failed");
if (enum_thorough_typesafe.treesTestO(pine) != pine) throw new Exception("treesTest Global O failed");
if (enum_thorough_typesafe.treesTestP(pine) != pine) throw new Exception("treesTest Global P failed");
if (enum_thorough_typesafe.treesTestQ(pine) != pine) throw new Exception("treesTest Global Q failed");
if (enum_thorough_typesafe.treesTestR(pine) != pine) throw new Exception("treesTest Global R failed");
}
{
HairStruct h = new HairStruct();
HairStruct.hair ginger = HairStruct.hair.ginger;
if (h.hairTest1(ginger) != ginger) throw new Exception("hairTest 1 failed");
if (h.hairTest2(ginger) != ginger) throw new Exception("hairTest 2 failed");
if (h.hairTest3(ginger) != ginger) throw new Exception("hairTest 3 failed");
if (h.hairTest4(ginger) != ginger) throw new Exception("hairTest 4 failed");
if (h.hairTest5(ginger) != ginger) throw new Exception("hairTest 5 failed");
if (h.hairTest6(ginger) != ginger) throw new Exception("hairTest 6 failed");
if (h.hairTest7(ginger) != ginger) throw new Exception("hairTest 7 failed");
if (h.hairTest8(ginger) != ginger) throw new Exception("hairTest 8 failed");
if (h.hairTest9(ginger) != ginger) throw new Exception("hairTest 9 failed");
if (h.hairTestA(ginger) != ginger) throw new Exception("hairTest A failed");
if (h.hairTestB(ginger) != ginger) throw new Exception("hairTest B failed");
colour red = colour.red;
if (h.colourTest1(red) != red) throw new Exception("colourTest HairStruct 1 failed");
if (h.colourTest2(red) != red) throw new Exception("colourTest HairStruct 2 failed");
if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest HairStruct 1 failed");
if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new Exception("namedanonspaceTest HairStruct 1 failed");
TreesClass.trees fir = TreesClass.trees.fir;
if (h.treesGlobalTest1(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 1 failed");
if (h.treesGlobalTest2(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 2 failed");
if (h.treesGlobalTest3(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 3 failed");
if (h.treesGlobalTest4(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 4 failed");
}
{
HairStruct.hair blonde = HairStruct.hair.blonde;
if (enum_thorough_typesafe.hairTest1(blonde) != blonde) throw new Exception("hairTest Global 1 failed");
if (enum_thorough_typesafe.hairTest2(blonde) != blonde) throw new Exception("hairTest Global 2 failed");
if (enum_thorough_typesafe.hairTest3(blonde) != blonde) throw new Exception("hairTest Global 3 failed");
if (enum_thorough_typesafe.hairTest4(blonde) != blonde) throw new Exception("hairTest Global 4 failed");
if (enum_thorough_typesafe.hairTest5(blonde) != blonde) throw new Exception("hairTest Global 5 failed");
if (enum_thorough_typesafe.hairTest6(blonde) != blonde) throw new Exception("hairTest Global 6 failed");
if (enum_thorough_typesafe.hairTest7(blonde) != blonde) throw new Exception("hairTest Global 7 failed");
if (enum_thorough_typesafe.hairTest8(blonde) != blonde) throw new Exception("hairTest Global 8 failed");
if (enum_thorough_typesafe.hairTest9(blonde) != blonde) throw new Exception("hairTest Global 9 failed");
if (enum_thorough_typesafe.hairTestA(blonde) != blonde) throw new Exception("hairTest Global A failed");
if (enum_thorough_typesafe.hairTestB(blonde) != blonde) throw new Exception("hairTest Global B failed");
if (enum_thorough_typesafe.hairTestC(blonde) != blonde) throw new Exception("hairTest Global C failed");
if (enum_thorough_typesafe.hairTestA1(blonde) != blonde) throw new Exception("hairTest Global A1 failed");
if (enum_thorough_typesafe.hairTestA2(blonde) != blonde) throw new Exception("hairTest Global A2 failed");
if (enum_thorough_typesafe.hairTestA3(blonde) != blonde) throw new Exception("hairTest Global A3 failed");
if (enum_thorough_typesafe.hairTestA4(blonde) != blonde) throw new Exception("hairTest Global A4 failed");
if (enum_thorough_typesafe.hairTestA5(blonde) != blonde) throw new Exception("hairTest Global A5 failed");
if (enum_thorough_typesafe.hairTestA6(blonde) != blonde) throw new Exception("hairTest Global A6 failed");
if (enum_thorough_typesafe.hairTestA7(blonde) != blonde) throw new Exception("hairTest Global A7 failed");
if (enum_thorough_typesafe.hairTestA8(blonde) != blonde) throw new Exception("hairTest Global A8 failed");
if (enum_thorough_typesafe.hairTestA9(blonde) != blonde) throw new Exception("hairTest Global A9 failed");
if (enum_thorough_typesafe.hairTestAA(blonde) != blonde) throw new Exception("hairTest Global AA failed");
if (enum_thorough_typesafe.hairTestAB(blonde) != blonde) throw new Exception("hairTest Global AB failed");
if (enum_thorough_typesafe.hairTestAC(blonde) != blonde) throw new Exception("hairTest Global AC failed");
if (enum_thorough_typesafe.hairTestB1(blonde) != blonde) throw new Exception("hairTest Global B1 failed");
if (enum_thorough_typesafe.hairTestB2(blonde) != blonde) throw new Exception("hairTest Global B2 failed");
if (enum_thorough_typesafe.hairTestB3(blonde) != blonde) throw new Exception("hairTest Global B3 failed");
if (enum_thorough_typesafe.hairTestB4(blonde) != blonde) throw new Exception("hairTest Global B4 failed");
if (enum_thorough_typesafe.hairTestB5(blonde) != blonde) throw new Exception("hairTest Global B5 failed");
if (enum_thorough_typesafe.hairTestB6(blonde) != blonde) throw new Exception("hairTest Global B6 failed");
if (enum_thorough_typesafe.hairTestB7(blonde) != blonde) throw new Exception("hairTest Global B7 failed");
if (enum_thorough_typesafe.hairTestB8(blonde) != blonde) throw new Exception("hairTest Global B8 failed");
if (enum_thorough_typesafe.hairTestB9(blonde) != blonde) throw new Exception("hairTest Global B9 failed");
if (enum_thorough_typesafe.hairTestBA(blonde) != blonde) throw new Exception("hairTest Global BA failed");
if (enum_thorough_typesafe.hairTestBB(blonde) != blonde) throw new Exception("hairTest Global BB failed");
if (enum_thorough_typesafe.hairTestBC(blonde) != blonde) throw new Exception("hairTest Global BC failed");
if (enum_thorough_typesafe.hairTestC1(blonde) != blonde) throw new Exception("hairTest Global C1 failed");
if (enum_thorough_typesafe.hairTestC2(blonde) != blonde) throw new Exception("hairTest Global C2 failed");
if (enum_thorough_typesafe.hairTestC3(blonde) != blonde) throw new Exception("hairTest Global C3 failed");
if (enum_thorough_typesafe.hairTestC4(blonde) != blonde) throw new Exception("hairTest Global C4 failed");
if (enum_thorough_typesafe.hairTestC5(blonde) != blonde) throw new Exception("hairTest Global C5 failed");
if (enum_thorough_typesafe.hairTestC6(blonde) != blonde) throw new Exception("hairTest Global C6 failed");
if (enum_thorough_typesafe.hairTestC7(blonde) != blonde) throw new Exception("hairTest Global C7 failed");
if (enum_thorough_typesafe.hairTestC8(blonde) != blonde) throw new Exception("hairTest Global C8 failed");
if (enum_thorough_typesafe.hairTestC9(blonde) != blonde) throw new Exception("hairTest Global C9 failed");
if (enum_thorough_typesafe.hairTestCA(blonde) != blonde) throw new Exception("hairTest Global CA failed");
if (enum_thorough_typesafe.hairTestCB(blonde) != blonde) throw new Exception("hairTest Global CB failed");
if (enum_thorough_typesafe.hairTestCC(blonde) != blonde) throw new Exception("hairTest Global CC failed");
}
{
FirStruct f = new FirStruct();
HairStruct.hair blonde = HairStruct.hair.blonde;
if (f.hairTestFir1(blonde) != blonde) throw new Exception("hairTestFir 1 failed");
if (f.hairTestFir2(blonde) != blonde) throw new Exception("hairTestFir 2 failed");
if (f.hairTestFir3(blonde) != blonde) throw new Exception("hairTestFir 3 failed");
if (f.hairTestFir4(blonde) != blonde) throw new Exception("hairTestFir 4 failed");
if (f.hairTestFir5(blonde) != blonde) throw new Exception("hairTestFir 5 failed");
if (f.hairTestFir6(blonde) != blonde) throw new Exception("hairTestFir 6 failed");
if (f.hairTestFir7(blonde) != blonde) throw new Exception("hairTestFir 7 failed");
if (f.hairTestFir8(blonde) != blonde) throw new Exception("hairTestFir 8 failed");
if (f.hairTestFir9(blonde) != blonde) throw new Exception("hairTestFir 9 failed");
if (f.hairTestFirA(blonde) != blonde) throw new Exception("hairTestFir A failed");
}
{
enum_thorough_typesafe.GlobalInstance = enum_thorough_typesafe.globalinstance2;
if (enum_thorough_typesafe.GlobalInstance != enum_thorough_typesafe.globalinstance2) throw new Exception("GlobalInstance 1 failed");
Instances i = new Instances();
i.MemberInstance = Instances.memberinstance3;
if (i.MemberInstance != Instances.memberinstance3) throw new Exception("MemberInstance 1 failed");
}
// ignore enum item tests start
{
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_zero).swigValue != 0) throw new Exception("ignoreATest 0 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_three).swigValue != 3) throw new Exception("ignoreATest 3 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_ten).swigValue != 10) throw new Exception("ignoreATest 10 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_eleven).swigValue != 11) throw new Exception("ignoreATest 11 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirteen).swigValue != 13) throw new Exception("ignoreATest 13 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_fourteen).swigValue != 14) throw new Exception("ignoreATest 14 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_twenty).swigValue != 20) throw new Exception("ignoreATest 20 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirty).swigValue != 30) throw new Exception("ignoreATest 30 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirty_two).swigValue != 32) throw new Exception("ignoreATest 32 failed");
if (enum_thorough_typesafe.ignoreATest(IgnoreTest.IgnoreA.ignoreA_thirty_three).swigValue != 33) throw new Exception("ignoreATest 33 failed");
}
{
if (enum_thorough_typesafe.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_eleven).swigValue != 11) throw new Exception("ignoreBTest 11 failed");
if (enum_thorough_typesafe.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_twelve).swigValue != 12) throw new Exception("ignoreBTest 12 failed");
if (enum_thorough_typesafe.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_thirty_one).swigValue != 31) throw new Exception("ignoreBTest 31 failed");
if (enum_thorough_typesafe.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_thirty_two).swigValue != 32) throw new Exception("ignoreBTest 32 failed");
if (enum_thorough_typesafe.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_forty_one).swigValue != 41) throw new Exception("ignoreBTest 41 failed");
if (enum_thorough_typesafe.ignoreBTest(IgnoreTest.IgnoreB.ignoreB_forty_two).swigValue != 42) throw new Exception("ignoreBTest 42 failed");
}
{
if (enum_thorough_typesafe.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_ten).swigValue != 10) throw new Exception("ignoreCTest 10 failed");
if (enum_thorough_typesafe.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_twelve).swigValue != 12) throw new Exception("ignoreCTest 12 failed");
if (enum_thorough_typesafe.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_thirty).swigValue != 30) throw new Exception("ignoreCTest 30 failed");
if (enum_thorough_typesafe.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_thirty_two).swigValue != 32) throw new Exception("ignoreCTest 32 failed");
if (enum_thorough_typesafe.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_forty).swigValue != 40) throw new Exception("ignoreCTest 40 failed");
if (enum_thorough_typesafe.ignoreCTest(IgnoreTest.IgnoreC.ignoreC_forty_two).swigValue != 42) throw new Exception("ignoreCTest 42 failed");
}
{
if (enum_thorough_typesafe.ignoreDTest(IgnoreTest.IgnoreD.ignoreD_twenty_one).swigValue != 21) throw new Exception("ignoreDTest 21 failed");
if (enum_thorough_typesafe.ignoreDTest(IgnoreTest.IgnoreD.ignoreD_twenty_two).swigValue != 22) throw new Exception("ignoreDTest 22 failed");
}
{
if (enum_thorough_typesafe.ignoreETest(IgnoreTest.IgnoreE.ignoreE_zero).swigValue != 0) throw new Exception("ignoreETest 0 failed");
if (enum_thorough_typesafe.ignoreETest(IgnoreTest.IgnoreE.ignoreE_twenty_one).swigValue != 21) throw new Exception("ignoreETest 21 failed");
if (enum_thorough_typesafe.ignoreETest(IgnoreTest.IgnoreE.ignoreE_twenty_two).swigValue != 22) throw new Exception("ignoreETest 22 failed");
}
// ignore enum item tests end
{
if (enum_thorough_typesafe.repeatTest(repeat.one).swigValue != 1) throw new Exception("repeatTest 1 failed");
if (enum_thorough_typesafe.repeatTest(repeat.initial).swigValue != 1) throw new Exception("repeatTest 2 failed");
if (enum_thorough_typesafe.repeatTest(repeat.two).swigValue != 2) throw new Exception("repeatTest 3 failed");
if (enum_thorough_typesafe.repeatTest(repeat.three).swigValue != 3) throw new Exception("repeatTest 4 failed");
if (enum_thorough_typesafe.repeatTest(repeat.llast).swigValue != 3) throw new Exception("repeatTest 5 failed");
if (enum_thorough_typesafe.repeatTest(repeat.end).swigValue != 3) throw new Exception("repeatTest 6 failed");
}
{
if (enum_thorough_typesafe.enumWithMacroTest(enumWithMacro.ABCD).swigValue != (('A' << 24) | ('B' << 16) | ('C' << 8) | 'D')) throw new Exception("enumWithMacroTest 1 failed");
if (enum_thorough_typesafe.enumWithMacroTest(enumWithMacro.ABCD2).swigValue != enum_thorough_typesafe.enumWithMacroTest(enumWithMacro.ABCD).swigValue) throw new Exception("enumWithMacroTest 2 failed");
}
// different types
{
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typeint).swigValue != 10) throw new Exception("differentTypes 1 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typebooltrue).swigValue != 1) throw new Exception("differentTypes 2 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typebooltwo).swigValue != 2) throw new Exception("differentTypes 3 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typeboolfalse).swigValue != 0) throw new Exception("differentTypes 4 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typechar).swigValue != (int)'C') throw new Exception("differentTypes 5 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typedefaultint).swigValue != (int)'D') throw new Exception("differentTypes 6 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typecharcompound).swigValue != (int)'A' + 1) throw new Exception("differentTypes 7 failed");
if (enum_thorough_typesafe.differentTypesTest(DifferentTypes.typecharcompound2).swigValue != (int)'B' << 2) throw new Exception("differentTypes 8 failed");
int global_enum = enum_thorough_typesafe.global_typeint;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != 10) throw new Exception("global differentTypes 1 failed");
global_enum = enum_thorough_typesafe.global_typeboolfalse;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != 0) throw new Exception("global differentTypes 2 failed");
global_enum = enum_thorough_typesafe.global_typebooltrue;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != 1) throw new Exception("global differentTypes 3 failed");
global_enum = enum_thorough_typesafe.global_typebooltwo;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != 2) throw new Exception("global differentTypes 4 failed");
global_enum = enum_thorough_typesafe.global_typechar;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != 'C') throw new Exception("global differentTypes 5 failed");
global_enum = enum_thorough_typesafe.global_typedefaultint;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != 'D') throw new Exception("global differentTypes 6 failed");
global_enum = enum_thorough_typesafe.global_typecharcompound;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != (int)'A' + 1) throw new Exception("global differentTypes 7 failed");
global_enum = enum_thorough_typesafe.global_typecharcompound2;
if (enum_thorough_typesafe.globalDifferentTypesTest(global_enum) != (int)'B' << 2) throw new Exception("global differentTypes 8 failed");
}
}
}
using System;
using exception_orderNamespace;
public class runme {
static void Main() {
A a = new A();
try {
a.foo();
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ E1 exception thrown")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
a.bar();
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ E2 exception thrown")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
a.foobar();
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "postcatch unknown")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
a.barfoo(1);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ E1 exception thrown")
throw new ApplicationException("bad exception order: " + e.Message);
}
try {
a.barfoo(2);
throw new Exception("missed exception");
} catch (ApplicationException e) {
if (e.Message != "C++ E2 * exception thrown")
throw new ApplicationException("bad exception order: " + e.Message);
}
}
}
using System;
using friendsNamespace;
public class friends_runme {
public static void Main() {
A a = new A(2);
if (friends.get_val1(a) != 2)
throw new Exception("failed");
if (friends.get_val2(a) != 4)
throw new Exception("failed");
if (friends.get_val3(a) != 6)
throw new Exception("failed");
// nice overload working fine
if (friends.get_val1(1,2,3) != 1)
throw new Exception("failed");
B b = new B(3);
// David's case
if (friends.mix(a,b) != 5)
throw new Exception("failed");
D_d di = new D_d(2);
D_d dd = new D_d(3.3);
// incredible template overloading working just fine
if (friends.get_val1(di) != 2)
throw new Exception("failed");
if (friends.get_val1(dd) != 3.3)
throw new Exception("failed");
friends.set(di, 4);
friends.set(dd, 1.3);
if (friends.get_val1(di) != 4)
throw new Exception("failed");
if (friends.get_val1(dd) != 1.3)
throw new Exception("failed");
}
}
using System;
using importsNamespace;
public class runme
{
static void Main() {
B b = new B();
b.hello(); //call member function in A which is in a different SWIG generated library.
b.bye();
if (b.member_virtual_test(A.MemberEnum.memberenum1) != A.MemberEnum.memberenum2)
throw new Exception("Test 1 failed");
if (b.global_virtual_test(GlobalEnum.globalenum1) != GlobalEnum.globalenum2)
throw new Exception("Test 2 failed");
imports_b.global_test(A.MemberEnum.memberenum1);
}
}
using System;
using inherit_target_languageNamespace;
public class inherit_target_language_runme {
public static void Main() {
new Derived1().targetLanguageBaseMethod();
new Derived2().targetLanguageBaseMethod();
new MultipleDerived1().targetLanguageBaseMethod();
new MultipleDerived2().targetLanguageBaseMethod();
new MultipleDerived3().f();
new MultipleDerived4().g();
BaseX baseX = new BaseX();
baseX.basex();
baseX.targetLanguageBase2Method();
DerivedX derivedX = new DerivedX();
derivedX.basex();
derivedX.derivedx();
derivedX.targetLanguageBase2Method();
}
}
/***********************************************************************************************
NOTE: This is a custom testcase and should be run using make intermediary_classname.customtest
***********************************************************************************************/
using System;
using intermediary_classnameNamespace;
public class runme
{
static void Main()
{
// test the renamed module class is correctly named
double d = intermediary_classnameModule.maxdouble(10.0, 20.0);
if (d!=20.0) throw new Exception("Test failed");
// test the renamed intermediary class is correctly named
IntPtr ptr = intermediary_classname.new_vecdouble(10);
intermediary_classname.delete_vecdouble(new System.Runtime.InteropServices.HandleRef(null,ptr));
}
}
// Ported from Python li_attribute_runme.py
using System;
using li_attributeNamespace;
public class li_attribute_runme {
public static void Main() {
A aa = new A(1,2,3);
if (aa.a != 1)
throw new ApplicationException("error");
aa.a = 3;
if (aa.a != 3)
throw new ApplicationException("error");
if (aa.b != 2)
throw new ApplicationException("error");
aa.b = 5;
if (aa.b != 5)
throw new ApplicationException("error");
if (aa.d != aa.b)
throw new ApplicationException("error");
if (aa.c != 3)
throw new ApplicationException("error");
//aa.c = 5;
//if (aa.c != 3)
// throw new ApplicationException("error");
Param_i pi = new Param_i(7);
if (pi.value != 7)
throw new ApplicationException("error");
pi.value=3;
if (pi.value != 3)
throw new ApplicationException("error");
B b = new B(aa);
if (b.a.c != 3)
throw new ApplicationException("error");
// class/struct attribute with get/set methods using return/pass by reference
MyFoo myFoo = new MyFoo();
myFoo.x = 8;
MyClass myClass = new MyClass();
myClass.Foo = myFoo;
if (myClass.Foo.x != 8)
throw new ApplicationException("error");
// class/struct attribute with get/set methods using return/pass by value
MyClassVal myClassVal = new MyClassVal();
if (myClassVal.ReadWriteFoo.x != -1)
throw new ApplicationException("error");
if (myClassVal.ReadOnlyFoo.x != -1)
throw new ApplicationException("error");
myClassVal.ReadWriteFoo = myFoo;
if (myClassVal.ReadWriteFoo.x != 8)
throw new ApplicationException("error");
if (myClassVal.ReadOnlyFoo.x != 8)
throw new ApplicationException("error");
// string attribute with get/set methods using return/pass by value
MyStringyClass myStringClass = new MyStringyClass("initial string");
if (myStringClass.ReadWriteString != "initial string")
throw new ApplicationException("error");
if (myStringClass.ReadOnlyString != "initial string")
throw new ApplicationException("error");
myStringClass.ReadWriteString = "changed string";
if (myStringClass.ReadWriteString != "changed string")
throw new ApplicationException("error");
if (myStringClass.ReadOnlyString != "changed string")
throw new ApplicationException("error");
}
}
using System;
using li_boost_shared_ptr_bitsNamespace;
public class runme
{
static void Main()
{
VectorIntHolder v = new VectorIntHolder();
v.Add(new IntHolder(11));
v.Add(new IntHolder(22));
v.Add(new IntHolder(33));
int sum = li_boost_shared_ptr_bits.sum(v);
if (sum != 66)
throw new ApplicationException("sum is wrong");
HiddenDestructor hidden = HiddenDestructor.create();
hidden.Dispose();
HiddenPrivateDestructor hiddenPrivate = HiddenPrivateDestructor.create();
if (HiddenPrivateDestructor.DeleteCount != 0)
throw new ApplicationException("Count should be zero");
hiddenPrivate.Dispose();
if (HiddenPrivateDestructor.DeleteCount != 1)
throw new ApplicationException("Count should be one");
}
}
using System;
using li_boost_shared_ptr_directorNamespace;
public class li_boost_shared_ptr_director_runme {
private static void check(int got, int expected) {
if (got != expected)
throw new Exception("Failed, got: " + got + " expected: " + expected);
}
public static void Main() {
Derived a = new Derived(false);
Derived b = new Derived(true);
check(li_boost_shared_ptr_director.call_ret_c_shared_ptr(a), 1);
check(li_boost_shared_ptr_director.call_ret_c_shared_ptr(b), -1);
check(li_boost_shared_ptr_director.call_ret_c_by_value(a), 1);
check(li_boost_shared_ptr_director.call_ret_c_shared_ptr(a), 1);
check(li_boost_shared_ptr_director.call_ret_c_shared_ptr(b), -1);
check(li_boost_shared_ptr_director.call_ret_c_by_value(a), 1);
check(li_boost_shared_ptr_director.call_take_c_by_value(a), 5);
check(li_boost_shared_ptr_director.call_take_c_by_ref(a), 6);
check(li_boost_shared_ptr_director.call_take_c_by_pointer(a), 7);
check(li_boost_shared_ptr_director.call_take_c_by_pointer_ref(a), 8);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_value(a), 9);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_ref(a), 10);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_pointer(a), 11);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_pointer_ref(a), 12);
check(li_boost_shared_ptr_director.call_take_c_by_pointer_with_null(a), -2);
check(li_boost_shared_ptr_director.call_take_c_by_pointer_ref_with_null(a), -3);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_value_with_null(a), -4);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_ref_with_null(a), -5);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_pointer_with_null(a), -6);
check(li_boost_shared_ptr_director.call_take_c_shared_ptr_by_pointer_ref_with_null(a), -7);
}
}
class Derived : Base {
private bool return_none;
public Derived(bool flag) : base() {
this.return_none = flag;
}
public override C ret_c_shared_ptr() {
if (this.return_none)
return null;
else
return new C();
}
public override C ret_c_by_value() {
return new C();
}
public override int take_c_by_value(C c) {
return c.get_m();
}
public override int take_c_by_ref(C c) {
return c.get_m();
}
public override int take_c_by_pointer(C c) {
if (c != null)
return c.get_m();
else
return -2;
}
public override int take_c_by_pointer_ref(C c) {
if (c != null)
return c.get_m();
else
return -3;
}
public override int take_c_shared_ptr_by_value(C c) {
if (c != null)
return c.get_m();
else
return -4;
}
public override int take_c_shared_ptr_by_ref(C c) {
if (c != null)
return c.get_m();
else
return -5;
}
public override int take_c_shared_ptr_by_pointer(C c) {
if (c != null)
return c.get_m();
else
return -6;
}
public override int take_c_shared_ptr_by_pointer_ref(C c) {
if (c != null)
return c.get_m();
else
return -7;
}
}
using System;
using li_boost_shared_ptrNamespace;
public class runme
{
// Debugging flag
public static bool debug = false;
private static void WaitForGC()
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(10);
}
static void Main()
{
if (debug)
Console.WriteLine("Started");
li_boost_shared_ptr.debug_shared=debug;
// Change loop count to run for a long time to monitor memory
const int loopCount = 1; //50000;
for (int i=0; i<loopCount; i++) {
new runme().runtest();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
if (i%100 == 0) {
System.Threading.Thread.Sleep(1); // give some time to the lower priority finalizer thread
}
}
if (debug)
Console.WriteLine("Nearly finished");
{
int countdown = 500;
int expectedCount = 1;
while (true) {
WaitForGC();
if (--countdown == 0)
break;
if (Klass.getTotal_count() == expectedCount) // Expect the one global variable (GlobalValue)
break;
}
int actualCount = Klass.getTotal_count();
if (actualCount != expectedCount)
Console.Error.WriteLine("Expected count: " + expectedCount + " Actual count: " + actualCount); // Finalizers are not guaranteed to be run and sometimes they just don't
}
int wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count();
if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING)
if (wrapper_count != 1) // Expect the one global variable (GlobalSmartValue)
throw new ApplicationException("shared_ptr wrapper count=" + wrapper_count);
if (debug)
Console.WriteLine("Finished");
}
private void runtest() {
// simple shared_ptr usage - created in C++
{
Klass k = new Klass("me oh my");
String val = k.getValue();
verifyValue("me oh my", val);
verifyCount(1, k);
}
// simple shared_ptr usage - not created in C++
{
Klass k = li_boost_shared_ptr.factorycreate();
String val = k.getValue();
verifyValue("factorycreate", val);
verifyCount(1, k);
}
// pass by shared_ptr
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.smartpointertest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointertest", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// pass by shared_ptr pointer
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.smartpointerpointertest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointerpointertest", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// pass by shared_ptr reference
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.smartpointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointerreftest", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// pass by shared_ptr pointer reference
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointerpointerreftest", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// const pass by shared_ptr
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.constsmartpointertest(k);
String val = kret.getValue();
verifyValue("me oh my", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// const pass by shared_ptr pointer
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.constsmartpointerpointertest(k);
String val = kret.getValue();
verifyValue("me oh my", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// const pass by shared_ptr reference
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.constsmartpointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my", val);
verifyCount(2, k);
verifyCount(2, kret);
}
// pass by value
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.valuetest(k);
String val = kret.getValue();
verifyValue("me oh my valuetest", val);
verifyCount(1, k);
verifyCount(1, kret);
}
// pass by pointer
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.pointertest(k);
String val = kret.getValue();
verifyValue("me oh my pointertest", val);
verifyCount(1, k);
verifyCount(1, kret);
}
// pass by reference
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.reftest(k);
String val = kret.getValue();
verifyValue("me oh my reftest", val);
verifyCount(1, k);
verifyCount(1, kret);
}
// pass by pointer reference
{
Klass k = new Klass("me oh my");
Klass kret = li_boost_shared_ptr.pointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my pointerreftest", val);
verifyCount(1, k);
verifyCount(1, kret);
}
// null tests
{
Klass k = null;
// TODO: add in const versions too
if (li_boost_shared_ptr.smartpointertest(k) != null)
throw new ApplicationException("return was not null");
if (li_boost_shared_ptr.smartpointerpointertest(k) != null)
throw new ApplicationException("return was not null");
if (li_boost_shared_ptr.smartpointerreftest(k) != null)
throw new ApplicationException("return was not null");
if (li_boost_shared_ptr.smartpointerpointerreftest(k) != null)
throw new ApplicationException("return was not null");
if (li_boost_shared_ptr.nullsmartpointerpointertest(null) != "null pointer")
throw new ApplicationException("not null smartpointer pointer");
try { li_boost_shared_ptr.valuetest(k); throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
if (li_boost_shared_ptr.pointertest(k) != null)
throw new ApplicationException("return was not null");
try { li_boost_shared_ptr.reftest(k); throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
}
// $owner
{
Klass k = li_boost_shared_ptr.pointerownertest();
String val = k.getValue();
verifyValue("pointerownertest", val);
verifyCount(1, k);
}
{
Klass k = li_boost_shared_ptr.smartpointerpointerownertest();
String val = k.getValue();
verifyValue("smartpointerpointerownertest", val);
verifyCount(1, k);
}
////////////////////////////////// Derived classes ////////////////////////////////////////
// derived pass by shared_ptr
{
KlassDerived k = new KlassDerived("me oh my");
KlassDerived kret = li_boost_shared_ptr.derivedsmartptrtest(k);
String val = kret.getValue();
verifyValue("me oh my derivedsmartptrtest-Derived", val);
verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
verifyCount(4, kret);
}
// derived pass by shared_ptr pointer
{
KlassDerived k = new KlassDerived("me oh my");
KlassDerived kret = li_boost_shared_ptr.derivedsmartptrpointertest(k);
String val = kret.getValue();
verifyValue("me oh my derivedsmartptrpointertest-Derived", val);
verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
verifyCount(4, kret);
}
// derived pass by shared_ptr ref
{
KlassDerived k = new KlassDerived("me oh my");
KlassDerived kret = li_boost_shared_ptr.derivedsmartptrreftest(k);
String val = kret.getValue();
verifyValue("me oh my derivedsmartptrreftest-Derived", val);
verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
verifyCount(4, kret);
}
// derived pass by shared_ptr pointer ref
{
KlassDerived k = new KlassDerived("me oh my");
KlassDerived kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val);
verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
verifyCount(4, kret);
}
// derived pass by pointer
{
KlassDerived k = new KlassDerived("me oh my");
KlassDerived kret = li_boost_shared_ptr.derivedpointertest(k);
String val = kret.getValue();
verifyValue("me oh my derivedpointertest-Derived", val);
verifyCount(2, k); // includes an extra reference for the upcast in the proxy class
verifyCount(2, kret);
}
// derived pass by ref
{
KlassDerived k = new KlassDerived("me oh my");
KlassDerived kret = li_boost_shared_ptr.derivedreftest(k);
String val = kret.getValue();
verifyValue("me oh my derivedreftest-Derived", val);
verifyCount(2, k); // includes an extra reference for the upcast in the proxy class
verifyCount(2, kret);
}
////////////////////////////////// Derived and base class mixed ////////////////////////////////////////
// pass by shared_ptr (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.smartpointertest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointertest-Derived", val);
verifyCount(3, k); // an extra reference for the upcast in the proxy class
verifyCount(3, kret);
}
// pass by shared_ptr pointer (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.smartpointerpointertest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointerpointertest-Derived", val);
verifyCount(3, k); // an extra reference for the upcast in the proxy class
verifyCount(3, kret);
}
// pass by shared_ptr reference (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.smartpointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointerreftest-Derived", val);
verifyCount(3, k); // an extra reference for the upcast in the proxy class
verifyCount(3, kret);
}
// pass by shared_ptr pointer reference (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
String val = kret.getValue();
verifyValue("me oh my smartpointerpointerreftest-Derived", val);
verifyCount(3, k); // an extra reference for the upcast in the proxy class
verifyCount(3, kret);
}
// pass by value (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.valuetest(k);
String val = kret.getValue();
verifyValue("me oh my valuetest", val); // note slicing
verifyCount(2, k); // an extra reference for the upcast in the proxy class
verifyCount(1, kret);
}
// pass by pointer (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.pointertest(k);
String val = kret.getValue();
verifyValue("me oh my pointertest-Derived", val);
verifyCount(2, k); // an extra reference for the upcast in the proxy class
verifyCount(1, kret);
}
// pass by ref (mixed)
{
Klass k = new KlassDerived("me oh my");
Klass kret = li_boost_shared_ptr.reftest(k);
String val = kret.getValue();
verifyValue("me oh my reftest-Derived", val);
verifyCount(2, k); // an extra reference for the upcast in the proxy class
verifyCount(1, kret);
}
// 3rd derived class
{
Klass k = new Klass3rdDerived("me oh my");
String val = k.getValue();
verifyValue("me oh my-3rdDerived", val);
verifyCount(3, k); // 3 classes in inheritance chain == 3 swigCPtr values
val = li_boost_shared_ptr.test3rdupcast(k);
verifyValue("me oh my-3rdDerived", val);
verifyCount(3, k);
}
////////////////////////////////// Member variables ////////////////////////////////////////
// smart pointer by value
{
MemberVariables m = new MemberVariables();
Klass k = new Klass("smart member value");
m.SmartMemberValue = k;
String val = k.getValue();
verifyValue("smart member value", val);
verifyCount(2, k);
Klass kmember = m.SmartMemberValue;
val = kmember.getValue();
verifyValue("smart member value", val);
verifyCount(3, kmember);
verifyCount(3, k);
m.Dispose();
verifyCount(2, kmember);
verifyCount(2, k);
}
// smart pointer by pointer
{
MemberVariables m = new MemberVariables();
Klass k = new Klass("smart member pointer");
m.SmartMemberPointer = k;
String val = k.getValue();
verifyValue("smart member pointer", val);
verifyCount(1, k);
Klass kmember = m.SmartMemberPointer;
val = kmember.getValue();
verifyValue("smart member pointer", val);
verifyCount(2, kmember);
verifyCount(2, k);
m.Dispose();
verifyCount(2, kmember);
verifyCount(2, k);
}
// smart pointer by reference
{
MemberVariables m = new MemberVariables();
Klass k = new Klass("smart member reference");
m.SmartMemberReference = k;
String val = k.getValue();
verifyValue("smart member reference", val);
verifyCount(2, k);
Klass kmember = m.SmartMemberReference;
val = kmember.getValue();
verifyValue("smart member reference", val);
verifyCount(3, kmember);
verifyCount(3, k);
// The C++ reference refers to SmartMemberValue...
Klass kmemberVal = m.SmartMemberValue;
val = kmember.getValue();
verifyValue("smart member reference", val);
verifyCount(4, kmemberVal);
verifyCount(4, kmember);
verifyCount(4, k);
m.Dispose();
verifyCount(3, kmember);
verifyCount(3, k);
}
// plain by value
{
MemberVariables m = new MemberVariables();
Klass k = new Klass("plain member value");
m.MemberValue = k;
String val = k.getValue();
verifyValue("plain member value", val);
verifyCount(1, k);
Klass kmember = m.MemberValue;
val = kmember.getValue();
verifyValue("plain member value", val);
verifyCount(1, kmember);
verifyCount(1, k);
m.Dispose();
verifyCount(1, kmember);
verifyCount(1, k);
}
// plain by pointer
{
MemberVariables m = new MemberVariables();
Klass k = new Klass("plain member pointer");
m.MemberPointer = k;
String val = k.getValue();
verifyValue("plain member pointer", val);
verifyCount(1, k);
Klass kmember = m.MemberPointer;
val = kmember.getValue();
verifyValue("plain member pointer", val);
verifyCount(1, kmember);
verifyCount(1, k);
m.Dispose();
verifyCount(1, kmember);
verifyCount(1, k);
}
// plain by reference
{
MemberVariables m = new MemberVariables();
Klass k = new Klass("plain member reference");
m.MemberReference = k;
String val = k.getValue();
verifyValue("plain member reference", val);
verifyCount(1, k);
Klass kmember = m.MemberReference;
val = kmember.getValue();
verifyValue("plain member reference", val);
verifyCount(1, kmember);
verifyCount(1, k);
m.Dispose();
verifyCount(1, kmember);
verifyCount(1, k);
}
// null member variables
{
MemberVariables m = new MemberVariables();
// shared_ptr by value
Klass k = m.SmartMemberValue;
if (k != null)
throw new ApplicationException("expected null");
m.SmartMemberValue = null;
k = m.SmartMemberValue;
if (k != null)
throw new ApplicationException("expected null");
verifyCount(0, k);
// plain by value
try { m.MemberValue = null; throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
}
////////////////////////////////// Global variables ////////////////////////////////////////
// smart pointer
{
Klass kglobal = li_boost_shared_ptr.GlobalSmartValue;
if (kglobal != null)
throw new ApplicationException("expected null");
Klass k = new Klass("smart global value");
li_boost_shared_ptr.GlobalSmartValue = k;
verifyCount(2, k);
kglobal = li_boost_shared_ptr.GlobalSmartValue;
String val = kglobal.getValue();
verifyValue("smart global value", val);
verifyCount(3, kglobal);
verifyCount(3, k);
verifyValue("smart global value", li_boost_shared_ptr.GlobalSmartValue.getValue());
li_boost_shared_ptr.GlobalSmartValue = null;
}
// plain value
{
Klass kglobal;
Klass k = new Klass("global value");
li_boost_shared_ptr.GlobalValue = k;
verifyCount(1, k);
kglobal = li_boost_shared_ptr.GlobalValue;
String val = kglobal.getValue();
verifyValue("global value", val);
verifyCount(1, kglobal);
verifyCount(1, k);
verifyValue("global value", li_boost_shared_ptr.GlobalValue.getValue());
try { li_boost_shared_ptr.GlobalValue = null; throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
}
// plain pointer
{
Klass kglobal = li_boost_shared_ptr.GlobalPointer;
if (kglobal != null)
throw new ApplicationException("expected null");
Klass k = new Klass("global pointer");
li_boost_shared_ptr.GlobalPointer = k;
verifyCount(1, k);
kglobal = li_boost_shared_ptr.GlobalPointer;
String val = kglobal.getValue();
verifyValue("global pointer", val);
verifyCount(1, kglobal);
verifyCount(1, k);
li_boost_shared_ptr.GlobalPointer = null;
}
// plain reference
{
Klass kglobal;
Klass k = new Klass("global reference");
li_boost_shared_ptr.GlobalReference = k;
verifyCount(1, k);
kglobal = li_boost_shared_ptr.GlobalReference;
String val = kglobal.getValue();
verifyValue("global reference", val);
verifyCount(1, kglobal);
verifyCount(1, k);
try { li_boost_shared_ptr.GlobalReference = null; throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
}
////////////////////////////////// Templates ////////////////////////////////////////
{
PairIntDouble pid = new PairIntDouble(10, 20.2);
if (pid.baseVal1 != 20 || pid.baseVal2 != 40.4)
throw new ApplicationException("Base values wrong");
if (pid.val1 != 10 || pid.val2 != 20.2)
throw new ApplicationException("Derived Values wrong");
}
}
private void verifyValue(String expected, String got) {
if (expected != got)
throw new Exception("verify value failed. Expected: " + expected + " Got: " + got);
}
private void verifyCount(int expected, Klass k) {
int got = li_boost_shared_ptr.use_count(k);
if (expected != got)
throw new Exception("verify use_count failed. Expected: " + expected + " Got: " + got);
}
}
using System;
using li_std_auto_ptrNamespace;
public class li_std_auto_ptr_runme {
private static void WaitForGC()
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(10);
}
public static void Main()
{
Klass k1 = li_std_auto_ptr.makeKlassAutoPtr("first");
if (k1.getLabel() != "first")
throw new Exception("wrong object label");
Klass k2 = li_std_auto_ptr.makeKlassAutoPtr("second");
if (Klass.getTotal_count() != 2)
throw new Exception("number of objects should be 2");
using (Klass k3 = li_std_auto_ptr.makeKlassAutoPtr("second")) {
if (Klass.getTotal_count() != 3)
throw new Exception("number of objects should be 3");
}
if (Klass.getTotal_count() != 2)
throw new Exception("number of objects should be 2");
k1 = null;
{
int countdown = 500;
int expectedCount = 1;
while (true) {
WaitForGC();
if (--countdown == 0)
break;
if (Klass.getTotal_count() == expectedCount)
break;
};
int actualCount = Klass.getTotal_count();
if (actualCount != expectedCount)
Console.Error.WriteLine("Expected count: " + expectedCount + " Actual count: " + actualCount); // Finalizers are not guaranteed to be run and sometimes they just don't
}
if (k2.getLabel() != "second")
throw new Exception("wrong object label");
k2 = null;
{
int countdown = 500;
int expectedCount = 0;
while (true) {
WaitForGC();
if (--countdown == 0)
break;
if (Klass.getTotal_count() == expectedCount)
break;
}
int actualCount = Klass.getTotal_count();
if (actualCount != expectedCount)
Console.Error.WriteLine("Expected count: " + expectedCount + " Actual count: " + actualCount); // Finalizers are not guaranteed to be run and sometimes they just don't
}
}
}
using System;
using li_std_combinationsNamespace;
public class li_std_combinations_runme {
public static void Main() {
VectorPairIntString vpis = new VectorPairIntString();
vpis.Add(new PairIntString(123, "one hundred and twenty three"));
VectorString vs = new VectorString();
vs.Add("hi");
PairIntVectorString pivs = new PairIntVectorString(456, vs);
if (pivs.second[0] != "hi")
throw new ApplicationException("PairIntVectorString");
VectorVectorString vvs = new VectorVectorString();
vvs.Add(vs);
PairIntPairIntString pipis = new PairIntPairIntString(12, new PairIntString(3, "4"));
if (pipis.first != 12)
throw new ApplicationException("PairIntPairIntString");
PairDoubleString pds = new PairDoubleString(12.34, "okay");
VectorPairDoubleString vpds = new VectorPairDoubleString();
vpds.Add(pds);
// Check SWIG_STD_VECTOR_ENHANCED macro - it provides the Contains method
if (!vpds.Contains(pds))
throw new ApplicationException("VectorPairDoubleString");
}
}
// This test tests all the methods in the C# collection wrapper
using System;
using li_std_exceptNamespace;
public class li_std_except_runme {
public static void Main() {
Test test = new Test();
try { test.throw_bad_cast(); throw new Exception("throw_bad_cast failed"); } catch (InvalidCastException) {}
try { test.throw_bad_exception(); throw new Exception("throw_bad_exception failed"); } catch (ApplicationException) {}
try { test.throw_domain_error(); throw new Exception("throw_domain_error failed"); } catch (ApplicationException) {}
try { test.throw_exception(); throw new Exception("throw_exception failed"); } catch (ApplicationException) {}
try { test.throw_invalid_argument(); throw new Exception("throw_invalid_argument failed"); } catch (ArgumentException) {}
try { test.throw_length_error(); throw new Exception("throw_length_error failed"); } catch (IndexOutOfRangeException) {}
try { test.throw_logic_error(); throw new Exception("throw_logic_error failed"); } catch (ApplicationException) {}
try { test.throw_out_of_range(); throw new Exception("throw_out_of_range failed"); } catch (ArgumentOutOfRangeException) {}
try { test.throw_overflow_error(); throw new Exception("throw_overflow_error failed"); } catch (OverflowException) {}
try { test.throw_range_error(); throw new Exception("throw_range_error failed"); } catch (IndexOutOfRangeException) {}
try { test.throw_runtime_error(); throw new Exception("throw_runtime_error failed"); } catch (ApplicationException) {}
try { test.throw_underflow_error(); throw new Exception("throw_underflow_error failed"); } catch (OverflowException) {}
}
}
using System;
using li_std_listNamespace;
public class li_std_list_runme {
private static readonly int collectionSize = 20;
public static void Main() {
// Setup a list of int
IntList list = new IntList();
IntList.IntListNode node;
for (int i = 0; i < 20; i++) {
int nb = i * 10;
list.Add(nb);
}
// Count property test
if (list.Count != collectionSize)
throw new Exception("Count test failed");
// IsReadOnly property test
if (list.IsReadOnly)
throw new Exception("IsReadOnly test failed");
// Contains method test
if (!list.Contains(0))
throw new Exception("Contains method test 1 failed");
if (!list.Contains(2 * 10))
throw new Exception("Contains method test 2 failed");
if (!list.Contains(19 * 10))
throw new Exception("Contains method test 3 failed");
if (list.Contains(20 * 10))
throw new Exception("Contains method test 4 failed");
// Nodes comparison method overload
{
IntList.IntListNode temp = new IntList.IntListNode(3);
if (list.First == temp)
throw new Exception("== overload method test (1) failed");
temp = new IntList.IntListNode(0);
if (list.First == temp)
throw new Exception("== overload method test (2) failed");
IntList.IntListNode temp2 = new IntList.IntListNode(0);
if (temp == temp2)
throw new Exception("== overload method test (3) failed");
if (!(list.First == list.First))
throw new Exception("== overload method test (4) failed");
if (list.First != list.First)
throw new Exception("!= overload method test (1) failed");
if (!(temp != temp2))
throw new Exception("!= overload method test (2) failed");
if (list.First.Equals(temp))
throw new Exception("Equals method test failed");
if (list.First.GetHashCode() == temp.GetHashCode())
throw new Exception("GetHashCode method test (1) failed");
if (list.First.GetHashCode() == list.First.GetHashCode())
throw new Exception("GetHashCode method test (2) failed");
}
// Getter test
{
if (list.First == null)
throw new Exception("First getter test (1) failed");
if (list.Last == null)
throw new Exception("Last getter test (1) failed");
if (list.Last.Next != null)
throw new Exception("Next getter test (1) failed");
if (list.First.Next == null)
throw new Exception("Next getter test (2) failed");
if (list.First.Previous != null)
throw new Exception("Previous getter test (1) failed");
if (list.Last.Previous == null)
throw new Exception("Previous getter test (2) failed");
}
// AddFirst method test
node = list.AddFirst(34);
if (list.First.Value != 34 || node.Value != 34 || node != list.First)
throw new Exception("AddFirst method test failed");
try {
list.AddFirst(null);
} catch (ArgumentNullException) {
try {
list.AddFirst(list.First);
} catch (InvalidOperationException) {
}
}
// RemoveFirst method test
int tmp = list.First.Value;
list.RemoveFirst();
if (list.First.Value == tmp || list.First.Value != 0 * 10)
throw new Exception("RemoveFirst method test failed");
// AddLast method test
node = list.AddLast(8);
if (list.Last.Value != 8 || node.Value != 8 || node != list.Last)
throw new Exception("AddLast method test failed");
try {
list.AddLast(null);
} catch (ArgumentNullException) {
try {
list.AddLast(list.First);
} catch (InvalidOperationException) {
}
}
// RemoveLast method test
int tmp2 = list.Last.Value;
list.RemoveLast();
if (list.Last.Value == tmp2 || list.Last.Value != (list.Count - 1) * 10)
throw new Exception("RemoveLast method test failed");
// AddBefore method test
node = list.AddBefore(list.Last, 17);
if (list.Last.Previous.Value != 17 || node.Value != 17 || node != list.Last.Previous)
throw new Exception("AddBefore method test (1) failed");
try {
node = null;
list.AddBefore(list.Last, node);
throw new Exception("AddBefore method test (2) failed");
} catch (ArgumentNullException) {
try {
node = new IntList.IntListNode(1);
list.AddBefore(null, node);
throw new Exception("AddBefore method test (3) failed");
} catch (ArgumentNullException) {
try {
list.AddBefore(list.Last, list.First);
} catch (InvalidOperationException) {
}
}
}
// AddAfter method test
node = list.AddAfter(list.First, 47);
if (list.First.Next.Value != 47 || node.Value != 47 || node != list.First.Next)
throw new Exception("AddAfter method test (1) failed");
try {
node = null;
list.AddAfter(list.First.Next, node);
throw new Exception("AddAfter method test (2) failed");
} catch (ArgumentNullException) {
try {
list.AddAfter(list.First, list.Last);
} catch (InvalidOperationException) {
}
}
// Find method test
node = list.Find(0);
if (node == null || node.Value != 0)
throw new Exception("Find method test (1) failed");
node = list.Find(47);
if (node == null || node.Value != 47)
throw new Exception("Find method test (2) failed");
node = list.Find(190);
if (node == null || node.Value != 190)
throw new Exception("Find method test (3) failed");
node = list.Find(-3);
if (node != null)
throw new Exception("Find method test (4) failed");
// Remove method test
if (!list.Remove(17) || list.Contains(17) || list.Last.Previous.Value == 17)
throw new Exception("Remove method test (1) failed");
if (!list.Remove(47) || list.Contains(47) || list.First.Next.Value == 47)
throw new Exception("Remove method test (2) failed");
if (!list.Remove(0) || list.Contains(0) || list.First.Value == 0)
throw new Exception("Remove method test (3) failed");
if (!list.Remove(190) || list.Contains(190) || list.Last.Value == 190)
throw new Exception("Remove method test (4) failed");
try {
node = null;
list.Remove(node);
throw new Exception("Remove method test (5) failed");
} catch (ArgumentNullException) {
try {
node = new IntList.IntListNode(4);
list.Remove(node);
throw new Exception("Remove method test (5) failed");
} catch (InvalidOperationException) {
}
}
// ICollection constructor test
{
int[] intArray = new int[] { 0, 11, 22, 33, 44, 55, 33 };
IntList il = new IntList(intArray);
if (intArray.Length != il.Count)
throw new Exception("ICollection constructor length check failed: " + intArray.Length + "-" + il.Count);
node = il.First;
for (int i = 0; i < intArray.Length; i++) {
if (intArray[i] != node.Value)
throw new Exception("ICollection constructor failed, index:" + i);
node = node.Next;
}
try {
new IntList((System.Collections.ICollection)null);
throw new Exception("ICollection constructor null test failed");
} catch (ArgumentNullException) {
}
}
// Enumerator test
{
node = list.First;
System.Collections.IEnumerator myEnumerator = list.GetEnumerator();
while (myEnumerator.MoveNext()) {
if ((int)myEnumerator.Current != node.Value)
throw new Exception("Enumerator (1) test failed");
node = node.Next;
}
}
{
node = list.First;
System.Collections.Generic.IEnumerator<int> myEnumerator = list.GetEnumerator();
while (myEnumerator.MoveNext()) {
if (myEnumerator.Current != node.Value)
throw new Exception("Enumerator (2) test failed");
node = node.Next;
}
}
{
node = list.First;
IntList.IntListEnumerator myEnumerator = list.GetEnumerator();
while (myEnumerator.MoveNext()) {
if (myEnumerator.Current != node.Value)
throw new Exception("Enumerator (3) test failed");
node = node.Next;
}
}
{
node = list.First;
foreach (var elem in list) {
if (elem != node.Value)
throw new Exception("Enumerator (4) test failed");
node = node.Next;
}
}
// CopyTo method test
{
int[] outputarray = new int[collectionSize - 2];
list.CopyTo(outputarray, 0);
int index = 0;
IntList.IntListNode temp = list.First;
foreach (int val in outputarray) {
if (temp.Value != val) {
throw new Exception("CopyTo method test (1) failed, index:" + index);
}
index++;
temp = temp.Next;
}
}
{
DoubleList inputlist = new DoubleList();
int arrayLen = 10;
for (int i = 0; i < arrayLen; i++) {
double num = i * 10.1;
inputlist.Add(num);
}
double[] outputarray = new double[arrayLen];
inputlist.CopyTo(outputarray, 0);
DoubleList.DoubleListNode temp = inputlist.First;
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i] != temp.Value)
throw new Exception("CopyTo method test (2) failed, index:" + i);
temp = temp.Next;
}
}
{
StructList inputlist = new StructList();
int arrayLen = 10;
for (int i = 0; i < arrayLen; i++)
inputlist.Add(new Struct(i / 10.0));
Struct[] outputarray = new Struct[arrayLen];
inputlist.CopyTo(outputarray, 0);
StructList.StructListNode temp = inputlist.First;
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i].num != temp.Value.num)
throw new Exception("CopyTo method test (3) failed, index:" + i);
temp = temp.Next;
}
foreach (Struct s in inputlist) {
s.num += 20.0;
}
temp = inputlist.First;
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i].num != temp.Value.num)
throw new Exception("CopyTo method test (4) failed, index:" + i);
temp = temp.Next;
}
}
try {
list.CopyTo(null, 0);
throw new Exception("CopyTo method test (5) failed");
} catch (ArgumentNullException) {
}
// Clear() test
list.Clear();
if (list.Count != 0)
throw new Exception("Clear method failed");
// Finally test the methods being wrapped
{
IntList il = new IntList();
for (int i = 0; i < 4; i++) {
il.Add(i);
}
double x = li_std_list.average(il);
x += li_std_list.average(new IntList(new int[] { 1, 2, 3, 4 }));
DoubleList dlist = new DoubleList();
for (int i = 0; i < 10; i++) {
dlist.Add(i / 2.0);
}
li_std_list.halve_in_place(dlist);
}
// Dispose()
{
using (StructList ls = new StructList(new Struct[] { new Struct(0.0), new Struct(11.1) }))
using (DoubleList ld = new DoubleList(new double[] { 0.0, 11.1 })) { }
}
// More wrapped methods
{
FloatList l0 = li_std_list.listreal(new FloatList());
float flo = 123.456f;
l0.Add(flo);
flo = l0.First.Value;
IntList l1 = li_std_list.listint(new IntList());
IntPtrList l2 = li_std_list.listintptr(new IntPtrList());
IntConstPtrList l3 = li_std_list.listintconstptr(new IntConstPtrList());
l1.Add(123);
l2.Clear();
l3.Clear();
StructList l4 = li_std_list.liststruct(new StructList());
StructPtrList l5 = li_std_list.liststructptr(new StructPtrList());
StructConstPtrList l6 = li_std_list.liststructconstptr(new StructConstPtrList());
l4.Add(new Struct(123));
l5.Add(new Struct(123));
l6.Add(new Struct(123));
}
// Test lists of pointers
{
StructPtrList inputlist = new StructPtrList();
int arrayLen = 10;
for (int i = 0; i < arrayLen; i++) {
inputlist.Add(new Struct(i / 10.0));
}
Struct[] outputarray = new Struct[arrayLen];
inputlist.CopyTo(outputarray, 0);
StructPtrList.StructPtrListNode temp = inputlist.First;
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i].num != temp.Value.num)
throw new Exception("StructPtrList test (1) failed, i:" + i);
temp = temp.Next;
}
foreach (Struct s in inputlist) {
s.num += 20.0;
}
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i].num != 20.0 + i / 10.0)
throw new Exception("StructPtrList test (2) failed (a deep copy was incorrectly made), i:" + i);
}
}
// Test lists of const pointers
{
StructConstPtrList inputlist = new StructConstPtrList();
int arrayLen = 10;
for (int i = 0; i < arrayLen; i++) {
inputlist.Add(new Struct(i / 10.0));
}
Struct[] outputarray = new Struct[arrayLen];
inputlist.CopyTo(outputarray, 0);
StructConstPtrList.StructConstPtrListNode temp = inputlist.First;
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i].num != temp.Value.num)
throw new Exception("StructConstPtrList test (1) failed, i:" + i);
temp = temp.Next;
}
foreach (Struct s in inputlist) {
s.num += 20.0;
}
for (int i = 0; i < arrayLen; i++) {
if (outputarray[i].num != 20.0 + i / 10.0)
throw new Exception("StructConstPtrList test (2) failed (a deep copy was incorrectly made), i:" + i);
}
}
}
}
/* -----------------------------------------------------------------------------
* li_std_map_runme.cs
*
* SWIG C# tester for std_map.i
* This class tests all the functionality of the std_map.i wrapper.
* Upon successful testing, the main function doesn't print out anything.
* If any error is found - it will be printed on the screen.
* ----------------------------------------------------------------------------- */
using System;
using System.Collections.Generic;
using li_std_mapNamespace;
public class li_std_map_runme {
private static readonly int collectionSize = 20;
private static readonly int midCollection = collectionSize / 2;
public static void Main()
{
// Set up an string to int map
StringIntMap simap = new StringIntMap();
for (int i = 0; i < collectionSize; i++)
{
int val = i * 18;
simap.Add(i.ToString(), val);
}
// Count property test
if (simap.Count != collectionSize)
throw new Exception("Count test failed");
// IsReadOnly property test
if (simap.IsReadOnly)
throw new Exception("IsReadOnly test failed");
// Item indexing test
simap["0"] = 200;
if (simap["0"] != 200)
throw new Exception("Item property test failed");
simap["0"] = 0 * 18;
// ContainsKey() test
for (int i = 0; i < collectionSize; i++)
{
if (!simap.ContainsKey(i.ToString()))
throw new Exception("ContainsKey test " + i + " failed");
}
// ContainsKey() test
for (int i = 0; i < collectionSize; i++)
{
if (!simap.Contains(new KeyValuePair<string, int>(i.ToString(), i * 18)))
throw new Exception("Contains test " + i + " failed");
}
// TryGetValue() test
int value;
bool rc = simap.TryGetValue("3", out value);
if (rc != true || value != (3 * 18))
throw new Exception("TryGetValue test 1 failed");
rc = simap.TryGetValue("-1", out value);
if (rc != false)
throw new Exception("TryGetValue test 2 failed");
// Keys and Values test
{
IList<string> keys = new List<string>(simap.Keys);
IList<int> values = new List<int>(simap.Values);
Dictionary<string, int> check = new Dictionary<string, int>();
if (keys.Count != collectionSize)
throw new Exception("Keys count test failed");
if (values.Count != collectionSize)
throw new Exception("Values count test failed");
for (int i = 0; i < keys.Count; i++)
{
if (simap[keys[i]] != values[i])
throw new Exception("Keys and values test failed for index " + i);
check.Add(keys[i], values[i]);
}
for (int i = 0; i < collectionSize; i++)
{
if (!check.ContainsKey(i.ToString()))
throw new Exception("Keys and Values ContainsKey test " + i + " failed");
}
}
// Add and Remove test
for (int i = 100; i < 103; i++)
{
simap.Add(i.ToString(), i * 18);
if (!simap.ContainsKey(i.ToString()) || simap[i.ToString()] != (i * 18))
throw new Exception("Add test failed for index " + i);
simap.Remove(i.ToString());
if (simap.ContainsKey(i.ToString()))
throw new Exception("Remove test failed for index " + i);
}
for (int i = 200; i < 203; i++)
{
simap.Add(new KeyValuePair<string, int>(i.ToString(), i * 18));
if (!simap.ContainsKey(i.ToString()) || simap[i.ToString()] != (i * 18))
throw new Exception("Add explicit test failed for index " + i);
simap.Remove(new KeyValuePair<string, int>(i.ToString(), i * 18));
if (simap.ContainsKey(i.ToString()))
throw new Exception("Remove explicit test failed for index " + i);
}
// Duplicate key test
try
{
simap.Add("3", 0);
throw new Exception("Adding duplicate key test failed");
}
catch (ArgumentException)
{
}
// CopyTo() test
{
KeyValuePair<string, int>[] outputarray = new KeyValuePair<string, int>[collectionSize];
simap.CopyTo(outputarray);
foreach (KeyValuePair<string, int> val in outputarray)
{
if (simap[val.Key] != val.Value)
throw new Exception("CopyTo (1) test failed, index:" + val.Key);
}
}
{
KeyValuePair<string, int>[] outputarray = new KeyValuePair<string, int>[midCollection + collectionSize];
simap.CopyTo(outputarray, midCollection);
for (int i = midCollection; i < midCollection + collectionSize; i++)
{
KeyValuePair<string, int> val = outputarray[i];
if (simap[val.Key] != val.Value)
throw new Exception("CopyTo (2) test failed, index:" + val.Key);
}
}
{
KeyValuePair<string, int>[] outputarray = new KeyValuePair<string, int>[collectionSize - 1];
try
{
simap.CopyTo(outputarray);
throw new Exception("CopyTo (4) test failed");
}
catch (ArgumentException)
{
}
}
// Clear test
simap.Clear();
if (simap.Count != 0)
throw new Exception("Clear test failed");
// Test wrapped methods
for (int i = 1; i <= 5; i++)
{
simap[i.ToString()] = i;
}
double avg = li_std_map.valueAverage(simap);
if (avg != 3.0)
throw new Exception("Wrapped method valueAverage test failed. Got " + avg);
string keyStringified = li_std_map.stringifyKeys(simap);
if (keyStringified != " 1 2 3 4 5")
throw new Exception("Wrapped method stringifyKeys test failed. Got " + keyStringified);
// Test a map with a new complex type (Struct)
{
IntStructMap ismap = new IntStructMap();
for (int i = 0; i < 10; i++)
{
ismap.Add(i, new Struct(i * 10.1));
}
if (ismap.Count != 10)
throw new Exception("Count test on complex type map failed");
foreach (KeyValuePair<int, Struct> p in ismap)
{
if ((p.Key * 10.1) != p.Value.num)
throw new Exception("Iteration test on complex type map failed for index " + p.Key);
}
}
// Test a map of pointers
{
IntStructPtrMap ispmap = new IntStructPtrMap();
for (int i = 0; i < 10; i++)
{
ispmap.Add(i, new Struct(i * 10.1));
}
if (ispmap.Count != 10)
throw new Exception("Count test on complex type pointer map failed");
foreach (KeyValuePair<int, Struct> p in ispmap)
{
if ((p.Key * 10.1) != p.Value.num)
throw new Exception("Iteration test on complex type pointer map failed for index " + p.Key);
}
}
{
IntStructConstPtrMap iscpmap = new IntStructConstPtrMap();
for (int i = 0; i < 10; i++)
{
iscpmap.Add(i, new Struct(i * 10.1));
}
if (iscpmap.Count != 10)
throw new Exception("Count test on complex type const pointer map failed");
foreach (KeyValuePair<int, Struct> p in iscpmap)
{
if ((p.Key * 10.1) != p.Value.num)
throw new Exception("Iteration test on complex type const pointer map failed for index " + p.Key);
}
}
// Test complex type as key (Struct)
{
StructIntMap limap = new StructIntMap();
Struct s7 = new Struct(7);
Struct s8 = new Struct(8);
limap[s7] = 8;
if (limap[s7] != 8)
throw new Exception("Assignment test on complex key map failed");
if (!limap.ContainsKey(s7))
throw new Exception("Key test (1) on complex key map failed");
if (limap.ContainsKey(s8))
throw new Exception("Key test (2) on complex key map failed");
}
// Custom compare function
{
StringLengthNumberMap slmap = new StringLengthNumberMap();
li_std_map.populate(slmap);
string keys = string.Join(" ", new List<string>(slmap.Keys));
if (keys != "a aa zzz xxxx aaaaa")
throw new Exception("Keys are wrong or in wrong order: " + keys);
string values = string.Join(" ", new List<int>(slmap.Values));
if (values != "1 2 3 4 5")
throw new Exception("Values are wrong or in wrong order: " + values);
}
// All done
}
}
using System;
using System.Collections.Generic;
using li_std_setNamespace;
public class runme
{
static void checkThat(bool mustBeTrue, string message)
{
if (!mustBeTrue)
throw new Exception("Test that the set " + message + " failed");
}
static void Main()
{
StringSet ss = new StringSet();
// Check the interface methods first.
ISet<string> s = ss;
checkThat(s.Count == 0, "is initially empty");
checkThat(!s.Contains("key"), "doesn't contain inexistent element");
checkThat(!s.Remove("key"), "returns false when removing inexistent element");
checkThat(s.Add("key"), "returns true when adding a new element");
checkThat(!s.Add("key"), "returns false when adding an existing element");
checkThat(s.Contains("key"), "contains the just added element");
checkThat(s.Remove("key"), "returns true when removing an existing element");
checkThat(s.Count == 0, "is empty again");
checkThat(s.Add("key1"), "Add(key1) returns true");
checkThat(s.Add("key2"), "Add(key2) returns true");
checkThat(s.Add("key3"), "Add(key3) returns true");
// Also check a different interface, providing a different Add() (sic!).
ICollection<string> coll = ss;
coll.Add("key");
checkThat(ss.Count == 4, "contains 4 elements");
// Now use object-specific methods, mimicking HashSet<>.
string val;
checkThat(ss.TryGetValue("key1", out val), "could retrieve existing item");
checkThat(val.Equals("key1"), "value was returned correctly by TryGetValue()");
checkThat(!ss.TryGetValue("no-such-key", out val), "couldn't retrieve inexistent item");
checkThat(val == null, "value was reset after failed TryGetValue()");
IList<string> list = new List<string>();
foreach (string str in ss) {
list.Add(str);
}
checkThat(list.Count == 4, "copy contains 4 elements");
ss.Clear();
checkThat(ss.Count == 0, "is empty after Clear()");
// Check set-theoretic methods.
checkThat(new StringSet().SetEquals(new StringSet()), "SetEquals() works for empty sets");
checkThat(new StringSet{"foo"}.SetEquals(new StringSet{"foo"}), "SetEquals() works for non-empty sets");
checkThat(!new StringSet{"foo"}.SetEquals(new[] {"bar"}), "SetEquals() doesn't always return true");
ss = new StringSet{"foo", "bar", "baz"};
ss.ExceptWith(new[] {"baz", "quux"});
checkThat(ss.SetEquals(new[] {"foo", "bar"}), "ExceptWith works");
ss = new StringSet{"foo", "bar", "baz"};
ss.IntersectWith(new[] {"baz", "quux"});
checkThat(ss.SetEquals(new[] {"baz"}), "IntersectWith works");
checkThat(ss.IsProperSubsetOf(new[] {"bar", "baz"}), "IsProperSubsetOf works");
checkThat(!ss.IsProperSubsetOf(new[] {"baz"}), "!IsProperSubsetOf works");
checkThat(ss.IsSubsetOf(new[] {"bar", "baz"}), "IsSubsetOf works");
checkThat(!ss.IsSubsetOf(new[] {"bar"}), "!IsSubsetOf works");
ss = new StringSet{"foo", "bar", "baz"};
checkThat(ss.IsProperSupersetOf(new[] {"bar"}), "IsProperSupersetOf works");
checkThat(!ss.IsProperSupersetOf(new[] {"quux"}), "IsProperSupersetOf works");
checkThat(ss.IsSupersetOf(new[] {"foo", "bar", "baz"}), "IsProperSupersetOf works");
checkThat(!ss.IsSupersetOf(new[] {"foo", "bar", "baz", "quux"}), "IsProperSupersetOf works");
checkThat(ss.Overlaps(new[] {"foo"}), "Overlaps works");
checkThat(!ss.Overlaps(new[] {"moo"}), "!Overlaps works");
ss.SymmetricExceptWith(new[] {"baz", "quux"});
checkThat(ss.SetEquals(new[] {"foo", "bar", "quux"}), "SymmetricExceptWith works");
ss = new StringSet{"foo", "bar", "baz"};
ss.UnionWith(new[] {"baz", "quux"});
checkThat(ss.SetEquals(new[] {"foo", "bar", "baz", "quux"}), "UnionWith works");
// Check a set of another type.
FooSet fooSet = new FooSet();
ISet<Foo> fooISet = fooSet;
checkThat(fooISet.Count == 0, "is initially empty");
checkThat(fooISet.Add(new Foo(17)), "added successfully");
checkThat(fooISet.Count == 1, "is not empty any more");
// And a set of primitive type.
IntSet intSet = new IntSet();
checkThat(intSet.Count == 0, "is initially empty");
checkThat(intSet.Add(17), "17 added successfully");
checkThat(!intSet.Add(17), "17 not added again");
checkThat(intSet.Count == 1, "not empty any more");
checkThat(intSet.Add(289), "289 added successfully");
checkThat(intSet.Count == 2, "even less empty now");
}
}
using System;
using li_std_stringNamespace;
public class runme
{
static void Main()
{
// Checking expected use of %typemap(in) std::string {}
li_std_string.test_value("Fee");
// Checking expected result of %typemap(out) std::string {}
if (li_std_string.test_value("Fi") != "Fi")
throw new Exception("Test 1 failed");
// Verify type-checking for %typemap(in) std::string {}
try {
li_std_string.test_value(null);
throw new Exception("Test 2 failed");
} catch (ArgumentNullException) {
}
// Checking expected use of %typemap(in) const std::string & {}
li_std_string.test_const_reference("Fo");
// Checking expected result of %typemap(out) const std::string& {}
if (li_std_string.test_const_reference("Fum") != "Fum")
throw new Exception("Test 3 failed");
// Verify type-checking for %typemap(in) const std::string & {}
try {
li_std_string.test_const_reference(null);
throw new Exception("Test 4 failed");
} catch (ArgumentNullException) {
}
//
// Input and output typemaps for pointers and non-const references to
// std::string are *not* supported; the following tests confirm
// that none of these cases are slipping through.
//
SWIGTYPE_p_std__string stringPtr = null;
stringPtr = li_std_string.test_pointer_out();
li_std_string.test_pointer(stringPtr);
stringPtr = li_std_string.test_const_pointer_out();
li_std_string.test_const_pointer(stringPtr);
stringPtr = li_std_string.test_reference_out();
li_std_string.test_reference(stringPtr);
// Check throw exception specification
try {
li_std_string.test_throw();
throw new Exception("Test 5 failed");
} catch (ApplicationException e) {
if (e.Message != "test_throw message")
throw new Exception("Test 5 string check: " + e.Message);
}
try {
li_std_string.test_const_reference_throw();
throw new Exception("Test 6 failed");
} catch (ApplicationException e) {
if (e.Message != "test_const_reference_throw message")
throw new Exception("Test 6 string check: " + e.Message);
}
// Global variables
const string s = "initial string";
if (li_std_string.GlobalString2 != "global string 2")
throw new Exception("GlobalString2 test 1");
li_std_string.GlobalString2 = s;
if (li_std_string.GlobalString2 != s)
throw new Exception("GlobalString2 test 2");
if (li_std_string.ConstGlobalString != "const global string")
throw new Exception("ConstGlobalString test");
// Member variables
Structure myStructure = new Structure();
if (myStructure.MemberString2 != "member string 2")
throw new Exception("MemberString2 test 1");
myStructure.MemberString2 = s;
if (myStructure.MemberString2 != s)
throw new Exception("MemberString2 test 2");
if (myStructure.ConstMemberString != "const member string")
throw new Exception("ConstMemberString test");
if (Structure.StaticMemberString2 != "static member string 2")
throw new Exception("StaticMemberString2 test 1");
Structure.StaticMemberString2 = s;
if (Structure.StaticMemberString2 != s)
throw new Exception("StaticMemberString2 test 2");
if (Structure.ConstStaticMemberString != "const static member string")
throw new Exception("ConstStaticMemberString test");
}
}
// This test tests all the methods in the C# collection wrapper
using System;
using li_std_vector_enumNamespace;
public class li_std_vector_enum_runme {
public static void Main() {
EnumVector ev = new EnumVector();
check((int)ev.nums[0], 10);
check((int)ev.nums[1], 20);
check((int)ev.nums[2], 30);
int expected = 10;
foreach (EnumVector.numbers val in ev.nums) {
check((int)val, expected);
expected += 10;
}
}
private static void check(int a, int b) {
if (a != b)
throw new ApplicationException("values don't match");
}
}
// This test tests all the methods in the C# collection wrapper
using System;
using li_std_vectorNamespace;
public class li_std_vector_runme {
private static readonly int collectionSize = 20;
private static readonly int midCollection = collectionSize/2;
public static DoubleVector myDoubleVector;
public static RealVector myRealVector;
public static void Main() {
// Setup collection
DoubleVector vect = new DoubleVector();
for (int i=0; i<collectionSize; i++) {
double num = i*10.1;
vect.Add(num);
}
// Count property test
if (vect.Count != collectionSize)
throw new Exception("Count test failed");
// IsFixedSize property test
if (vect.IsFixedSize)
throw new Exception("IsFixedSize test failed");
// IsReadOnly property test
if (vect.IsReadOnly)
throw new Exception("IsReadOnly test failed");
// Item indexing
vect[0] = 200.1;
if (vect[0] != 200.1)
throw new Exception("Item property test failed");
vect[0] = 0*10.1;
try {
vect[-1] = 777.1;
throw new Exception("Item out of range (1) test failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect[vect.Count] = 777.1;
throw new Exception("Item out of range (2) test failed");
} catch (ArgumentOutOfRangeException) {
}
// CopyTo() test
{
double[] outputarray = new double[collectionSize];
vect.CopyTo(outputarray);
int index = 0;
foreach(double val in outputarray) {
if (vect[index] != val)
throw new Exception("CopyTo (1) test failed, index:" + index);
index++;
}
}
{
double[] outputarray = new double[midCollection+collectionSize];
vect.CopyTo(outputarray, midCollection);
int index = midCollection;
foreach(double val in vect) {
if (outputarray[index] != val)
throw new Exception("CopyTo (2) test failed, index:" + index);
index++;
}
}
{
double[] outputarray = new double[3];
vect.CopyTo(10, outputarray, 1, 2);
if (outputarray[0] != 0.0 || outputarray[1] != vect[10] || outputarray[2] != vect[11])
throw new Exception("CopyTo (3) test failed");
}
{
double[] outputarray = new double[collectionSize-1];
try {
vect.CopyTo(outputarray);
throw new Exception("CopyTo (4) test failed");
} catch (ArgumentException) {
}
}
{
StructVector inputvector = new StructVector();
int arrayLen = 10;
for (int i=0; i<arrayLen; i++) {
inputvector.Add(new Struct(i/10.0));
}
Struct[] outputarray = new Struct[arrayLen];
inputvector.CopyTo(outputarray);
for(int i=0; i<arrayLen; i++) {
if (outputarray[i].num != inputvector[i].num)
throw new Exception("CopyTo (6) test failed, i:" + i);
}
foreach (Struct s in inputvector) {
s.num += 20.0;
}
for(int i=0; i<arrayLen; i++) {
if (outputarray[i].num + 20.0 != inputvector[i].num )
throw new Exception("CopyTo (7) test failed (only a shallow copy was made), i:" + i);
}
}
{
try {
vect.CopyTo(null);
throw new Exception("CopyTo (8) test failed");
} catch (ArgumentNullException) {
}
}
// Contains() test
if (!vect.Contains(0*10.1))
throw new Exception("Contains test 1 failed");
if (!vect.Contains(10*10.1))
throw new Exception("Contains test 2 failed");
if (!vect.Contains(19*10.1))
throw new Exception("Contains test 3 failed");
if (vect.Contains(20*10.1))
throw new Exception("Contains test 4 failed");
{
// IEnumerable constructor
double[] doubleArray = new double[] { 0.0, 11.1, 22.2, 33.3, 44.4, 55.5, 33.3 };
DoubleVector dv = new DoubleVector(doubleArray);
if (doubleArray.Length != dv.Count)
throw new Exception("ICollection constructor length check failed: " + doubleArray.Length + "-" + dv.Count);
for (int i=0; i<doubleArray.Length; i++) {
if (doubleArray[i] != dv[i])
throw new Exception("ICollection constructor failed, index:" + i);
}
{
Struct[] structArray = new Struct[] { new Struct(0.0), new Struct(11.1), new Struct(22.2), new Struct(33.3) };
StructVector sv = new StructVector(structArray);
for (int i=0; i<structArray.Length; i++) {
structArray[i].num += 200.0;
}
for (int i=0; i<structArray.Length; i++) {
if (structArray[i].num != sv[i].num + 200.0)
throw new Exception("ICollection constructor not a deep copy, index:" + i);
}
}
try {
new DoubleVector((System.Collections.ICollection)null);
throw new Exception("ICollection constructor null test failed");
} catch (ArgumentNullException) {
}
{
// Collection initializer test, requires C# 3.0
// myDoubleVector = new DoubleVector() { 123.4, 567.8, 901.2 };
}
// IndexOf() test
for (int i=0; i<collectionSize; i++) {
if (vect.IndexOf(i*10.1) != i)
throw new Exception("IndexOf test " + i + " failed");
}
if (vect.IndexOf(200.1) != -1)
throw new Exception("IndexOf non-existent test failed");
if (dv.IndexOf(33.3) != 3)
throw new Exception("IndexOf position test failed");
// LastIndexOf() test
for (int i=0; i<collectionSize; i++) {
if (vect.LastIndexOf(i*10.1) != i)
throw new Exception("LastIndexOf test " + i + " failed");
}
if (vect.LastIndexOf(200.1) != -1)
throw new Exception("LastIndexOf non-existent test failed");
if (dv.LastIndexOf(33.3) != 6)
throw new Exception("LastIndexOf position test failed");
// Copy constructor test
DoubleVector dvCopy = new DoubleVector(dv);
for (int i=0; i<doubleArray.Length; i++) {
if (doubleArray[i] != dvCopy[i])
throw new Exception("Copy constructor failed, index:" + i);
}
if (dvCopy.Count != doubleArray.Length)
throw new Exception("Copy constructor lengths mismatch");
// ToArray test
double[] dvArray = dv.ToArray();
for (int i=0; i<doubleArray.Length; i++) {
if (doubleArray[i] != dvArray[i])
throw new Exception("ToArray failed, index:" + i);
}
if (dvArray.Length != doubleArray.Length)
throw new Exception("ToArray lengths mismatch");
}
{
// Repeat() test
try {
myDoubleVector = DoubleVector.Repeat(77.7, -1);
throw new Exception("Repeat negative count test failed");
} catch (ArgumentOutOfRangeException) {
}
DoubleVector dv = DoubleVector.Repeat(77.7, 5);
if (dv.Count != 5)
throw new Exception("Repeat count test failed");
// Also tests enumerator
{
System.Collections.IEnumerator myEnumerator = dv.GetEnumerator();
while ( myEnumerator.MoveNext() ) {
if ((double)myEnumerator.Current != 77.7)
throw new Exception("Repeat (1) test failed");
}
}
{
System.Collections.Generic.IEnumerator<double> myEnumerator = dv.GetEnumerator();
while ( myEnumerator.MoveNext() ) {
if (myEnumerator.Current != 77.7)
throw new Exception("Repeat (2) test failed");
}
}
}
{
// InsertRange() test
DoubleVector dvect = new DoubleVector();
for (int i=0; i<5; i++) {
dvect.Add(1000.0*i);
}
vect.InsertRange(midCollection, dvect);
if (vect.Count != collectionSize+dvect.Count)
throw new Exception("InsertRange test size failed");
for (int i=0; i<midCollection; i++) {
if (vect.IndexOf(i*10.1) != i)
throw new Exception("InsertRange (1) test " + i + " failed");
}
for (int i=0; i<dvect.Count; i++) {
if (vect[i+midCollection] != dvect[i])
throw new Exception("InsertRange (2) test " + i + " failed");
}
for (int i=midCollection; i<collectionSize; i++) {
if (vect.IndexOf(i*10.1) != i+dvect.Count)
throw new Exception("InsertRange (3) test " + i + " failed");
}
try {
vect.InsertRange(0, null);
throw new Exception("InsertRange (4) test failed");
} catch (ArgumentNullException) {
}
// RemoveRange() test
vect.RemoveRange(0, 0);
vect.RemoveRange(midCollection, dvect.Count);
if (vect.Count != collectionSize)
throw new Exception("RemoveRange test size failed");
for (int i=0; i<collectionSize; i++) {
if (vect.IndexOf(i*10.1) != i)
throw new Exception("RemoveRange test " + i + " failed");
}
try {
vect.RemoveRange(-1, 0);
throw new Exception("RemoveRange index out of range (1) test failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect.RemoveRange(0, -1);
throw new Exception("RemoveRange count out of range (2) test failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect.RemoveRange(collectionSize+1, 0);
throw new Exception("RemoveRange index and count out of range (1) test failed");
} catch (ArgumentException) {
}
try {
vect.RemoveRange(0, collectionSize+1);
throw new Exception("RemoveRange index and count out of range (2) test failed");
} catch (ArgumentException) {
}
// AddRange() test
vect.AddRange(dvect);
if (vect.Count != collectionSize+dvect.Count)
throw new Exception("AddRange test size failed");
for (int i=0; i<collectionSize; i++) {
if (vect.IndexOf(i*10.1) != i)
throw new Exception("AddRange (1) test " + i + " failed");
}
for (int i=0; i<dvect.Count; i++) {
if (vect[i+collectionSize] != dvect[i])
throw new Exception("AddRange (2) test " + i + " failed");
}
try {
vect.AddRange(null);
throw new Exception("AddRange (3) test failed");
} catch (ArgumentNullException) {
}
vect.RemoveRange(collectionSize, dvect.Count);
// GetRange() test
int rangeSize = 5;
DoubleVector returnedVec = vect.GetRange(0, 0);
returnedVec = vect.GetRange(midCollection, rangeSize);
if (returnedVec.Count != rangeSize)
throw new Exception("GetRange test size failed");
for (int i=0; i<rangeSize; i++) {
if (returnedVec.IndexOf((i+midCollection)*10.1) != i)
throw new Exception("GetRange test " + i + " failed");
}
try {
vect.GetRange(-1, 0);
throw new Exception("GetRange index out of range (1) test failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect.GetRange(0, -1);
throw new Exception("GetRange count out of range (2) test failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect.GetRange(collectionSize+1, 0);
throw new Exception("GetRange index and count out of range (1) test failed");
} catch (ArgumentException) {
}
try {
vect.GetRange(0, collectionSize+1);
throw new Exception("GetRange index and count out of range (2) test failed");
} catch (ArgumentException) {
}
{
StructVector inputvector = new StructVector();
int arrayLen = 10;
for (int i=0; i<arrayLen; i++) {
inputvector.Add(new Struct(i/10.0));
}
StructVector outputvector = inputvector.GetRange(0,arrayLen);
for(int i=0; i<arrayLen; i++) {
if (outputvector[i].num != inputvector[i].num)
throw new Exception("GetRange (1) test failed, i:" + i);
}
foreach (Struct s in inputvector) {
s.num += 20.0;
}
for(int i=0; i<arrayLen; i++) {
if (outputvector[i].num + 20.0 != inputvector[i].num )
throw new Exception("GetRange (2) test failed (only a shallow copy was made), i:" + i);
}
}
}
// Insert() test
int pos = 0;
int count = vect.Count;
vect.Insert(pos, -5.1);
count++;
if (vect.Count != count || vect[pos] != -5.1)
throw new Exception("Insert at beginning test failed");
pos = midCollection;
vect.Insert(pos, 85.1);
count++;
if (vect.Count != count || vect[pos] != 85.1)
throw new Exception("Insert at " + pos + " test failed");
pos = vect.Count;
vect.Insert(pos, 195.1);
count++;
if (vect.Count != count || vect[pos] != 195.1)
throw new Exception("Insert at end test failed");
pos = vect.Count+1;
try {
vect.Insert(pos, 222.1); // should throw
throw new Exception("Insert after end (1) test failed");
} catch (ArgumentOutOfRangeException) {
}
if (vect.Count != count)
throw new Exception("Insert after end (2) test failed");
pos = -1;
try {
vect.Insert(pos, 333.1); // should throw
throw new Exception("Insert before start (1) test failed");
} catch (ArgumentOutOfRangeException) {
}
if (vect.Count != count)
throw new Exception("Insert before start (2) test failed");
// Remove() test
vect.Remove(195.1);
count--;
vect.Remove(-5.1);
count--;
vect.Remove(85.1);
count--;
vect.Remove(9999.1); // element does not exist, should quietly do nothing
if (vect.Count != count)
throw new Exception("Remove count check test failed");
for (int i=0; i<collectionSize; i++) {
if (vect[i] != i*10.1)
throw new Exception("Remove test failed, index:" + i);
}
// RemoveAt() test
vect.Insert(0, -4.1);
vect.Insert(midCollection, 84.1);
vect.Insert(vect.Count, 194.1);
vect.RemoveAt(vect.Count-1);
vect.RemoveAt(midCollection);
vect.RemoveAt(0);
try {
vect.RemoveAt(-1);
throw new Exception("RemoveAt test (1) failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect.RemoveAt(vect.Count);
throw new Exception("RemoveAt test (2) failed");
} catch (ArgumentOutOfRangeException) {
}
for (int i=0; i<collectionSize; i++) {
if (vect[i] != i*10.1)
throw new Exception("RemoveAt test (3) failed, index:" + i);
}
{
// Capacity test
try {
myDoubleVector = new DoubleVector(-1);
throw new Exception("constructor setting capacity (1) test failed");
} catch (ArgumentOutOfRangeException) {
}
DoubleVector dv = new DoubleVector(10);
if (dv.Capacity != 10 || dv.Count != 0)
throw new Exception("constructor setting capacity (2) test failed");
dv.Capacity = 20;
if (dv.Capacity != 20)
throw new Exception("capacity test (1) failed");
dv.Add(1.11);
try {
dv.Capacity = dv.Count-1;
throw new Exception("capacity test (2) failed");
} catch (ArgumentOutOfRangeException) {
}
// SetRange() test
for (int i=dv.Count; i<collectionSize; i++) {
dv.Add(0.0);
}
dv.SetRange(0, vect);
if (dv.Count != collectionSize)
throw new Exception("SetRange count check test failed");
for (int i=0; i<collectionSize; i++) {
if (vect[i] != dv[i])
throw new Exception("SetRange test (1) failed, index:" + i);
}
try {
dv.SetRange(-1, vect);
throw new Exception("SetRange test (2) failed");
} catch (ArgumentOutOfRangeException) {
}
try {
dv.SetRange(1, vect);
throw new Exception("SetRange test (3) failed");
} catch (ArgumentOutOfRangeException) {
}
try {
vect.SetRange(0, null);
throw new Exception("SetRange (4) test failed");
} catch (ArgumentNullException) {
}
// Reverse() test
dv.Reverse();
for (int i=0; i<collectionSize; i++) {
if (vect[i] != dv[collectionSize-i-1])
throw new Exception("Reverse test (1) failed, index:" + i);
}
dv.Reverse(0, collectionSize);
for (int i=0; i<collectionSize; i++) {
if (vect[i] != dv[i])
throw new Exception("Reverse test (2) failed, index:" + i);
}
dv.Reverse(0, 0); // should do nothing!
for (int i=0; i<collectionSize; i++) {
if (vect[i] != dv[i])
throw new Exception("Reverse test (3) failed, index:" + i);
}
try {
dv.Reverse(-1, 0);
throw new Exception("Reverse test (4) failed");
} catch (ArgumentOutOfRangeException) {
}
try {
dv.Reverse(0, -1);
throw new Exception("Reverse test (5) failed");
} catch (ArgumentOutOfRangeException) {
}
try {
dv.Reverse(collectionSize+1, 0);
throw new Exception("Reverse test (6) failed");
} catch (ArgumentException) {
}
try {
dv.Reverse(0, collectionSize+1);
throw new Exception("Reverse test (7) failed");
} catch (ArgumentException) {
}
}
// foreach test
{
int index=0;
foreach (double s in vect) {
if (s != index*10.1)
throw new Exception("foreach test failed, index:" + index);
index++;
}
}
// Clear() test
vect.Clear();
if (vect.Count != 0)
throw new Exception("Clear failed");
// Finally test the methods being wrapped
{
IntVector iv = new IntVector();
for (int i=0; i<4; i++) {
iv.Add(i);
}
double x = li_std_vector.average(iv);
x += li_std_vector.average( new IntVector( new int[] {1, 2, 3, 4} ) );
myRealVector = li_std_vector.half( new RealVector( new float[] {10F, 10.5F, 11F, 11.5F} ) );
DoubleVector dvec = new DoubleVector();
for (int i=0; i<10; i++) {
dvec.Add(i/2.0);
}
li_std_vector.halve_in_place(dvec);
}
// Dispose()
{
using (StructVector vs = new StructVector( new Struct[] { new Struct(0.0), new Struct(11.1) } ) )
using (DoubleVector vd = new DoubleVector( new double[] { 0.0, 11.1 } ) ) {
}
}
// More wrapped methods
{
RealVector v0 = li_std_vector.vecreal(new RealVector());
float flo = 123.456f;
v0.Add(flo);
flo = v0[0];
IntVector v1 = li_std_vector.vecintptr(new IntVector());
IntPtrVector v2 = li_std_vector.vecintptr(new IntPtrVector());
IntConstPtrVector v3 = li_std_vector.vecintconstptr(new IntConstPtrVector());
v1.Add(123);
v2.Clear();
v3.Clear();
StructVector v4 = li_std_vector.vecstruct(new StructVector());
StructPtrVector v5 = li_std_vector.vecstructptr(new StructPtrVector());
StructConstPtrVector v6 = li_std_vector.vecstructconstptr(new StructConstPtrVector());
v4.Add(new Struct(123));
v5.Add(new Struct(123));
v6.Add(new Struct(123));
}
// Test vectors of pointers
{
StructPtrVector inputvector = new StructPtrVector();
int arrayLen = 10;
for (int i=0; i<arrayLen; i++) {
inputvector.Add(new Struct(i/10.0));
}
Struct[] outputarray = new Struct[arrayLen];
inputvector.CopyTo(outputarray);
for(int i=0; i<arrayLen; i++) {
if (outputarray[i].num != inputvector[i].num)
throw new Exception("StructPtrVector test (1) failed, i:" + i);
}
foreach (Struct s in inputvector) {
s.num += 20.0;
}
for(int i=0; i<arrayLen; i++) {
if (outputarray[i].num != 20.0 + i/10.0)
throw new Exception("StructPtrVector test (2) failed (a deep copy was incorrectly made), i:" + i);
}
int rangeSize = 5;
int mid = arrayLen/2;
StructPtrVector returnedVec = inputvector.GetRange(mid, rangeSize);
for (int i=0; i<rangeSize; i++) {
if (inputvector[i+mid].num != returnedVec[i].num)
throw new Exception("StructPtrVector test (3) failed, i:" + i);
}
}
// Test vectors of const pointers
{
StructConstPtrVector inputvector = new StructConstPtrVector();
int arrayLen = 10;
for (int i=0; i<arrayLen; i++) {
inputvector.Add(new Struct(i/10.0));
}
Struct[] outputarray = new Struct[arrayLen];
inputvector.CopyTo(outputarray);
for(int i=0; i<arrayLen; i++) {
if (outputarray[i].num != inputvector[i].num)
throw new Exception("StructConstPtrVector test (1) failed, i:" + i);
}
foreach (Struct s in inputvector) {
s.num += 20.0;
}
for(int i=0; i<arrayLen; i++) {
if (outputarray[i].num != 20.0 + i/10.0)
throw new Exception("StructConstPtrVector test (2) failed (a deep copy was incorrectly made), i:" + i);
}
int rangeSize = 5;
int mid = arrayLen/2;
StructConstPtrVector returnedVec = inputvector.GetRange(mid, rangeSize);
for (int i=0; i<rangeSize; i++) {
if (inputvector[i+mid].num != returnedVec[i].num)
throw new Exception("StructConstPtrVector test (3) failed, i:" + i);
}
}
// Test construction
{
string[] one_two_three = new string[] { "one", "two", "three" };
// Test construction from array
{
string[] collection = one_two_three;
check123(new StringVector(collection));
}
// Test construction from IEnumerable
{
global::System.Collections.IEnumerable collection = one_two_three;
check123(new StringVector(collection));
}
// Test construction from IEnumerable<>
{
global::System.Collections.Generic.IEnumerable<string> collection = one_two_three;
check123(new StringVector(collection));
}
// Test construction from IList<>
{
global::System.Collections.Generic.IList<string> collection = one_two_three;
check123(new StringVector(collection));
}
// Test construction from ICollection
{
global::System.Collections.ICollection collection = one_two_three;
check123(new StringVector(collection));
}
// Test construction from ICollection<>
{
global::System.Collections.Generic.ICollection<string> collection = new global::System.Collections.Generic.List<string>(one_two_three);
check123(new StringVector(collection));
}
}
}
private static void check123(StringVector stringv) {
string concatenated = "";
foreach (string s in stringv)
concatenated = concatenated + s;
if (concatenated != "onetwothree")
throw new Exception("concatenated string failed: " + concatenated);
}
}
using System;
using li_std_wstringNamespace;
public class runme
{
static private void check_equal(char a, char b)
{
if (a != b)
throw new Exception("char failed '" + a + "' != '" + b + "'");
}
static private void check_equal(string a, string b)
{
if (a != b)
throw new Exception("string failed '" + a + "' != '" + b + "'");
}
static void Main()
{
char h = 'h';
check_equal(li_std_wstring.test_wcvalue(h), h);
string x = "abc";
check_equal(li_std_wstring.test_ccvalue(x), x);
check_equal(li_std_wstring.test_cvalue(x), x);
check_equal(li_std_wstring.test_wchar_overload(x), x);
check_equal(li_std_wstring.test_wchar_overload(), null);
li_std_wstring.test_pointer(null);
li_std_wstring.test_const_pointer(null);
try {
li_std_wstring.test_value(null);
throw new Exception("NULL check failed");
} catch (ArgumentNullException) {
}
try {
li_std_wstring.test_reference(null);
throw new Exception("NULL check failed");
} catch (ArgumentNullException e) {
if (!e.Message.Contains("type is null"))
throw new Exception("Missing text " + e);
}
try {
li_std_wstring.test_const_reference(null);
throw new Exception("NULL check failed");
} catch (ArgumentNullException e) {
if (!e.Message.Contains("null wstring"))
throw new Exception("Missing text " + e);
}
x = "hello";
check_equal(li_std_wstring.test_const_reference(x), x);
/* Postpone, tricky, std::wstring portability problem.
* std::wstring is 2 bytes on Windows, 4 bytes on Linux, LPWSTR is 2 bytes.
* .NET marshalling should work on Windows but not Linux.
string s = "abc";
if (!li_std_wstring.test_equal_abc(s))
throw new Exception("Not equal " + s);
*/
try {
li_std_wstring.test_throw();
} catch (Exception e) {
check_equal(e.Message, "throwing test_throw");
}
x = "abc\0def";
// Unlike other languages, embedded NULL in std::string not supported
// check_equal(li_std_wstring.test_value(x), x);
check_equal(li_std_wstring.test_value(x), "abc");
check_equal(li_std_wstring.test_ccvalue(x), "abc");
check_equal(li_std_wstring.test_wchar_overload(x), "abc");
{
// Unicode strings
string[] test_strings = {
"JP: 日本語", "DE: Kröpeliner Straße" , "RU: Война и мир", "EN: War and Peace"
};
foreach (string expected in test_strings)
{
string received = li_std_wstring.test_value(expected);
check_equal(received, expected);
}
foreach (string expected in test_strings)
{
string received = li_std_wstring.test_const_reference(expected);
check_equal(received, expected);
}
foreach (string expected in test_strings)
{
string received = li_std_wstring.test_ccvalue(expected);
check_equal(received, expected);
}
/* Not working for Japanese and Russian characters on Windows, okay on Linux
* Is fixed by adding CharSet=CharSet.Unicode to the DllImport, so change to:
* [global::System.Runtime.InteropServices.DllImport("li_std_wstring", CharSet=global::System.Runtime.InteropServices.CharSet.Unicode, EntryPoint="CSharp_li_std_wstringNamespace_test_wcvalue")]
* Needs a SWIG code change to support this
foreach (string test_string in test_strings)
{
foreach (char expected in test_string)
{
char received = li_std_wstring.test_wcvalue(expected);
check_equal(received, expected);
}
}
*/
}
}
}
using System;
using li_swigtype_inoutNamespace;
public class li_swigtype_inout_runme {
public static void Main() {
XXX xxx = new XXX(999);
check_count(1);
XXX x1 = null;
XXX x2 = null;
XXX x3 = null;
XXX x4 = null;
li_swigtype_inout.ptr_ref_out(out x1, out x2, out x3, out x4);
check_value(111, x1.value);
check_value(222, x2.value);
check_value(333, x3.value);
check_value(444, x4.value);
check_count(5);
x1.Dispose();
x2.Dispose();
x3.Dispose();
x4.Dispose();
xxx.Dispose();
check_count(0);
x1 = null;
x2 = null;
x3 = null;
x4 = null;
new ConstructorTest(out x1, out x2, out x3, out x4);
check_count(4);
check_value(111, x1.value);
check_value(222, x2.value);
check_value(333, x3.value);
check_value(444, x4.value);
x1.Dispose();
x2.Dispose();
x3.Dispose();
x4.Dispose();
check_count(0);
}
public static void check_count(int count) {
int actual = XXX.count;
if( count != actual ) {
throw new Exception(String.Format("Count wrong. Expected: {0} Got: {1}", count, actual));
}
}
public static void check_value(int expected, int actual) {
if( expected != actual ) {
throw new Exception(String.Format("Wrong value. Expected: {0} Got: {1}", expected, actual));
}
}
}
// Check a few of the INPUT, OUTPUT and INOUT typemaps.
using System;
using li_typemapsNamespace;
public class runme
{
static void Main()
{
// Check double INPUT typemaps
if (li_typemaps.in_double(22.22) != 22.22) exit_test("in_double");
if (li_typemaps.inr_double(22.22) != 22.22) exit_test("inr_double");
// Check double OUTPUT typemaps
{
double var = 44.44;
li_typemaps.out_double(22.22, out var);
if (var != 22.22) exit_test("out_double");
}
{
double var = 44.44;
li_typemaps.outr_double(22.22, out var);
if (var != 22.22) exit_test("outr_double");
}
// Check double INOUT typemaps
{
double var = 44.44;
li_typemaps.inout_double(ref var);
if (var != 44.44) exit_test("inout_double");
}
{
double var = 44.44;
li_typemaps.inoutr_double(ref var);
if (var != 44.44) exit_test("inoutr_double");
}
// Check unsigned long long INPUT typemaps
if (li_typemaps.in_ulonglong(20) != 20) exit_test("in_ulonglong");
if (li_typemaps.inr_ulonglong(20) != 20) exit_test("inr_ulonglong");
// Check unsigned long long OUTPUT typemaps
{
ulong var = 40;
li_typemaps.out_ulonglong(20, out var);
if (var != 20) exit_test("out_ulonglong");
}
{
ulong var = 40;
li_typemaps.outr_ulonglong(20, out var);
if (var != 20) exit_test("outr_ulonglong");
}
// Check unsigned long long INOUT typemaps
{
ulong var = 40;
li_typemaps.inout_ulonglong(ref var);
if (var != 40) exit_test("inout_ulonglong");
}
{
ulong var = 40;
li_typemaps.inoutr_ulonglong(ref var);
if (var != 40) exit_test("inoutr_ulonglong");
}
// Check unsigned bool INPUT typemaps
if (li_typemaps.in_bool(false) != false) exit_test("in_bool");
if (li_typemaps.inr_bool(false) != false) exit_test("inr_bool");
// Check unsigned bool OUTPUT typemaps
{
bool var = false;
li_typemaps.out_bool(true, out var);
if (var != true) exit_test("out_bool");
}
{
bool var = false;
li_typemaps.outr_bool(true, out var);
if (var != true) exit_test("outr_bool");
}
// Check unsigned bool INOUT typemaps
{
bool var = false;
li_typemaps.inout_bool(ref var);
if (var != false) exit_test("inout_bool");
}
{
bool var = false;
li_typemaps.inoutr_bool(ref var);
if (var != false) exit_test("inoutr_bool");
}
}
private static void exit_test(String funcName) {
throw new Exception("Test FAILED in function " + funcName);
}
}
// This is the long_long runtime testcase. It checks that the long long and
// unsigned long long types work.
using System;
using long_longNamespace;
public class long_long_runme {
public static void Main() {
check_ll(0L);
check_ll(0x7FFFFFFFFFFFFFFFL);
check_ll(-10);
check_ull(0);
check_ull(127);
check_ull(128);
check_ull(9223372036854775807); //0x7FFFFFFFFFFFFFFFL
check_ull(18446744073709551615); //0xFFFFFFFFFFFFFFFFL
}
public static void check_ll(long ll) {
long_long.ll = ll;
long ll_check = long_long.ll;
if (ll != ll_check) {
string ErrorMessage = "Runtime test using long long failed. ll=" + ll + " ll_check=" + ll_check;
throw new Exception(ErrorMessage);
}
}
public static void check_ull(ulong ull) {
long_long.ull = ull;
ulong ull_check = long_long.ull;
if (ull != ull_check) {
string ErrorMessage = "Runtime test using unsigned long long failed. ull=" + ull + " ull_check=" + ull_check;
throw new Exception(ErrorMessage);
}
}
}
using System;
using member_pointerNamespace;
public class runme {
public static SWIGTYPE_m_Shape__f_void__double memberPtr = null;
static void Main() {
// Get the pointers
SWIGTYPE_m_Shape__f_void__double area_pt = member_pointer.areapt();
SWIGTYPE_m_Shape__f_void__double perim_pt = member_pointer.perimeterpt();
// Create some objects
Square s = new Square(10);
// Do some calculations
check( "Square area ", 100.0, member_pointer.do_op(s,area_pt) );
check( "Square perim", 40.0, member_pointer.do_op(s,perim_pt) );
memberPtr = member_pointer.areavar;
memberPtr = member_pointer.perimetervar;
// Try the variables
check( "Square area ", 100.0, member_pointer.do_op(s,member_pointer.areavar) );
check( "Square perim", 40.0, member_pointer.do_op(s,member_pointer.perimetervar) );
// Modify one of the variables
member_pointer.areavar = perim_pt;
check( "Square perimeter", 40.0, member_pointer.do_op(s,member_pointer.areavar) );
// Try the constants
memberPtr = member_pointer.AREAPT;
memberPtr = member_pointer.PERIMPT;
memberPtr = member_pointer.NULLPT;
check( "Square area ", 100.0, member_pointer.do_op(s,member_pointer.AREAPT) );
check( "Square perim", 40.0, member_pointer.do_op(s,member_pointer.PERIMPT) );
}
private static void check(string what, double expected, double actual) {
if (expected != actual)
throw new ApplicationException("Failed: " + what + " Expected: " + expected + " Actual: " + actual);
}
}
using System;
using multiple_inheritance_abstractNamespace;
public class multiple_inheritance_abstract_runme {
//Test base class as a parameter in C#
int jcbase1b(CBase1 cb1){
return cb1.cbase1y();
}
int jabase1(ABase1 ab1){
return ab1.abase1();
}
int jcbase2(CBase2 cb2){
return cb2.cbase2();
}
public static void check(bool fail, string msg) {
if (fail)
throw new Exception(msg);
}
public static void Main() {
//Test Derived1
Derived1 d1=new Derived1();
check(d1.cbase1y()!=3, "Derived1::cbase1y() failed");
check(d1.cbase2()!=4, "Derived1::cbase2() failed");
//Test Derived2
Derived2 d2=new Derived2();
check(d2.cbase1y()!=6, "Derived2::cbase1y() failed");
check(d2.abase1()!=5, "Derived2::abase1() failed");
//Test Derived3
Derived3 d3=new Derived3();
check(d3.cbase1y()!=7, "Derived3::cbase1y() failed");
check(d3.cbase2()!=8, "Derived3::cbase2() failed");
check(d3.abase1()!=9, "Derived3::abase1() failed");
//Test Bottom1
Bottom1 b1=new Bottom1();
check(b1.cbase1y()!=103, "Bottom1::cbase1y() failed");
check(b1.cbase2()!=104, "Bottom1::cbase2() failed");
//Test Bottom2
Bottom2 b2=new Bottom2();
check(b2.cbase1y()!=206, "Bottom2::cbase1y() failed");
check(b2.abase1()!=205, "Bottom2::abase1() failed");
//Test Bottom3
Bottom3 b3=new Bottom3();
check(b3.cbase1y()!=307, "Bottom3::cbase1y() failed");
check(b3.cbase2()!=308, "Bottom3::cbase2() failed");
check(b3.abase1()!=309, "Bottom3::abase1() failed");
//Test interfaces from c++ classes
CBase1 cb1=new CBase1SwigImpl();
CBase2 cb2=new CBase2SwigImpl();
check(cb1.cbase1y()!=1, "CBase1::cbase1y() failed");
check(cb2.cbase2()!=2, "CBase2::cbase2() failed");
//Test abstract class as return value
ABase1 ab1=d3.cloneit();
check(ab1.abase1()!=9, "Derived3::abase1() through ABase1 failed");
//Test concrete base class as return value
CBase1 cb6=d2.cloneit();
CBase2 cb7=d1.cloneit();
check(cb6.cbase1y()!=6, "Derived2::cbase1y() through CBase1 failed");
check(cb7.cbase2()!=4, "Derived1:cbase2() through ABase1 failed");
//Test multi inheritance
CBase1 cb3=new Derived1();
CBase1 cb4=new Derived3();
CBase2 cb5=new Derived3();
ABase1 ab6=new Derived2();
check(cb3.cbase1y()!=3, "Derived1::cbase1y() through CBase1 failed");
check(cb4.cbase1y()!=7, "Derived3::cbase1y() through CBase1 failed");
check(cb5.cbase2()!=8, "Derived3::cbase2() through CBase2 failed");
check(ab6.abase1()!=5, "Derived2::abase1() through ABase1 failed");
//Test base classes as parameter in C#
multiple_inheritance_abstract_runme mhar=new multiple_inheritance_abstract_runme();
check(mhar.jcbase1b(d1)!=3, "jcbase1b() through Derived1 as parameter failed");
check(mhar.jcbase1b(d2)!=6, "jcbase1b() through Derived2 as parameter failed");
check(mhar.jcbase1b(d3)!=7, "jcbase1b() through Derived3 as parameter failed");
check(mhar.jcbase2(d1)!=4, "jcbase2() through Derived1 as parameter failed");
check(mhar.jcbase2(d3)!=8, "jcbase2() through Derived3 as parameter failed");
check(mhar.jabase1(d2)!=5, "jabase1() through Derived2 as parameter failed");
check(mhar.jabase1(d3)!=9, "jabase1() through Derived3 as parameter failed");
//Value parameters
//Test CBase1 CBase2 as parameters (note slicing for Derived and Bottom classes)
check(multiple_inheritance_abstract.InputValCBase1(d1)!=1, "InputValCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase1(d2)!=1, "InputValCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase1(d3)!=1, "InputValCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase2(d3)!=2, "InputValCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase2(d1)!=2, "InputValCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase1(cb1)!=1, "InputValCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase2(cb2)!=2, "InputValCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase1(b1)!=1, "InputValCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase1(b2)!=1, "InputValCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase1(b3)!=1, "InputValCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase2(b3)!=2, "InputValCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputValCBase2(b1)!=2, "InputValCBase2(), Bottom1 as a parameter failed");
//Pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_abstract.InputPtrABase1(d2)!=5, "InputPtrABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrABase1(d3)!=9, "InputPtrABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrABase1(b2)!=205, "InputPtrABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrABase1(b3)!=309, "InputPtrABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_abstract.InputPtrCBase1(d1)!=3, "InputPtrCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase1(d2)!=6, "InputPtrCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase1(d3)!=7, "InputPtrCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase2(d3)!=8, "InputPtrCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase2(d1)!=4, "InputPtrCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase1(cb1)!=1, "InputPtrCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase2(cb2)!=2, "InputPtrCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase1(b1)!=103, "InputPtrCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase1(b2)!=206, "InputPtrCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase1(b3)!=307, "InputPtrCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase2(b3)!=308, "InputPtrCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputPtrCBase2(b1)!=104, "InputPtrCBase2(), Bottom1 as a parameter failed");
//Reference parameters
//Test ABase1 as a parameter
check(multiple_inheritance_abstract.InputRefABase1(d2)!=5, "InputRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputRefABase1(d3)!=9, "InputRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputRefABase1(b2)!=205, "InputRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputRefABase1(b3)!=309, "InputRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_abstract.InputRefCBase1(d1)!=3, "InputRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase1(d2)!=6, "InputRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase1(d3)!=7, "InputRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase2(d3)!=8, "InputRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase2(d1)!=4, "InputRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase1(cb1)!=1, "InputRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase2(cb2)!=2, "InputRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase1(b1)!=103, "InputRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase1(b2)!=206, "InputRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase1(b3)!=307, "InputRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase2(b3)!=308, "InputRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputRefCBase2(b1)!=104, "InputRefCBase2(), Bottom1 as a parameter failed");
//Const reference pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_abstract.InputCPtrRefABase1(d2)!=5, "InputCPtrRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefABase1(d3)!=9, "InputCPtrRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefABase1(b2)!=205, "InputCPtrRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefABase1(b3)!=309, "InputCPtrRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_abstract.InputCPtrRefCBase1(d1)!=3, "InputCPtrRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase1(d2)!=6, "InputCPtrRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase1(d3)!=7, "InputCPtrRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase2(d3)!=8, "InputCPtrRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase2(d1)!=4, "InputCPtrRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase1(cb1)!=1, "InputCPtrRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase2(cb2)!=2, "InputCPtrRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase1(b1)!=103, "InputCPtrRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase1(b2)!=206, "InputCPtrRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase1(b3)!=307, "InputCPtrRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase2(b3)!=308, "InputCPtrRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_abstract.InputCPtrRefCBase2(b1)!=104, "InputCPtrRefCBase2(), Bottom1 as a parameter failed");
//Derived classes as parameters
check(multiple_inheritance_abstract.InputValDerived1(d1)!=3+4, "InputValDerived1() failed");
check(multiple_inheritance_abstract.InputValDerived2(d2)!=6+5, "InputValDerived2() failed");
check(multiple_inheritance_abstract.InputValDerived3(d3)!=7+8+9, "InputValDerived3() failed");
check(multiple_inheritance_abstract.InputRefDerived1(d1)!=3+4, "InputRefDerived1() failed");
check(multiple_inheritance_abstract.InputRefDerived2(d2)!=6+5, "InputRefDerived2() failed");
check(multiple_inheritance_abstract.InputRefDerived3(d3)!=7+8+9, "InputRefDerived3() failed");
check(multiple_inheritance_abstract.InputPtrDerived1(d1)!=3+4, "InputPtrDerived1() failed");
check(multiple_inheritance_abstract.InputPtrDerived2(d2)!=6+5, "InputPtrDerived2() failed");
check(multiple_inheritance_abstract.InputPtrDerived3(d3)!=7+8+9, "InputPtrDerived3() failed");
check(multiple_inheritance_abstract.InputCPtrRefDerived1(d1)!=3+4, "InputCPtrRefDerived1() failed");
check(multiple_inheritance_abstract.InputCPtrRefDerived2(d2)!=6+5, "InputCPtrRefDerived2() failed");
check(multiple_inheritance_abstract.InputCPtrRefDerived3(d3)!=7+8+9, "InputCPtrRefDerived3() failed");
//Bottom classes as Derived parameters
check(multiple_inheritance_abstract.InputValDerived1(b1)!=3+4, "InputValDerived1() failed");
check(multiple_inheritance_abstract.InputValDerived2(b2)!=6+5, "InputValDerived2() failed");
check(multiple_inheritance_abstract.InputValDerived3(b3)!=7+8+9, "InputValDerived3() failed");
check(multiple_inheritance_abstract.InputRefDerived1(b1)!=103+104, "InputRefDerived1() failed");
check(multiple_inheritance_abstract.InputRefDerived2(b2)!=206+205, "InputRefDerived2() failed");
check(multiple_inheritance_abstract.InputRefDerived3(b3)!=307+308+309, "InputRefDerived3() failed");
check(multiple_inheritance_abstract.InputPtrDerived1(b1)!=103+104, "InputPtrDerived1() failed");
check(multiple_inheritance_abstract.InputPtrDerived2(b2)!=206+205, "InputPtrDerived2() failed");
check(multiple_inheritance_abstract.InputPtrDerived3(b3)!=307+308+309, "InputPtrDerived3() failed");
check(multiple_inheritance_abstract.InputCPtrRefDerived1(b1)!=103+104, "InputCPtrRefDerived1() failed");
check(multiple_inheritance_abstract.InputCPtrRefDerived2(b2)!=206+205, "InputCPtrRefDerived2() failed");
check(multiple_inheritance_abstract.InputCPtrRefDerived3(b3)!=307+308+309, "InputCPtrRefDerived3() failed");
//Bottom classes as Bottom parameters
check(multiple_inheritance_abstract.InputValBottom1(b1)!=103+104, "InputValBottom1() failed");
check(multiple_inheritance_abstract.InputValBottom2(b2)!=206+205, "InputValBottom2() failed");
check(multiple_inheritance_abstract.InputValBottom3(b3)!=307+308+309, "InputValBottom3() failed");
check(multiple_inheritance_abstract.InputRefBottom1(b1)!=103+104, "InputRefBottom1() failed");
check(multiple_inheritance_abstract.InputRefBottom2(b2)!=206+205, "InputRefBottom2() failed");
check(multiple_inheritance_abstract.InputRefBottom3(b3)!=307+308+309, "InputRefBottom3() failed");
check(multiple_inheritance_abstract.InputPtrBottom1(b1)!=103+104, "InputPtrBottom1() failed");
check(multiple_inheritance_abstract.InputPtrBottom2(b2)!=206+205, "InputPtrBottom2() failed");
check(multiple_inheritance_abstract.InputPtrBottom3(b3)!=307+308+309, "InputPtrBottom3() failed");
check(multiple_inheritance_abstract.InputCPtrRefBottom1(b1)!=103+104, "InputCPtrRefBottom1() failed");
check(multiple_inheritance_abstract.InputCPtrRefBottom2(b2)!=206+205, "InputCPtrRefBottom2() failed");
check(multiple_inheritance_abstract.InputCPtrRefBottom3(b3)!=307+308+309, "InputCPtrRefBottom3() failed");
// Return pointers
check(multiple_inheritance_abstract.MakePtrDerived1_CBase1().cbase1y()!=3, "MakePtrDerived1_CBase1 failed");
check(multiple_inheritance_abstract.MakePtrDerived1_CBase2().cbase2()!=4, "MakePtrDerived1_CBase2 failed");
check(multiple_inheritance_abstract.MakePtrDerived2_CBase1().cbase1y()!=6, "MakePtrDerived2_CBase1 failed");
check(multiple_inheritance_abstract.MakePtrDerived2_ABase1().abase1()!=5, "MakePtrDerived2_ABase1 failed");
check(multiple_inheritance_abstract.MakePtrDerived3_ABase1().abase1()!=9, "MakePtrDerived3_ABase1 failed");
check(multiple_inheritance_abstract.MakePtrDerived3_CBase1().cbase1y()!=7, "MakePtrDerived3_CBase1 failed");
check(multiple_inheritance_abstract.MakePtrDerived3_CBase2().cbase2()!=8, "MakePtrDerived3_CBase2 failed");
// Return references
check(multiple_inheritance_abstract.MakeRefDerived1_CBase1().cbase1y()!=3, "MakeRefDerived1_CBase1 failed");
check(multiple_inheritance_abstract.MakeRefDerived1_CBase2().cbase2()!=4, "MakeRefDerived1_CBase2 failed");
check(multiple_inheritance_abstract.MakeRefDerived2_CBase1().cbase1y()!=6, "MakeRefDerived2_CBase1 failed");
check(multiple_inheritance_abstract.MakeRefDerived2_ABase1().abase1()!=5, "MakeRefDerived2_ABase1 failed");
check(multiple_inheritance_abstract.MakeRefDerived3_ABase1().abase1()!=9, "MakeRefDerived3_ABase1 failed");
check(multiple_inheritance_abstract.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed");
check(multiple_inheritance_abstract.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed");
// Return by value (sliced objects)
check(multiple_inheritance_abstract.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed");
check(multiple_inheritance_abstract.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed");
check(multiple_inheritance_abstract.MakeValDerived2_CBase1().cbase1y()!=1, "MakeValDerived2_CBase1 failed");
check(multiple_inheritance_abstract.MakeValDerived3_CBase1().cbase1y()!=1, "MakeValDerived3_CBase1 failed");
check(multiple_inheritance_abstract.MakeValDerived3_CBase2().cbase2()!=2, "MakeValDerived3_CBase2 failed");
}
}
using System;
using System.Collections.Generic;
using multiple_inheritance_interfacesNamespace;
public class multiple_inheritance_interfaces_runme {
static string SortArrayToString(string[] types) {
Array.Sort<string>(types);
return string.Join(" ", types);
}
static string SortArrayToString(Type[] types) {
List<string> stypes = new List<string>();
foreach (Type t in types)
stypes.Add(t.Name);
return SortArrayToString(stypes.ToArray());
}
private static void checkBaseAndInterfaces(Type cls, bool interfaceExpected, string baseClass, string[] interfaces) {
string[] expectedInterfaces = new string[interfaces.Length + (interfaceExpected ? 0 : 1)];
for (int i=0; i<interfaces.Length; ++i)
expectedInterfaces[i] = interfaces[i];
if (!interfaceExpected)
expectedInterfaces[interfaces.Length] = "IDisposable";
Type[] actualInterfaces = cls.GetInterfaces();
string expectedInterfacesString = SortArrayToString(expectedInterfaces);
string actualInterfacesString = SortArrayToString(actualInterfaces);
if (expectedInterfacesString != actualInterfacesString)
throw new Exception("Expected interfaces for " + cls.Name + ": \n" + expectedInterfacesString + "\n" + "Actual interfaces: \n" + actualInterfacesString);
string expectedBaseString = null;
if (interfaceExpected) {
// expecting an interface
if (!cls.IsInterface)
throw new Exception(cls.Name + " should be an interface but is not");
expectedBaseString = string.IsNullOrEmpty(baseClass) ? "" : "multiple_inheritance_interfacesNamespace." + baseClass;
} else {
// expecting a class
if (cls.IsInterface)
throw new Exception(cls.Name + " is an interface but it should not be");
expectedBaseString = string.IsNullOrEmpty(baseClass) ? "Object" : baseClass;
}
string actualBaseString = cls.BaseType == null ? "" : cls.BaseType.Name;
if (expectedBaseString != actualBaseString)
throw new Exception("Expected base for " + cls.Name + ": [" + expectedBaseString + "]" + " Actual base: [" + actualBaseString + "]");
}
public static void Main() {
// Note that we can't get just the immediate interface
// Type.GetInterfaces() returns all interfaces up the inheritance hierarchy
checkBaseAndInterfaces(typeof(IA), true, "", new string[] {});
checkBaseAndInterfaces(typeof(IB), true, "", new string[] {});
checkBaseAndInterfaces(typeof(IC), true, "", new string[] {"IA", "IB"});
checkBaseAndInterfaces(typeof(A), false, "", new string[] {"IA"});
checkBaseAndInterfaces(typeof(B), false, "", new string[] {"IB"});
checkBaseAndInterfaces(typeof(C), false, "", new string[] {"IA", "IB", "IC"});
checkBaseAndInterfaces(typeof(D), false, "", new string[] {"IA", "IB", "IC"});
checkBaseAndInterfaces(typeof(E), false, "D", new string[] {"IA", "IB", "IC"});
checkBaseAndInterfaces(typeof(IJ), true, "", new string[] {});
checkBaseAndInterfaces(typeof(IK), true, "", new string[] {"IJ"});
checkBaseAndInterfaces(typeof(IL), true, "", new string[] {"IJ", "IK"});
checkBaseAndInterfaces(typeof(J), false, "", new string[] {"IJ"});
checkBaseAndInterfaces(typeof(K), false, "", new string[] {"IJ", "IK"});
checkBaseAndInterfaces(typeof(L), false, "", new string[] {"IJ", "IK", "IL"});
checkBaseAndInterfaces(typeof(M), false, "", new string[] {"IJ", "IK", "IL"});
checkBaseAndInterfaces(typeof(P), false, "", new string[] {});
checkBaseAndInterfaces(typeof(IQ), true, "", new string[] {});
checkBaseAndInterfaces(typeof(Q), false, "", new string[] {"IQ"});
checkBaseAndInterfaces(typeof(R), false, "P", new string[] {"IQ"});
checkBaseAndInterfaces(typeof(S), false, "P", new string[] {"IQ"});
checkBaseAndInterfaces(typeof(T), false, "", new string[] {"IQ"});
checkBaseAndInterfaces(typeof(U), false, "R", new string[] {"IQ"});
checkBaseAndInterfaces(typeof(V), false, "S", new string[] {"IQ"});
checkBaseAndInterfaces(typeof(W), false, "T", new string[] {"IQ"});
// overloaded methods check
D d = new D();
d.ia();
d.ia(10);
d.ia("bye");
d.ia("bye", false);
}
}
using System;
using multiple_inheritance_nspaceNamespace;
using multiple_inheritance_nspaceNamespace.Space;
public class multiple_inheritance_nspace_runme {
//Test base class as a parameter in C#
int jcbase1b(CBase1SwigInterface cb1){
return cb1.cbase1y();
}
int jabase1(ABase1SwigInterface ab1){
return ab1.abase1();
}
int jcbase2(CBase2SwigInterface cb2){
return cb2.cbase2();
}
public static void check(bool fail, string msg) {
if (fail)
throw new Exception(msg);
}
public static void Main() {
//Test Derived1
Derived1 d1=new Derived1();
check(d1.cbase1y()!=3, "Derived1::cbase1y() failed");
check(d1.cbase2()!=4, "Derived1::cbase2() failed");
//Test Derived2
Derived2 d2=new Derived2();
check(d2.cbase1y()!=6, "Derived2::cbase1y() failed");
check(d2.abase1()!=5, "Derived2::abase1() failed");
//Test Derived3
Derived3 d3=new Derived3();
check(d3.cbase1y()!=7, "Derived3::cbase1y() failed");
check(d3.cbase2()!=8, "Derived3::cbase2() failed");
check(d3.abase1()!=9, "Derived3::abase1() failed");
//Test Bottom1
Bottom1 b1=new Bottom1();
check(b1.cbase1y()!=103, "Bottom1::cbase1y() failed");
check(b1.cbase2()!=104, "Bottom1::cbase2() failed");
//Test Bottom2
Bottom2 b2=new Bottom2();
check(b2.cbase1y()!=206, "Bottom2::cbase1y() failed");
check(b2.abase1()!=205, "Bottom2::abase1() failed");
//Test Bottom3
Bottom3 b3=new Bottom3();
check(b3.cbase1y()!=307, "Bottom3::cbase1y() failed");
check(b3.cbase2()!=308, "Bottom3::cbase2() failed");
check(b3.abase1()!=309, "Bottom3::abase1() failed");
//Test interfaces from c++ classes
CBase1SwigInterface cb1=new CBase1();
CBase2SwigInterface cb2=new CBase2();
check(cb1.cbase1y()!=1, "CBase1::cbase1y() failed");
check(cb2.cbase2()!=2, "CBase2::cbase2() failed");
//Test nspace class as return value
ABase1SwigInterface ab1=d3.cloneit();
check(ab1.abase1()!=9, "Derived3::abase1() through ABase1 failed");
//Test concrete base class as return value
CBase1SwigInterface cb6=d2.cloneit();
CBase2SwigInterface cb7=d1.cloneit();
check(cb6.cbase1y()!=6, "Derived2::cbase1y() through CBase1 failed");
check(cb7.cbase2()!=4, "Derived1:cbase2() through ABase1 failed");
//Test multi inheritance
CBase1SwigInterface cb3=new Derived1();
CBase1SwigInterface cb4=new Derived3();
CBase2SwigInterface cb5=new Derived3();
ABase1SwigInterface ab6=new Derived2();
check(cb3.cbase1y()!=3, "Derived1::cbase1y() through CBase1 failed");
check(cb4.cbase1y()!=7, "Derived3::cbase1y() through CBase1 failed");
check(cb5.cbase2()!=8, "Derived3::cbase2() through CBase2 failed");
check(ab6.abase1()!=5, "Derived2::abase1() through ABase1 failed");
//Test base classes as parameter in C#
multiple_inheritance_nspace_runme mhar=new multiple_inheritance_nspace_runme();
check(mhar.jcbase1b(d1)!=3, "jcbase1b() through Derived1 as parameter failed");
check(mhar.jcbase1b(d2)!=6, "jcbase1b() through Derived2 as parameter failed");
check(mhar.jcbase1b(d3)!=7, "jcbase1b() through Derived3 as parameter failed");
check(mhar.jcbase2(d1)!=4, "jcbase2() through Derived1 as parameter failed");
check(mhar.jcbase2(d3)!=8, "jcbase2() through Derived3 as parameter failed");
check(mhar.jabase1(d2)!=5, "jabase1() through Derived2 as parameter failed");
check(mhar.jabase1(d3)!=9, "jabase1() through Derived3 as parameter failed");
//Value parameters
//Test CBase1 CBase2 as parameters (note slicing for Derived and Bottom classes)
check(multiple_inheritance_nspace.InputValCBase1(d1)!=1, "InputValCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase1(d2)!=1, "InputValCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase1(d3)!=1, "InputValCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase2(d3)!=2, "InputValCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase2(d1)!=2, "InputValCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase1(cb1)!=1, "InputValCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase2(cb2)!=2, "InputValCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase1(b1)!=1, "InputValCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase1(b2)!=1, "InputValCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase1(b3)!=1, "InputValCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase2(b3)!=2, "InputValCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputValCBase2(b1)!=2, "InputValCBase2(), Bottom1 as a parameter failed");
//Pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_nspace.InputPtrABase1(d2)!=5, "InputPtrABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrABase1(d3)!=9, "InputPtrABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrABase1(b2)!=205, "InputPtrABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrABase1(b3)!=309, "InputPtrABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_nspace.InputPtrCBase1(d1)!=3, "InputPtrCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase1(d2)!=6, "InputPtrCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase1(d3)!=7, "InputPtrCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase2(d3)!=8, "InputPtrCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase2(d1)!=4, "InputPtrCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase1(cb1)!=1, "InputPtrCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase2(cb2)!=2, "InputPtrCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase1(b1)!=103, "InputPtrCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase1(b2)!=206, "InputPtrCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase1(b3)!=307, "InputPtrCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase2(b3)!=308, "InputPtrCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputPtrCBase2(b1)!=104, "InputPtrCBase2(), Bottom1 as a parameter failed");
//Reference parameters
//Test ABase1 as a parameter
check(multiple_inheritance_nspace.InputRefABase1(d2)!=5, "InputRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputRefABase1(d3)!=9, "InputRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputRefABase1(b2)!=205, "InputRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputRefABase1(b3)!=309, "InputRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_nspace.InputRefCBase1(d1)!=3, "InputRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase1(d2)!=6, "InputRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase1(d3)!=7, "InputRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase2(d3)!=8, "InputRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase2(d1)!=4, "InputRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase1(cb1)!=1, "InputRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase2(cb2)!=2, "InputRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase1(b1)!=103, "InputRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase1(b2)!=206, "InputRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase1(b3)!=307, "InputRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase2(b3)!=308, "InputRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputRefCBase2(b1)!=104, "InputRefCBase2(), Bottom1 as a parameter failed");
//Const reference pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_nspace.InputCPtrRefABase1(d2)!=5, "InputCPtrRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefABase1(d3)!=9, "InputCPtrRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefABase1(b2)!=205, "InputCPtrRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefABase1(b3)!=309, "InputCPtrRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_nspace.InputCPtrRefCBase1(d1)!=3, "InputCPtrRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase1(d2)!=6, "InputCPtrRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase1(d3)!=7, "InputCPtrRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase2(d3)!=8, "InputCPtrRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase2(d1)!=4, "InputCPtrRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase1(cb1)!=1, "InputCPtrRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase2(cb2)!=2, "InputCPtrRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase1(b1)!=103, "InputCPtrRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase1(b2)!=206, "InputCPtrRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase1(b3)!=307, "InputCPtrRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase2(b3)!=308, "InputCPtrRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_nspace.InputCPtrRefCBase2(b1)!=104, "InputCPtrRefCBase2(), Bottom1 as a parameter failed");
//Derived classes as parameters
check(multiple_inheritance_nspace.InputValDerived1(d1)!=3+4, "InputValDerived1() failed");
check(multiple_inheritance_nspace.InputValDerived2(d2)!=6+5, "InputValDerived2() failed");
check(multiple_inheritance_nspace.InputValDerived3(d3)!=7+8+9, "InputValDerived3() failed");
check(multiple_inheritance_nspace.InputRefDerived1(d1)!=3+4, "InputRefDerived1() failed");
check(multiple_inheritance_nspace.InputRefDerived2(d2)!=6+5, "InputRefDerived2() failed");
check(multiple_inheritance_nspace.InputRefDerived3(d3)!=7+8+9, "InputRefDerived3() failed");
check(multiple_inheritance_nspace.InputPtrDerived1(d1)!=3+4, "InputPtrDerived1() failed");
check(multiple_inheritance_nspace.InputPtrDerived2(d2)!=6+5, "InputPtrDerived2() failed");
check(multiple_inheritance_nspace.InputPtrDerived3(d3)!=7+8+9, "InputPtrDerived3() failed");
check(multiple_inheritance_nspace.InputCPtrRefDerived1(d1)!=3+4, "InputCPtrRefDerived1() failed");
check(multiple_inheritance_nspace.InputCPtrRefDerived2(d2)!=6+5, "InputCPtrRefDerived2() failed");
check(multiple_inheritance_nspace.InputCPtrRefDerived3(d3)!=7+8+9, "InputCPtrRefDerived3() failed");
//Bottom classes as Derived parameters
check(multiple_inheritance_nspace.InputValDerived1(b1)!=3+4, "InputValDerived1() failed");
check(multiple_inheritance_nspace.InputValDerived2(b2)!=6+5, "InputValDerived2() failed");
check(multiple_inheritance_nspace.InputValDerived3(b3)!=7+8+9, "InputValDerived3() failed");
check(multiple_inheritance_nspace.InputRefDerived1(b1)!=103+104, "InputRefDerived1() failed");
check(multiple_inheritance_nspace.InputRefDerived2(b2)!=206+205, "InputRefDerived2() failed");
check(multiple_inheritance_nspace.InputRefDerived3(b3)!=307+308+309, "InputRefDerived3() failed");
check(multiple_inheritance_nspace.InputPtrDerived1(b1)!=103+104, "InputPtrDerived1() failed");
check(multiple_inheritance_nspace.InputPtrDerived2(b2)!=206+205, "InputPtrDerived2() failed");
check(multiple_inheritance_nspace.InputPtrDerived3(b3)!=307+308+309, "InputPtrDerived3() failed");
check(multiple_inheritance_nspace.InputCPtrRefDerived1(b1)!=103+104, "InputCPtrRefDerived1() failed");
check(multiple_inheritance_nspace.InputCPtrRefDerived2(b2)!=206+205, "InputCPtrRefDerived2() failed");
check(multiple_inheritance_nspace.InputCPtrRefDerived3(b3)!=307+308+309, "InputCPtrRefDerived3() failed");
//Bottom classes as Bottom parameters
check(multiple_inheritance_nspace.InputValBottom1(b1)!=103+104, "InputValBottom1() failed");
check(multiple_inheritance_nspace.InputValBottom2(b2)!=206+205, "InputValBottom2() failed");
check(multiple_inheritance_nspace.InputValBottom3(b3)!=307+308+309, "InputValBottom3() failed");
check(multiple_inheritance_nspace.InputRefBottom1(b1)!=103+104, "InputRefBottom1() failed");
check(multiple_inheritance_nspace.InputRefBottom2(b2)!=206+205, "InputRefBottom2() failed");
check(multiple_inheritance_nspace.InputRefBottom3(b3)!=307+308+309, "InputRefBottom3() failed");
check(multiple_inheritance_nspace.InputPtrBottom1(b1)!=103+104, "InputPtrBottom1() failed");
check(multiple_inheritance_nspace.InputPtrBottom2(b2)!=206+205, "InputPtrBottom2() failed");
check(multiple_inheritance_nspace.InputPtrBottom3(b3)!=307+308+309, "InputPtrBottom3() failed");
check(multiple_inheritance_nspace.InputCPtrRefBottom1(b1)!=103+104, "InputCPtrRefBottom1() failed");
check(multiple_inheritance_nspace.InputCPtrRefBottom2(b2)!=206+205, "InputCPtrRefBottom2() failed");
check(multiple_inheritance_nspace.InputCPtrRefBottom3(b3)!=307+308+309, "InputCPtrRefBottom3() failed");
// Return pointers
check(multiple_inheritance_nspace.MakePtrDerived1_CBase1().cbase1y()!=3, "MakePtrDerived1_CBase1 failed");
check(multiple_inheritance_nspace.MakePtrDerived1_CBase2().cbase2()!=4, "MakePtrDerived1_CBase2 failed");
check(multiple_inheritance_nspace.MakePtrDerived2_CBase1().cbase1y()!=6, "MakePtrDerived2_CBase1 failed");
check(multiple_inheritance_nspace.MakePtrDerived2_ABase1().abase1()!=5, "MakePtrDerived2_ABase1 failed");
check(multiple_inheritance_nspace.MakePtrDerived3_ABase1().abase1()!=9, "MakePtrDerived3_ABase1 failed");
check(multiple_inheritance_nspace.MakePtrDerived3_CBase1().cbase1y()!=7, "MakePtrDerived3_CBase1 failed");
check(multiple_inheritance_nspace.MakePtrDerived3_CBase2().cbase2()!=8, "MakePtrDerived3_CBase2 failed");
// Return references
check(multiple_inheritance_nspace.MakeRefDerived1_CBase1().cbase1y()!=3, "MakeRefDerived1_CBase1 failed");
check(multiple_inheritance_nspace.MakeRefDerived1_CBase2().cbase2()!=4, "MakeRefDerived1_CBase2 failed");
check(multiple_inheritance_nspace.MakeRefDerived2_CBase1().cbase1y()!=6, "MakeRefDerived2_CBase1 failed");
check(multiple_inheritance_nspace.MakeRefDerived2_ABase1().abase1()!=5, "MakeRefDerived2_ABase1 failed");
check(multiple_inheritance_nspace.MakeRefDerived3_ABase1().abase1()!=9, "MakeRefDerived3_ABase1 failed");
check(multiple_inheritance_nspace.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed");
check(multiple_inheritance_nspace.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed");
// Return by value (sliced objects)
check(multiple_inheritance_nspace.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed");
check(multiple_inheritance_nspace.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed");
check(multiple_inheritance_nspace.MakeValDerived2_CBase1().cbase1y()!=1, "MakeValDerived2_CBase1 failed");
check(multiple_inheritance_nspace.MakeValDerived3_CBase1().cbase1y()!=1, "MakeValDerived3_CBase1 failed");
check(multiple_inheritance_nspace.MakeValDerived3_CBase2().cbase2()!=2, "MakeValDerived3_CBase2 failed");
}
}
using System;
using multiple_inheritance_shared_ptrNamespace;
public class multiple_inheritance_shared_ptr_runme {
//Test base class as a parameter in C#
int jcbase1b(CBase1 cb1){
return cb1.cbase1y();
}
int jabase1(ABase1 ab1){
return ab1.abase1();
}
int jcbase2(CBase2 cb2){
return cb2.cbase2();
}
public static void check(bool fail, string msg) {
if (fail)
throw new Exception(msg);
}
public static void Main() {
//Test Derived1
Derived1 d1=new Derived1();
check(d1.cbase1y()!=3, "Derived1::cbase1y() failed");
check(d1.cbase2()!=4, "Derived1::cbase2() failed");
//Test Derived2
Derived2 d2=new Derived2();
check(d2.cbase1y()!=6, "Derived2::cbase1y() failed");
check(d2.abase1()!=5, "Derived2::abase1() failed");
//Test Derived3
Derived3 d3=new Derived3();
check(d3.cbase1y()!=7, "Derived3::cbase1y() failed");
check(d3.cbase2()!=8, "Derived3::cbase2() failed");
check(d3.abase1()!=9, "Derived3::abase1() failed");
//Test Bottom1
Bottom1 b1=new Bottom1();
check(b1.cbase1y()!=103, "Bottom1::cbase1y() failed");
check(b1.cbase2()!=104, "Bottom1::cbase2() failed");
//Test Bottom2
Bottom2 b2=new Bottom2();
check(b2.cbase1y()!=206, "Bottom2::cbase1y() failed");
check(b2.abase1()!=205, "Bottom2::abase1() failed");
//Test Bottom3
Bottom3 b3=new Bottom3();
check(b3.cbase1y()!=307, "Bottom3::cbase1y() failed");
check(b3.cbase2()!=308, "Bottom3::cbase2() failed");
check(b3.abase1()!=309, "Bottom3::abase1() failed");
//Test interfaces from c++ classes
CBase1 cb1=new CBase1SwigImpl();
CBase2 cb2=new CBase2SwigImpl();
check(cb1.cbase1y()!=1, "CBase1::cbase1y() failed");
check(cb2.cbase2()!=2, "CBase2::cbase2() failed");
//Test abstract class as return value
ABase1 ab1=d3.cloneit();
check(ab1.abase1()!=9, "Derived3::abase1() through ABase1 failed");
//Test concrete base class as return value
CBase1 cb6=d2.cloneit();
CBase2 cb7=d1.cloneit();
check(cb6.cbase1y()!=6, "Derived2::cbase1y() through CBase1 failed");
check(cb7.cbase2()!=4, "Derived1:cbase2() through ABase1 failed");
//Test multi inheritance
CBase1 cb3=new Derived1();
CBase1 cb4=new Derived3();
CBase2 cb5=new Derived3();
ABase1 ab6=new Derived2();
check(cb3.cbase1y()!=3, "Derived1::cbase1y() through CBase1 failed");
check(cb4.cbase1y()!=7, "Derived3::cbase1y() through CBase1 failed");
check(cb5.cbase2()!=8, "Derived3::cbase2() through CBase2 failed");
check(ab6.abase1()!=5, "Derived2::abase1() through ABase1 failed");
//Test base classes as parameter in C#
multiple_inheritance_shared_ptr_runme mhar=new multiple_inheritance_shared_ptr_runme();
check(mhar.jcbase1b(d1)!=3, "jcbase1b() through Derived1 as parameter failed");
check(mhar.jcbase1b(d2)!=6, "jcbase1b() through Derived2 as parameter failed");
check(mhar.jcbase1b(d3)!=7, "jcbase1b() through Derived3 as parameter failed");
check(mhar.jcbase2(d1)!=4, "jcbase2() through Derived1 as parameter failed");
check(mhar.jcbase2(d3)!=8, "jcbase2() through Derived3 as parameter failed");
check(mhar.jabase1(d2)!=5, "jabase1() through Derived2 as parameter failed");
check(mhar.jabase1(d3)!=9, "jabase1() through Derived3 as parameter failed");
//Value parameters
//Test CBase1 CBase2 as parameters (note slicing for Derived and Bottom classes)
check(multiple_inheritance_shared_ptr.InputValCBase1(d1)!=1, "InputValCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase1(d2)!=1, "InputValCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase1(d3)!=1, "InputValCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase2(d3)!=2, "InputValCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase2(d1)!=2, "InputValCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase1(cb1)!=1, "InputValCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase2(cb2)!=2, "InputValCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase1(b1)!=1, "InputValCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase1(b2)!=1, "InputValCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase1(b3)!=1, "InputValCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase2(b3)!=2, "InputValCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputValCBase2(b1)!=2, "InputValCBase2(), Bottom1 as a parameter failed");
//Pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_shared_ptr.InputPtrABase1(d2)!=5, "InputPtrABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrABase1(d3)!=9, "InputPtrABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrABase1(b2)!=205, "InputPtrABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrABase1(b3)!=309, "InputPtrABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_shared_ptr.InputPtrCBase1(d1)!=3, "InputPtrCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase1(d2)!=6, "InputPtrCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase1(d3)!=7, "InputPtrCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase2(d3)!=8, "InputPtrCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase2(d1)!=4, "InputPtrCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase1(cb1)!=1, "InputPtrCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase2(cb2)!=2, "InputPtrCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase1(b1)!=103, "InputPtrCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase1(b2)!=206, "InputPtrCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase1(b3)!=307, "InputPtrCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase2(b3)!=308, "InputPtrCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputPtrCBase2(b1)!=104, "InputPtrCBase2(), Bottom1 as a parameter failed");
//Reference parameters
//Test ABase1 as a parameter
check(multiple_inheritance_shared_ptr.InputRefABase1(d2)!=5, "InputRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefABase1(d3)!=9, "InputRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefABase1(b2)!=205, "InputRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefABase1(b3)!=309, "InputRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_shared_ptr.InputRefCBase1(d1)!=3, "InputRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase1(d2)!=6, "InputRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase1(d3)!=7, "InputRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase2(d3)!=8, "InputRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase2(d1)!=4, "InputRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase1(cb1)!=1, "InputRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase2(cb2)!=2, "InputRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase1(b1)!=103, "InputRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase1(b2)!=206, "InputRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase1(b3)!=307, "InputRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase2(b3)!=308, "InputRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputRefCBase2(b1)!=104, "InputRefCBase2(), Bottom1 as a parameter failed");
//Const reference pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_shared_ptr.InputCPtrRefABase1(d2)!=5, "InputCPtrRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefABase1(d3)!=9, "InputCPtrRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefABase1(b2)!=205, "InputCPtrRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefABase1(b3)!=309, "InputCPtrRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(d1)!=3, "InputCPtrRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(d2)!=6, "InputCPtrRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(d3)!=7, "InputCPtrRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase2(d3)!=8, "InputCPtrRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase2(d1)!=4, "InputCPtrRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(cb1)!=1, "InputCPtrRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase2(cb2)!=2, "InputCPtrRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(b1)!=103, "InputCPtrRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(b2)!=206, "InputCPtrRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase1(b3)!=307, "InputCPtrRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase2(b3)!=308, "InputCPtrRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefCBase2(b1)!=104, "InputCPtrRefCBase2(), Bottom1 as a parameter failed");
//Shared pointer parameters
//Test ABase1 as a parameter
check(multiple_inheritance_shared_ptr.InputSharedPtrABase1(d2)!=5, "InputSharedPtrABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrABase1(d3)!=9, "InputSharedPtrABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrABase1(b2)!=205, "InputSharedPtrABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrABase1(b3)!=309, "InputSharedPtrABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(d1)!=3, "InputSharedPtrCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(d2)!=6, "InputSharedPtrCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(d3)!=7, "InputSharedPtrCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase2(d3)!=8, "InputSharedPtrCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase2(d1)!=4, "InputSharedPtrCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(cb1)!=1, "InputSharedPtrCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase2(cb2)!=2, "InputSharedPtrCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(b1)!=103, "InputSharedPtrCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(b2)!=206, "InputSharedPtrCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase1(b3)!=307, "InputSharedPtrCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase2(b3)!=308, "InputSharedPtrCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrCBase2(b1)!=104, "InputSharedPtrCBase2(), Bottom1 as a parameter failed");
//Shared pointer reference parameters
//Test ABase1 as a parameter
check(multiple_inheritance_shared_ptr.InputSharedPtrRefABase1(d2)!=5, "InputSharedPtrRefABase1() through Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefABase1(d3)!=9, "InputSharedPtrRefABase1() through Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefABase1(b2)!=205, "InputSharedPtrRefABase1() through Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefABase1(b3)!=309, "InputSharedPtrRefABase1() through Bottom3 as a parameter failed");
//Test CBase1 CBase2 as parameters
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(d1)!=3, "InputSharedPtrRefCBase1(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(d2)!=6, "InputSharedPtrRefCBase1(), Derived2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(d3)!=7, "InputSharedPtrRefCBase1(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase2(d3)!=8, "InputSharedPtrRefCBase2(), Derived3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase2(d1)!=4, "InputSharedPtrRefCBase2(), Derived1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(cb1)!=1, "InputSharedPtrRefCBase1(), CBase1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase2(cb2)!=2, "InputSharedPtrRefCBase2(), CBase2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(b1)!=103, "InputSharedPtrRefCBase1(), Bottom1 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(b2)!=206, "InputSharedPtrRefCBase1(), Bottom2 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase1(b3)!=307, "InputSharedPtrRefCBase1(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase2(b3)!=308, "InputSharedPtrRefCBase2(), Bottom3 as a parameter failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefCBase2(b1)!=104, "InputSharedPtrRefCBase2(), Bottom1 as a parameter failed");
//Derived classes as parameters
check(multiple_inheritance_shared_ptr.InputValDerived1(d1)!=3+4, "InputValDerived1() failed");
check(multiple_inheritance_shared_ptr.InputValDerived2(d2)!=6+5, "InputValDerived2() failed");
check(multiple_inheritance_shared_ptr.InputValDerived3(d3)!=7+8+9, "InputValDerived3() failed");
check(multiple_inheritance_shared_ptr.InputRefDerived1(d1)!=3+4, "InputRefDerived1() failed");
check(multiple_inheritance_shared_ptr.InputRefDerived2(d2)!=6+5, "InputRefDerived2() failed");
check(multiple_inheritance_shared_ptr.InputRefDerived3(d3)!=7+8+9, "InputRefDerived3() failed");
check(multiple_inheritance_shared_ptr.InputPtrDerived1(d1)!=3+4, "InputPtrDerived1() failed");
check(multiple_inheritance_shared_ptr.InputPtrDerived2(d2)!=6+5, "InputPtrDerived2() failed");
check(multiple_inheritance_shared_ptr.InputPtrDerived3(d3)!=7+8+9, "InputPtrDerived3() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefDerived1(d1)!=3+4, "InputCPtrRefDerived1() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefDerived2(d2)!=6+5, "InputCPtrRefDerived2() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefDerived3(d3)!=7+8+9, "InputCPtrRefDerived3() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrDerived1(d1)!=3+4, "InputSharedPtrDerived1() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrDerived2(d2)!=6+5, "InputSharedPtrDerived2() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrDerived3(d3)!=7+8+9, "InputSharedPtrDerived3() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefDerived1(d1)!=3+4, "InputSharedPtrRefDerived1() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefDerived2(d2)!=6+5, "InputSharedPtrRefDerived2() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefDerived3(d3)!=7+8+9, "InputSharedPtrRefDerived3() failed");
//Bottom classes as Derived parameters
check(multiple_inheritance_shared_ptr.InputValDerived1(b1)!=3+4, "InputValDerived1() failed");
check(multiple_inheritance_shared_ptr.InputValDerived2(b2)!=6+5, "InputValDerived2() failed");
check(multiple_inheritance_shared_ptr.InputValDerived3(b3)!=7+8+9, "InputValDerived3() failed");
check(multiple_inheritance_shared_ptr.InputRefDerived1(b1)!=103+104, "InputRefDerived1() failed");
check(multiple_inheritance_shared_ptr.InputRefDerived2(b2)!=206+205, "InputRefDerived2() failed");
check(multiple_inheritance_shared_ptr.InputRefDerived3(b3)!=307+308+309, "InputRefDerived3() failed");
check(multiple_inheritance_shared_ptr.InputPtrDerived1(b1)!=103+104, "InputPtrDerived1() failed");
check(multiple_inheritance_shared_ptr.InputPtrDerived2(b2)!=206+205, "InputPtrDerived2() failed");
check(multiple_inheritance_shared_ptr.InputPtrDerived3(b3)!=307+308+309, "InputPtrDerived3() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefDerived1(b1)!=103+104, "InputCPtrRefDerived1() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefDerived2(b2)!=206+205, "InputCPtrRefDerived2() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefDerived3(b3)!=307+308+309, "InputCPtrRefDerived3() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrDerived1(b1)!=103+104, "InputSharedPtrDerived1() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrDerived2(b2)!=206+205, "InputSharedPtrDerived2() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrDerived3(b3)!=307+308+309, "InputSharedPtrDerived3() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefDerived1(b1)!=103+104, "InputSharedPtrRefDerived1() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefDerived2(b2)!=206+205, "InputSharedPtrRefDerived2() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefDerived3(b3)!=307+308+309, "InputSharedPtrRefDerived3() failed");
//Bottom classes as Bottom parameters
check(multiple_inheritance_shared_ptr.InputValBottom1(b1)!=103+104, "InputValBottom1() failed");
check(multiple_inheritance_shared_ptr.InputValBottom2(b2)!=206+205, "InputValBottom2() failed");
check(multiple_inheritance_shared_ptr.InputValBottom3(b3)!=307+308+309, "InputValBottom3() failed");
check(multiple_inheritance_shared_ptr.InputRefBottom1(b1)!=103+104, "InputRefBottom1() failed");
check(multiple_inheritance_shared_ptr.InputRefBottom2(b2)!=206+205, "InputRefBottom2() failed");
check(multiple_inheritance_shared_ptr.InputRefBottom3(b3)!=307+308+309, "InputRefBottom3() failed");
check(multiple_inheritance_shared_ptr.InputPtrBottom1(b1)!=103+104, "InputPtrBottom1() failed");
check(multiple_inheritance_shared_ptr.InputPtrBottom2(b2)!=206+205, "InputPtrBottom2() failed");
check(multiple_inheritance_shared_ptr.InputPtrBottom3(b3)!=307+308+309, "InputPtrBottom3() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefBottom1(b1)!=103+104, "InputCPtrRefBottom1() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefBottom2(b2)!=206+205, "InputCPtrRefBottom2() failed");
check(multiple_inheritance_shared_ptr.InputCPtrRefBottom3(b3)!=307+308+309, "InputCPtrRefBottom3() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrBottom1(b1)!=103+104, "InputSharedPtrBottom1() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrBottom2(b2)!=206+205, "InputSharedPtrBottom2() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrBottom3(b3)!=307+308+309, "InputSharedPtrBottom3() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefBottom1(b1)!=103+104, "InputSharedPtrRefBottom1() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefBottom2(b2)!=206+205, "InputSharedPtrRefBottom2() failed");
check(multiple_inheritance_shared_ptr.InputSharedPtrRefBottom3(b3)!=307+308+309, "InputSharedPtrRefBottom3() failed");
// Return pointers
check(multiple_inheritance_shared_ptr.MakePtrDerived1_CBase1().cbase1y()!=3, "MakePtrDerived1_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakePtrDerived1_CBase2().cbase2()!=4, "MakePtrDerived1_CBase2 failed");
check(multiple_inheritance_shared_ptr.MakePtrDerived2_CBase1().cbase1y()!=6, "MakePtrDerived2_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakePtrDerived2_ABase1().abase1()!=5, "MakePtrDerived2_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakePtrDerived3_ABase1().abase1()!=9, "MakePtrDerived3_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakePtrDerived3_CBase1().cbase1y()!=7, "MakePtrDerived3_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakePtrDerived3_CBase2().cbase2()!=8, "MakePtrDerived3_CBase2 failed");
// Return references
check(multiple_inheritance_shared_ptr.MakeRefDerived1_CBase1().cbase1y()!=3, "MakeRefDerived1_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeRefDerived1_CBase2().cbase2()!=4, "MakeRefDerived1_CBase2 failed");
check(multiple_inheritance_shared_ptr.MakeRefDerived2_CBase1().cbase1y()!=6, "MakeRefDerived2_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeRefDerived2_ABase1().abase1()!=5, "MakeRefDerived2_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakeRefDerived3_ABase1().abase1()!=9, "MakeRefDerived3_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakeRefDerived3_CBase1().cbase1y()!=7, "MakeRefDerived3_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeRefDerived3_CBase2().cbase2()!=8, "MakeRefDerived3_CBase2 failed");
// Return by value (sliced objects)
check(multiple_inheritance_shared_ptr.MakeValDerived1_CBase1().cbase1y()!=1, "MakeValDerived1_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeValDerived1_CBase2().cbase2()!=2, "MakeValDerived1_CBase2 failed");
check(multiple_inheritance_shared_ptr.MakeValDerived2_CBase1().cbase1y()!=1, "MakeValDerived2_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeValDerived3_CBase1().cbase1y()!=1, "MakeValDerived3_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeValDerived3_CBase2().cbase2()!=2, "MakeValDerived3_CBase2 failed");
// Return smart pointers
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived1_CBase1().cbase1y()!=3, "MakeSharedPtrDerived1_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived1_CBase2().cbase2()!=4, "MakeSharedPtrDerived1_CBase2 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived2_CBase1().cbase1y()!=6, "MakeSharedPtrDerived2_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived2_ABase1().abase1()!=5, "MakeSharedPtrDerived2_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived3_ABase1().abase1()!=9, "MakeSharedPtrDerived3_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived3_CBase1().cbase1y()!=7, "MakeSharedPtrDerived3_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrDerived3_CBase2().cbase2()!=8, "MakeSharedPtrDerived3_CBase2 failed");
// Return smart pointers
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived1_CBase1().cbase1y()!=3, "MakeSharedPtrRefDerived1_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived1_CBase2().cbase2()!=4, "MakeSharedPtrRefDerived1_CBase2 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived2_CBase1().cbase1y()!=6, "MakeSharedPtrRefDerived2_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived2_ABase1().abase1()!=5, "MakeSharedPtrRefDerived2_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived3_ABase1().abase1()!=9, "MakeSharedPtrRefDerived3_ABase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived3_CBase1().cbase1y()!=7, "MakeSharedPtrRefDerived3_CBase1 failed");
check(multiple_inheritance_shared_ptr.MakeSharedPtrRefDerived3_CBase2().cbase2()!=8, "MakeSharedPtrRefDerived3_CBase2 failed");
}
}
using System;
using nested_classNamespace;
#pragma warning disable 219
public class runme {
static void Main() {
Outer outer = new Outer();
outer.a = 1;
outer.b = 2;
Outer.InnerStruct1 is1 = outer.makeInnerStruct1();
Outer.InnerClass1 ic1 = outer.makeInnerClass1();
Outer.InnerUnion1 iu1 = outer.makeInnerUnion1();
Outer.InnerStruct2 is2 = outer.makeInnerStruct2();
Outer.InnerClass2 ic2 = outer.makeInnerClass2();
Outer.InnerUnion2 iu2 = outer.makeInnerUnion2();
Outer.InnerClass4Typedef ic4 = outer.makeInnerClass4Typedef();
Outer.InnerStruct4Typedef is4 = outer.makeInnerStruct4Typedef();
Outer.InnerUnion4Typedef iu4 = outer.makeInnerUnion4Typedef();
Outer.InnerClass5Typedef ic5 = outer.makeInnerClass5();
Outer.InnerStruct5Typedef is5 = outer.makeInnerStruct5();
Outer.InnerUnion5Typedef iu5 = outer.makeInnerUnion5();
ic5 = outer.makeInnerClass5Typedef();
is5 = outer.makeInnerStruct5Typedef();
iu5 = outer.makeInnerUnion5Typedef();
{
Outer.InnerMultiple im1 = outer.MultipleInstance1;
Outer.InnerMultiple im2 = outer.MultipleInstance2;
Outer.InnerMultiple im3 = outer.MultipleInstance3;
Outer.InnerMultiple im4 = outer.MultipleInstance4;
}
{
Outer.InnerMultipleDerived im1 = outer.MultipleDerivedInstance1;
Outer.InnerMultipleDerived im2 = outer.MultipleDerivedInstance2;
Outer.InnerMultipleDerived im3 = outer.MultipleDerivedInstance3;
Outer.InnerMultipleDerived im4 = outer.MultipleDerivedInstance4;
}
{
Outer.InnerMultipleDerived im1 = outer.MultipleDerivedInstance1;
Outer.InnerMultipleDerived im2 = outer.MultipleDerivedInstance2;
Outer.InnerMultipleDerived im3 = outer.MultipleDerivedInstance3;
Outer.InnerMultipleDerived im4 = outer.MultipleDerivedInstance4;
}
{
Outer.InnerMultipleAnonTypedef1 mat1 = outer.makeInnerMultipleAnonTypedef1();
Outer.InnerMultipleAnonTypedef1 mat2 = outer.makeInnerMultipleAnonTypedef2();
SWIGTYPE_p_p_Outer__InnerMultipleAnonTypedef1 mat3 = outer.makeInnerMultipleAnonTypedef3();
Outer.InnerMultipleNamedTypedef1 mnt = outer.makeInnerMultipleNamedTypedef();
Outer.InnerMultipleNamedTypedef1 mnt1 = outer.makeInnerMultipleNamedTypedef1();
Outer.InnerMultipleNamedTypedef1 mnt2 = outer.makeInnerMultipleNamedTypedef2();
SWIGTYPE_p_p_Outer__InnerMultipleNamedTypedef mnt3 = outer.makeInnerMultipleNamedTypedef3();
}
{
Outer.InnerSameName isn = outer.makeInnerSameName();
}
}
}
using System;
using nested_directorsNamespace;
#pragma warning disable 219
public class CNested : Base.Nest {
public override bool GetValue() {return true;}
}
public class CSub : Sub {
protected override bool GetValue() { return base.GetValue(); }
public bool Test(){ return GetValue(); }
}
public class runme {
static void Main() {
CNested n = new CNested();
CSub s = new CSub();
if (!s.Test())
throw new Exception("Sub.GetValue");
}
}
using System;
using System.Collections.Generic;
using nested_inheritance_interfaceNamespace;
public class nested_inheritance_interface_runme {
static string SortArrayToString(string[] types) {
Array.Sort<string>(types);
return string.Join(" ", types);
}
static string SortArrayToString(Type[] types) {
List<string> stypes = new List<string>();
foreach (Type t in types)
stypes.Add(t.Name);
return SortArrayToString(stypes.ToArray());
}
private static void takeIA(IASwigInterface ia) {
}
public static void Main() {
Type[] BNInterfaces = typeof(B.N).GetInterfaces();
string expectedInterfacesString = "IASwigInterface IDisposable";
string actualInterfacesString = SortArrayToString(BNInterfaces);
if (expectedInterfacesString != actualInterfacesString)
throw new Exception("Expected interfaces for " + typeof(B.N).Name + ": \n" + expectedInterfacesString + "\n" + "Actual interfaces: \n" + actualInterfacesString);
if (!typeof(IASwigInterface).IsInterface)
throw new Exception(typeof(IASwigInterface).Name + " should be an interface but is not");
// overloaded methods check
B.N d = new B.N();
takeIA(d);
}
}
using System;
using nested_in_templateNamespace;
public class runme {
static void Main() {
var cd = new OuterTemplate1.ConcreteDerived(88);
if (cd.m_value != 88)
throw new Exception("ConcreteDerived not created correctly");
}
}
using System;
using nested_structsNamespace;
#pragma warning disable 219
public class runme {
static void Main() {
Outer outer = new Outer();
nested_structs.setValues(outer, 10);
Outer_inner1 inner1 = outer.inner1;
Outer_inner1 inner2 = outer.inner2;
Outer_inner1 inner3 = outer.inner3;
Outer_inner1 inner4 = outer.inner4;
if (inner1.val != 10) throw new Exception("failed inner1");
if (inner2.val != 20) throw new Exception("failed inner2");
if (inner3.val != 20) throw new Exception("failed inner3");
if (inner4.val != 40) throw new Exception("failed inner4");
Named inside1 = outer.inside1;
Named inside2 = outer.inside2;
Named inside3 = outer.inside3;
Named inside4 = outer.inside4;
if (inside1.val != 100) throw new Exception("failed inside1");
if (inside2.val != 200) throw new Exception("failed inside2");
if (inside3.val != 200) throw new Exception("failed inside3");
if (inside4.val != 400) throw new Exception("failed inside4");
}
}
using System;
using nested_workaroundNamespace;
#pragma warning disable 219
public class runme {
static void Main() {
{
Inner inner = new Inner(5);
Outer outer = new Outer();
Inner newInner = outer.doubleInnerValue(inner);
if (newInner.getValue() != 10)
throw new Exception("inner failed");
}
{
Outer outer = new Outer();
Inner inner = outer.createInner(3);
Inner newInner = outer.doubleInnerValue(inner);
if (outer.getInnerValue(newInner) != 6)
throw new Exception("inner failed");
}
}
}
using System;
public class runme
{
static void Main()
{
{
// constructors and destructors
nspace_extendNamespace.Outer.Inner1.Color color1 = new nspace_extendNamespace.Outer.Inner1.Color();
nspace_extendNamespace.Outer.Inner1.Color color = new nspace_extendNamespace.Outer.Inner1.Color(color1);
color1.Dispose();
color1 = null;
// class methods
color.colorInstanceMethod(20.0);
nspace_extendNamespace.Outer.Inner1.Color.colorStaticMethod(20.0);
nspace_extendNamespace.Outer.Inner1.Color created = nspace_extendNamespace.Outer.Inner1.Color.create();
created.Dispose();
}
{
// constructors and destructors
nspace_extendNamespace.Outer.Inner2.Color color2 = new nspace_extendNamespace.Outer.Inner2.Color();
nspace_extendNamespace.Outer.Inner2.Color color = new nspace_extendNamespace.Outer.Inner2.Color(color2);
color2.Dispose();
color2 = null;
// class methods
color.colorInstanceMethod(20.0);
nspace_extendNamespace.Outer.Inner2.Color.colorStaticMethod(20.0);
nspace_extendNamespace.Outer.Inner2.Color created = nspace_extendNamespace.Outer.Inner2.Color.create();
created.Dispose();
// Same class different namespaces
nspace_extendNamespace.Outer.Inner1.Color col1 = new nspace_extendNamespace.Outer.Inner1.Color();
nspace_extendNamespace.Outer.Inner2.Color col2 = nspace_extendNamespace.Outer.Inner2.Color.create();
col2.colors(col1, col1, col2, col2, col2);
}
}
}
using System;
public class runme
{
static void Main()
{
// constructors and destructors
nspaceNamespace.Outer.Inner1.Color color1 = new nspaceNamespace.Outer.Inner1.Color();
nspaceNamespace.Outer.Inner1.Color color = new nspaceNamespace.Outer.Inner1.Color(color1);
color1.Dispose();
color1 = null;
// class methods
color.colorInstanceMethod(20.0);
nspaceNamespace.Outer.Inner1.Color.colorStaticMethod(20.0);
nspaceNamespace.Outer.Inner1.Color created = nspaceNamespace.Outer.Inner1.Color.create();
created.Dispose();
// class enums
nspaceNamespace.Outer.SomeClass someClass = new nspaceNamespace.Outer.SomeClass();
nspaceNamespace.Outer.Inner1.Color.Channel channel = someClass.GetInner1ColorChannel();
if (channel != nspaceNamespace.Outer.Inner1.Color.Channel.Transmission)
throw new ApplicationException("Transmission wrong");
// class anonymous enums
int val1 = nspaceNamespace.Outer.Inner1.Color.ColorEnumVal1;
int val2 = nspaceNamespace.Outer.Inner1.Color.ColorEnumVal2;
if (val1 != 0 || val2 != 0x22)
throw new ApplicationException("ColorEnumVal wrong");
// instance member variables
color.instanceMemberVariable = 123;
if (color.instanceMemberVariable != 123)
throw new ApplicationException("instance member variable failed");
// static member variables
nspaceNamespace.Outer.Inner1.Color.staticMemberVariable = 789;
if (nspaceNamespace.Outer.Inner1.Color.staticMemberVariable != 789)
throw new ApplicationException("static member variable failed");
if (nspaceNamespace.Outer.Inner1.Color.staticConstMemberVariable != 222)
throw new ApplicationException("static const member variable failed");
if (nspaceNamespace.Outer.Inner1.Color.staticConstEnumMemberVariable != nspaceNamespace.Outer.Inner1.Color.Channel.Transmission)
throw new ApplicationException("static const enum member variable failed");
// check globals in a namespace don't get mangled with the nspaceNamespace option
nspaceNamespace.nspace.namespaceFunction(color);
nspaceNamespace.nspace.namespaceVar = 111;
if (nspaceNamespace.nspace.namespaceVar != 111)
throw new ApplicationException("global var failed");
// Same class different namespaces
nspaceNamespace.Outer.Inner1.Color col1 = new nspaceNamespace.Outer.Inner1.Color();
nspaceNamespace.Outer.Inner2.Color col2 = nspaceNamespace.Outer.Inner2.Color.create();
col2.colors(col1, col1, col2, col2, col2);
// global enums
nspaceNamespace.Outer.Inner1.Channel outerChannel1 = someClass.GetInner1Channel();
if (outerChannel1 != nspaceNamespace.Outer.Inner1.Channel.Transmission1)
throw new ApplicationException("Transmission1 wrong");
nspaceNamespace.Outer.Inner2.Channel outerChannel2 = someClass.GetInner2Channel();
if (outerChannel2 != nspaceNamespace.Outer.Inner2.Channel.Transmission2)
throw new ApplicationException("Transmission2 wrong");
// turn feature off / ignoring
nspaceNamespace.Outer.namespce ns = new nspaceNamespace.Outer.namespce();
ns.Dispose();
nspaceNamespace.NoNSpacePlease nons = new nspaceNamespace.NoNSpacePlease();
nons.Dispose();
// Derived class
nspaceNamespace.Outer.Inner3.Blue blue3 = new nspaceNamespace.Outer.Inner3.Blue();
blue3.blueInstanceMethod();
nspaceNamespace.Outer.Inner4.Blue blue4 = new nspaceNamespace.Outer.Inner4.Blue();
blue4.blueInstanceMethod();
}
}
using System;
using System.Threading;
using operator_overloadNamespace;
public class runme
{
static void Main()
{
Op.sanity_check();
{
Op op = new Op(100);
Op opNew = op++;
if (op.i != 101) throw new Exception("operator++ postfix failed (op)");
if (opNew.i != 100) throw new Exception("operator++ postfix failed (opNew)");
}
{
Op op = new Op(100);
Op opNew = op--;
if (op.i != 99) throw new Exception("operator-- postfix failed (op)");
if (opNew.i != 100) throw new Exception("operator-- postfix failed (opNew)");
}
{
Op op = new Op(100);
Op opNew = ++op;
if (op.i != 101) throw new Exception("operator++ prefix failed (op)");
if (opNew.i != 101) throw new Exception("operator++ prefix failed (opNew)");
}
{
Op op = new Op(100);
Op opNew = --op;
if (op.i != 99) throw new Exception("operator-- prefix failed (op)");
if (opNew.i != 99) throw new Exception("operator-- prefix failed (opNew)");
}
// overloaded operator class
Op k = new OpDerived(3);
int check_k = k.IntCast();
Assert(check_k == 6);
}
public static void Assert(bool b) {
if (!b)
throw new Exception("Assertion failed");
}
}
using System;
using overload_complicatedNamespace;
public class runme
{
static void Main()
{
SWIGTYPE_p_int pInt = null;
// Check the correct constructors are available
Pop p = new Pop(pInt);
p = new Pop(pInt, false);
// Check overloaded in const only and pointers/references which target languages cannot disambiguate
if (p.hip(false) != 701)
throw new Exception("Test 1 failed");
if (p.hip(pInt) != 702)
throw new Exception("Test 2 failed");
// Reverse the order for the above
if (p.hop(pInt) != 805)
throw new Exception("Test 3 failed");
if (p.hop(false) != 801)
throw new Exception("Test 4 failed");
// Few more variations and order shuffled
if (p.pop(false) != 901)
throw new Exception("Test 5 failed");
if (p.pop(pInt) != 902)
throw new Exception("Test 6 failed");
if (p.pop() != 905)
throw new Exception("Test 7 failed");
// Overload on const only
if (p.bop(pInt) != 1001)
throw new Exception("Test 8 failed");
if (p.bip(pInt) != 2001)
throw new Exception("Test 9 failed");
// Globals
if (overload_complicated.muzak(false) != 3001)
throw new Exception("Test 10 failed");
if (overload_complicated.muzak(pInt) != 3002)
throw new Exception("Test 11 failed");
}
}
using System;
using overload_templateNamespace;
public class runme
{
static void Main()
{
int f = overload_template.foo();
f += overload_template.maximum(3,4);
double b = overload_template.maximum(3.4,5.2);
b++; // warning suppression
// mix 1
if (overload_template.mix1("hi") != 101)
throw new Exception ("mix1(const char*)");
if (overload_template.mix1(1.0, 1.0) != 102)
throw new Exception ("mix1(double, const double &)");
if (overload_template.mix1(1.0) != 103)
throw new Exception ("mix1(double)");
// mix 2
if (overload_template.mix2("hi") != 101)
throw new Exception ("mix2(const char*)");
if (overload_template.mix2(1.0, 1.0) != 102)
throw new Exception ("mix2(double, const double &)");
if (overload_template.mix2(1.0) != 103)
throw new Exception ("mix2(double)");
// mix 3
if (overload_template.mix3("hi") != 101)
throw new Exception ("mix3(const char*)");
if (overload_template.mix3(1.0, 1.0) != 102)
throw new Exception ("mix3(double, const double &)");
if (overload_template.mix3(1.0) != 103)
throw new Exception ("mix3(double)");
// Combination 1
if (overload_template.overtparams1(100) != 10)
throw new Exception ("overtparams1(int)");
if (overload_template.overtparams1(100.0, 100) != 20)
throw new Exception ("overtparams1(double, int)");
// Combination 2
if (overload_template.overtparams2(100.0, 100) != 40)
throw new Exception ("overtparams2(double, int)");
// Combination 3
if (overload_template.overloaded() != 60)
throw new Exception ("overloaded()");
if (overload_template.overloaded(100.0, 100) != 70)
throw new Exception ("overloaded(double, int)");
// Combination 4
if (overload_template.overloadedagain("hello") != 80)
throw new Exception ("overloadedagain(const char *)");
if (overload_template.overloadedagain() != 90)
throw new Exception ("overloadedagain(double)");
// specializations
if (overload_template.specialization(10) != 202)
throw new Exception ("specialization(int)");
if (overload_template.specialization(10.0) != 203)
throw new Exception ("specialization(double)");
if (overload_template.specialization(10, 10) != 204)
throw new Exception ("specialization(int, int)");
if (overload_template.specialization(10.0, 10.0) != 205)
throw new Exception ("specialization(double, double)");
if (overload_template.specialization("hi", "hi") != 201)
throw new Exception ("specialization(const char *, const char *)");
// simple specialization
overload_template.xyz();
overload_template.xyz_int();
overload_template.xyz_double();
// a bit of everything
if (overload_template.overload("hi") != 0)
throw new Exception ("overload()");
if (overload_template.overload(1) != 10)
throw new Exception ("overload(int t)");
if (overload_template.overload(1, 1) != 20)
throw new Exception ("overload(int t, const int &)");
if (overload_template.overload(1, "hello") != 30)
throw new Exception ("overload(int t, const char *)");
Klass k = new Klass();
if (overload_template.overload(k) != 10)
throw new Exception ("overload(Klass t)");
if (overload_template.overload(k, k) != 20)
throw new Exception ("overload(Klass t, const Klass &)");
if (overload_template.overload(k, "hello") != 30)
throw new Exception ("overload(Klass t, const char *)");
if (overload_template.overload(10.0, "hi") != 40)
throw new Exception ("overload(double t, const char *)");
if (overload_template.overload() != 50)
throw new Exception ("overload(const char *)");
// everything put in a namespace
if (overload_template.nsoverload("hi") != 1000)
throw new Exception ("nsoverload()");
if (overload_template.nsoverload(1) != 1010)
throw new Exception ("nsoverload(int t)");
if (overload_template.nsoverload(1, 1) != 1020)
throw new Exception ("nsoverload(int t, const int &)");
if (overload_template.nsoverload(1, "hello") != 1030)
throw new Exception ("nsoverload(int t, const char *)");
if (overload_template.nsoverload(k) != 1010)
throw new Exception ("nsoverload(Klass t)");
if (overload_template.nsoverload(k, k) != 1020)
throw new Exception ("nsoverload(Klass t, const Klass &)");
if (overload_template.nsoverload(k, "hello") != 1030)
throw new Exception ("nsoverload(Klass t, const char *)");
if (overload_template.nsoverload(10.0, "hi") != 1040)
throw new Exception ("nsoverload(double t, const char *)");
if (overload_template.nsoverload() != 1050)
throw new Exception ("nsoverload(const char *)");
}
}
// This test tests all the methods in the C# collection wrapper
using System;
using pointer_referenceNamespace;
public class pointer_reference_runme {
public static void Main() {
Struct s = pointer_reference.get();
if (s.value != 10) throw new Exception("get test failed");
Struct ss = new Struct(20);
pointer_reference.set(ss);
if (Struct.instance.value != 20) throw new Exception("set test failed");
if (pointer_reference.overloading(1) != 111) throw new Exception("overload test 1 failed");
if (pointer_reference.overloading(ss) != 222) throw new Exception("overload test 2 failed");
}
}
using System;
using System.Reflection;
using preproc_constants_cNamespace;
// Same as preproc_constants_c.i testcase, but bool types are int instead
public class runme {
static void Main() {
assert( typeof(int) == preproc_constants_c.CONST_INT1.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_INT2.GetType() );
assert( typeof(uint) == preproc_constants_c.CONST_UINT1.GetType() );
assert( typeof(uint) == preproc_constants_c.CONST_UINT2.GetType() );
assert( typeof(uint) == preproc_constants_c.CONST_UINT3.GetType() );
assert( typeof(uint) == preproc_constants_c.CONST_UINT4.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_LONG1.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_LONG2.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_LONG3.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_LONG4.GetType() );
assert( typeof(long) == preproc_constants_c.CONST_LLONG1.GetType() );
assert( typeof(long) == preproc_constants_c.CONST_LLONG2.GetType() );
assert( typeof(long) == preproc_constants_c.CONST_LLONG3.GetType() );
assert( typeof(long) == preproc_constants_c.CONST_LLONG4.GetType() );
assert( typeof(ulong) == preproc_constants_c.CONST_ULLONG1.GetType() );
assert( typeof(ulong) == preproc_constants_c.CONST_ULLONG2.GetType() );
assert( typeof(ulong) == preproc_constants_c.CONST_ULLONG3.GetType() );
assert( typeof(ulong) == preproc_constants_c.CONST_ULLONG4.GetType() );
assert( typeof(double) == preproc_constants_c.CONST_DOUBLE1.GetType() );
assert( typeof(double) == preproc_constants_c.CONST_DOUBLE2.GetType() );
assert( typeof(double) == preproc_constants_c.CONST_DOUBLE3.GetType() );
assert( typeof(double) == preproc_constants_c.CONST_DOUBLE4.GetType() );
assert( typeof(double) == preproc_constants_c.CONST_DOUBLE5.GetType() );
assert( typeof(double) == preproc_constants_c.CONST_DOUBLE6.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_BOOL1.GetType() );
assert( typeof(int) == preproc_constants_c.CONST_BOOL2.GetType() );
assert( typeof(char) == preproc_constants_c.CONST_CHAR.GetType() );
assert( typeof(string) == preproc_constants_c.CONST_STRING1.GetType() );
assert( typeof(string) == preproc_constants_c.CONST_STRING2.GetType() );
assert( typeof(int) == preproc_constants_c.INT_AND_BOOL.GetType() );
assert( typeof(int) == preproc_constants_c.INT_AND_CHAR.GetType() );
assert( typeof(int) == preproc_constants_c.INT_AND_INT.GetType() );
assert( typeof(uint) == preproc_constants_c.INT_AND_UINT.GetType() );
assert( typeof(int) == preproc_constants_c.INT_AND_LONG.GetType() );
assert( typeof(uint) == preproc_constants_c.INT_AND_ULONG.GetType() );
assert( typeof(long) == preproc_constants_c.INT_AND_LLONG.GetType() );
assert( typeof(ulong) == preproc_constants_c.INT_AND_ULLONG.GetType() );
assert( typeof(int ) == preproc_constants_c.BOOL_AND_BOOL.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_MULTIPLY.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_DIVIDE.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_PLUS.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_MINUS.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_LSHIFT.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_RSHIFT.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_LTE.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_GTE.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_INEQUALITY.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_EQUALITY.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_AND.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_XOR.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_OR.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_LAND.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_LOR.GetType() );
assert( typeof(double) == preproc_constants_c.EXPR_CONDITIONAL.GetType() );
assert( typeof(double) == preproc_constants_c.EXPR_MIXED1.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_WCHAR_MAX.GetType() );
assert( typeof(int) == preproc_constants_c.EXPR_WCHAR_MIN.GetType() );
}
static void assert(bool assertion) {
if (!assertion)
throw new ApplicationException("test failed");
}
}
using System;
using System.Reflection;
using preproc_constantsNamespace;
public class runme {
static void Main() {
assert( typeof(int) == preproc_constants.CONST_INT1.GetType() );
assert( typeof(int) == preproc_constants.CONST_INT2.GetType() );
assert( typeof(uint) == preproc_constants.CONST_UINT1.GetType() );
assert( typeof(uint) == preproc_constants.CONST_UINT2.GetType() );
assert( typeof(uint) == preproc_constants.CONST_UINT3.GetType() );
assert( typeof(uint) == preproc_constants.CONST_UINT4.GetType() );
assert( typeof(int) == preproc_constants.CONST_LONG1.GetType() );
assert( typeof(int) == preproc_constants.CONST_LONG2.GetType() );
assert( typeof(int) == preproc_constants.CONST_LONG3.GetType() );
assert( typeof(int) == preproc_constants.CONST_LONG4.GetType() );
assert( typeof(long) == preproc_constants.CONST_LLONG1.GetType() );
assert( typeof(long) == preproc_constants.CONST_LLONG2.GetType() );
assert( typeof(long) == preproc_constants.CONST_LLONG3.GetType() );
assert( typeof(long) == preproc_constants.CONST_LLONG4.GetType() );
assert( typeof(ulong) == preproc_constants.CONST_ULLONG1.GetType() );
assert( typeof(ulong) == preproc_constants.CONST_ULLONG2.GetType() );
assert( typeof(ulong) == preproc_constants.CONST_ULLONG3.GetType() );
assert( typeof(ulong) == preproc_constants.CONST_ULLONG4.GetType() );
assert( typeof(double) == preproc_constants.CONST_DOUBLE1.GetType() );
assert( typeof(double) == preproc_constants.CONST_DOUBLE2.GetType() );
assert( typeof(double) == preproc_constants.CONST_DOUBLE3.GetType() );
assert( typeof(double) == preproc_constants.CONST_DOUBLE4.GetType() );
assert( typeof(double) == preproc_constants.CONST_DOUBLE5.GetType() );
assert( typeof(double) == preproc_constants.CONST_DOUBLE6.GetType() );
assert( typeof(bool) == preproc_constants.CONST_BOOL1.GetType() );
assert( typeof(bool) == preproc_constants.CONST_BOOL2.GetType() );
assert( typeof(char) == preproc_constants.CONST_CHAR.GetType() );
assert( typeof(string) == preproc_constants.CONST_STRING1.GetType() );
assert( typeof(string) == preproc_constants.CONST_STRING2.GetType() );
assert( typeof(int) == preproc_constants.INT_AND_BOOL.GetType() );
assert( typeof(int) == preproc_constants.INT_AND_CHAR.GetType() );
assert( typeof(int) == preproc_constants.INT_AND_INT.GetType() );
assert( typeof(uint) == preproc_constants.INT_AND_UINT.GetType() );
assert( typeof(int) == preproc_constants.INT_AND_LONG.GetType() );
assert( typeof(uint) == preproc_constants.INT_AND_ULONG.GetType() );
assert( typeof(long) == preproc_constants.INT_AND_LLONG.GetType() );
assert( typeof(ulong) == preproc_constants.INT_AND_ULLONG.GetType() );
assert( typeof(int ) == preproc_constants.BOOL_AND_BOOL.GetType() );
assert( typeof(int) == preproc_constants.EXPR_MULTIPLY.GetType() );
assert( typeof(int) == preproc_constants.EXPR_DIVIDE.GetType() );
assert( typeof(int) == preproc_constants.EXPR_PLUS.GetType() );
assert( typeof(int) == preproc_constants.EXPR_MINUS.GetType() );
assert( typeof(int) == preproc_constants.EXPR_LSHIFT.GetType() );
assert( typeof(int) == preproc_constants.EXPR_RSHIFT.GetType() );
assert( typeof(bool) == preproc_constants.EXPR_LTE.GetType() );
assert( typeof(bool) == preproc_constants.EXPR_GTE.GetType() );
assert( typeof(bool) == preproc_constants.EXPR_INEQUALITY.GetType() );
assert( typeof(bool) == preproc_constants.EXPR_EQUALITY.GetType() );
assert( typeof(int) == preproc_constants.EXPR_AND.GetType() );
assert( typeof(int) == preproc_constants.EXPR_XOR.GetType() );
assert( typeof(int) == preproc_constants.EXPR_OR.GetType() );
assert( typeof(bool) == preproc_constants.EXPR_LAND.GetType() );
assert( typeof(bool) == preproc_constants.EXPR_LOR.GetType() );
assert( typeof(double) == preproc_constants.EXPR_CONDITIONAL.GetType() );
assert( typeof(double) == preproc_constants.EXPR_MIXED1.GetType() );
assert( typeof(int) == preproc_constants.EXPR_WCHAR_MAX.GetType() );
assert( typeof(int) == preproc_constants.EXPR_WCHAR_MIN.GetType() );
}
static void assert(bool assertion) {
if (!assertion)
throw new ApplicationException("test failed");
}
}
using System;
using proxycodeNamespace;
public class proxycode_runme {
public static void Main() {
if (new Proxy1().proxycode1(100) != 101)
throw new Exception("Fail");
if (new Proxy2().proxycode2a(100) != 102)
throw new Exception("Fail");
if (new Proxy2().proxycode2b(100) != 102)
throw new Exception("Fail");
if (new Proxy3().proxycode3(100) != 103)
throw new Exception("Fail");
if (new Proxy4().proxycode4(100) != 104)
throw new Exception("Fail");
if (new Proxy4.Proxy4Nested().proxycode4nested(100) != 144)
throw new Exception("Fail");
if (new Proxy5a().proxycode5((short)100) != (short)100)
throw new Exception("Fail");
if (new Proxy5b().proxycode5(100) != 100)
throw new Exception("Fail");
if (new Proxy5b().proxycode5(100, 100) != 255)
throw new Exception("Fail");
uint t1 = 10;
uint t2 = 100;
Proxy6 p = new Proxy6().proxyUseT(t1, t2);
p.useT(t1, t2);
}
}
using System;
using rename_pcre_encoderNamespace;
public class runme {
static void Main() {
SomeWidget w = new SomeWidget();
w.put_borderWidth(17);
if ( w.get_borderWidth() != 17 )
throw new Exception(String.Format("Border with should be 17, not {0}",
w.get_borderWidth()));
if ( rename_pcre_encoder.StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42 )
throw new Exception("Unexpected result of renamed function call");
}
}
using System;
using rename_pcre_enumNamespace;
public class runme {
static void Main() {
Foo foo = Foo.First;
if ( foo == Foo.Second )
throw new Exception("Enum values should be different");
// Check that Foo_Max enum element was ignored.
int numFooEnumElements = Enum.GetValues(typeof(Foo)).Length;
if ( numFooEnumElements != 2 )
throw new Exception(String.Format("Enum should have 2 elements, not {0}",
numFooEnumElements));
BoundaryCondition bc = BoundaryCondition.MaxMax;
if ( (int)bc != 2 )
throw new Exception("Wrong enum value");
Colour c = Colour.red;
if ( c == Colour.blue )
throw new Exception("Enum values should be different");
}
}
using System;
using rename_simpleNamespace;
public class rename_simple_runme {
public static void Main() {
NewStruct s = new NewStruct();
check(111, s.NewInstanceVariable, "NewInstanceVariable");
check(222, s.NewInstanceMethod(), "NewInstanceMethod");
check(333, NewStruct.NewStaticMethod(), "NewStaticMethod");
check(444, NewStruct.NewStaticVariable, "NewStaticVariable");
check(555, rename_simple.NewFunction(), "NewFunction");
check(666, rename_simple.NewGlobalVariable, "NewGlobalVariable");
s.NewInstanceVariable = 1111;
NewStruct.NewStaticVariable = 4444;
rename_simple.NewGlobalVariable = 6666;
check(1111, s.NewInstanceVariable, "NewInstanceVariable");
check(4444, NewStruct.NewStaticVariable, "NewStaticVariable");
check(6666, rename_simple.NewGlobalVariable, "NewGlobalVariable");
}
public static void check(int expected, int actual, string msg) {
if (expected != actual)
throw new Exception("Failed: Expected: " + expected + " actual: " + actual + " " + msg);
}
}
using System;
using sizetNamespace;
public class sizet_runme {
public static void Main() {
uint s = 2000;
s = sizet.test1(s+1);
s = sizet.test2(s+1);
s = sizet.test3(s+1);
s = sizet.test4(s+1);
if (s != 2004)
throw new Exception("failed");
}
}
using System;
using sneaky1Namespace;
public class runme
{
static void Main()
{
if (sneaky1.add(30, 2) != 32)
throw new Exception("add test failed");
if (sneaky1.subtract(20, 2) != 18)
throw new Exception("subtract test failed");
if (sneaky1.mul(20, 2) != 40)
throw new Exception("mul test failed");
if (sneaky1.divide(20, 2) != 10)
throw new Exception("div test failed");
}
}
using System;
using special_variable_attributesNamespace;
public class special_variable_attributes_runme {
public static void Main() {
if (special_variable_attributes.getNumber1() != 111)
throw new ApplicationException("getNumber1 failed");
if (special_variable_attributes.getNumber2() != 222)
throw new ApplicationException("getNumber2 failed");
if (special_variable_attributes.getNumber3() != 333)
throw new ApplicationException("getNumber3 failed");
if (special_variable_attributes.bounceNumber1(10) != 110)
throw new ApplicationException("bounceNumber1 failed");
if (special_variable_attributes.bounceNumber2(10) != 220)
throw new ApplicationException("bounceNumber2 failed");
if (special_variable_attributes.bounceNumber3(10) != 330)
throw new ApplicationException("bounceNumber3 failed");
if (special_variable_attributes.multi1(12.34) != 12+34)
throw new ApplicationException("multi1 failed");
if (special_variable_attributes.multi2(12.34) != 12+34+55)
throw new ApplicationException("multi2 failed");
if (special_variable_attributes.multi3(12.34) != 12+34+77)
throw new ApplicationException("multi3 failed");
}
}
using System;
using special_variable_macrosNamespace;
public class runme {
static void Main() {
Name name = new Name();
if (special_variable_macros.testFred(name) != "none")
throw new Exception("test failed");
if (special_variable_macros.testJack(name) != "$specialname")
throw new Exception("test failed");
if (special_variable_macros.testJill(name) != "jilly")
throw new Exception("test failed");
if (special_variable_macros.testMary(name) != "SWIGTYPE_p_NameWrap")
throw new Exception("test failed");
if (special_variable_macros.testJames(name) != "SWIGTYPE_Name")
throw new Exception("test failed");
if (special_variable_macros.testJim(name) != "multiname num")
throw new Exception("test failed");
if (special_variable_macros.testJohn(new PairIntBool(10, false)) != 123)
throw new Exception("test failed");
NewName newName = NewName.factory("factoryname");
name = newName.getStoredName();
}
}
using System;
using template_nestedNamespace;
#pragma warning disable 219
public class runme {
static void Main() {
new T_NormalTemplateNormalClass().tmethod(new NormalClass());
new OuterClass().T_OuterTMethodNormalClass(new NormalClass());
TemplateFuncs tf = new TemplateFuncs();
if (tf.T_TemplateFuncs1Int(-10) != -10)
throw new Exception("it failed");
if (tf.T_TemplateFuncs2Double(-12.3) != -12.3)
throw new Exception("it failed");
T_NestedOuterTemplateDouble tn = new T_NestedOuterTemplateDouble();
if (tn.hohum(-12.3) != -12.3)
throw new Exception("it failed");
OuterClass.T_OuterClassInner1Int inner1 = new OuterClass().useInner1(new OuterClass.T_OuterClassInner1Int());
OuterClass.T_OuterClassInner2NormalClass inner2 = new OuterClass.T_OuterClassInner2NormalClass();
inner2.embeddedVar = 2;
OuterClass.T_OuterClassInner2NormalClass inner22 = new OuterClass().useInner2Again(inner2);
}
}
using System;
using System.Threading;
using threadsNamespace;
public class runme
{
static void Main()
{
Kerfuffle kerf = new Kerfuffle();
const int NUM_THREADS = 8;
Thread[] threads = new Thread[NUM_THREADS];
TestThread[] testThreads = new TestThread[NUM_THREADS];
// invoke the threads
for (int i=0; i<NUM_THREADS; i++) {
testThreads[i] = new TestThread(kerf, i);
threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
threads[i].Start();
}
// wait for the threads to finish
for (int i=0; i<NUM_THREADS; i++) {
threads[i].Join();
}
for (int i=0; i<NUM_THREADS; i++) {
if (testThreads[i].Failed) throw new Exception("Test Failed");
}
}
}
public class TestThread {
private int threadId;
private Kerfuffle kerf;
public bool Failed;
public TestThread(Kerfuffle t, int id) {
kerf = t;
threadId = id;
}
public void Run() {
Failed = false;
try {
for (int i=0; i<30000; i++) { // run test for a few seconds on a 1GHz machine
string given = "This is the test string that should come back. A number: " + i;
string received = kerf.StdString(given);
if (received != given) {
throw new ApplicationException("StdString string does not match. Received:\n[" + received + "].\nExpected:\n{" + given + "}");
}
}
for (int i=0; i<30000; i++) { // run test for a few seconds on a 1GHz machine
string given = "This is the test string that should come back. A number: " + i;
string received = kerf.CharString(given);
if (received != given) {
throw new ApplicationException("StdString string does not match. Received:\n[" + received + "].\nExpected:\n{" + given + "}");
}
}
} catch (Exception e) {
Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message);
Failed = true;
}
}
}
using System;
using throw_exceptionNamespace;
public class runme
{
static void Main() {
Foo f = new Foo();
try {
f.test_int();
throw new Exception("Integer exception should have been thrown");
} catch (System.Exception) {
}
try {
f.test_msg();
throw new Exception("String exception should have been thrown");
} catch (System.Exception) {
}
try {
f.test_cls();
throw new Exception("Class exception should have been thrown");
} catch (System.Exception) {
}
}
}
// This test tests all the methods in the C# collection wrapper
using System;
using typemap_namespaceNamespace;
public class typemap_namespace_runme {
public static void Main() {
if (typemap_namespace.test1("hello") != "hello")
throw new Exception("test1 failed");
if (typemap_namespace.test2("hello") != "hello")
throw new Exception("test2 failed");
}
}
using System;
using typemap_out_optimalNamespace;
public class typemap_out_optimal_runme {
public static XX x = null;
public static void Main() {
XX.debug = false;
x = XX.create();
}
}
// varargs test
using System;
using varargsNamespace;
public class varargs_runme {
public static void Main() {
if (varargs.test("Hello") != "Hello")
throw new Exception("Failed");
Foo f = new Foo("Greetings");
if (f.str != "Greetings")
throw new Exception("Failed");
if (f.test("Hello") != "Hello")
throw new Exception("Failed");
}
}
using System;
using virtual_polyNamespace;
public class runme {
static void Main() {
NDouble d = new NDouble(3.5);
NInt i = new NInt(2);
//
// These two natural 'copy' forms fail because no covariant (polymorphic) return types
// are supported in C#.
//
// NDouble dc = d.copy();
// NInt ic = i.copy();
//
// Unlike C++, we have to downcast instead.
//
NDouble dc = (NDouble)d.copy();
NInt ic = (NInt)i.copy();
NDouble ddc = NDouble.narrow(dc);
NInt dic = NInt.narrow(ic);
dc = ddc; ic = dic; // warning suppression
virtual_poly.incr(ic);
if ( (i.get() + 1) != ic.get() )
throw new Exception("incr test failed");
//
// Checking a pure user downcast
//
NNumber n1 = d.copy();
NNumber n2 = d.nnumber();
NDouble dn1 = NDouble.narrow(n1);
NDouble dn2 = NDouble.narrow(n2);
if ( (dn1.get()) != dn2.get() )
throw new Exception("copy/narrow test failed");
//
// Checking the ref polymorphic case
//
NNumber nr = d.ref_this();
NDouble dr1 = NDouble.narrow(nr);
NDouble dr2 = (NDouble)d.ref_this();
if ( dr1.get() != dr2.get() )
throw new Exception("copy/narrow test failed");
}
}
var abstract_access = require("abstract_access");
var d = new abstract_access.D()
if (d.do_x() != 1) {
throw "Error";
}
var abstract_inherit = require("abstract_inherit");
// Shouldn't be able to instantiate any of these classes
// since none of them implements the pure virtual function
// declared in the base class (Foo).
var Foo = abstract_inherit.Foo;
var Bar = abstract_inherit.Bar;
var Spam = abstract_inherit.Spam;
var caughtException = false;
try {
new Foo();
} catch (err) {
caughtException = true;
}
if (!caughtException) {
throw new Error("Foo should be instantiated as it is abstract");
}
caughtException = false;
try {
new Bar();
} catch (err) {
caughtException = true;
}
if (!caughtException) {
throw new Error("Bar should be instantiated as it is abstract");
}
caughtException = false;
try {
new Spam();
} catch (err) {
caughtException = true;
}
if (!caughtException) {
throw new Error("Spam should be instantiated as it is abstract");
}
var abstract_typedef2 = require("abstract_typedef2");
var a = new abstract_typedef2.A_UF();
if (a == undefined)
throw "Error";
var abstract_typedef = require("abstract_typedef");
var e = new abstract_typedef.Engine();
var a = new abstract_typedef.A()
if (a.write(e) != 1) {
throw "Error";
}
var abstract_virtual = require("abstract_virtual");
d = new abstract_virtual.D()
if (d == undefined)
throw "Error";
e = new abstract_virtual.E()
if (e == undefined)
throw "Error";
var arrays_global = require("arrays_global");
arrays_global.array_i = arrays_global.array_const_i;
arrays_global.BeginString_FIX44a;
arrays_global.BeginString_FIX44b;
arrays_global.BeginString_FIX44c;
arrays_global.BeginString_FIX44d;
arrays_global.BeginString_FIX44d;
arrays_global.BeginString_FIX44b = "12"+'\0'+"45";
arrays_global.BeginString_FIX44b;
arrays_global.BeginString_FIX44d;
arrays_global.BeginString_FIX44e;
arrays_global.BeginString_FIX44f;
arrays_global.test_a("hello","hi","chello","chi");
arrays_global.test_b("1234567","hi");
var array_member = require("array_member");
var f = new array_member.Foo();
f.data = array_member.global_data;
for (var i=0; i<8; i++) {
if (array_member.get_value(f.data,i) != array_member.get_value(array_member.global_data,i)) {
throw "Bad array assignment (1)";
}
}
for (var i=0; i<8; i++) {
array_member.set_value(f.data,i,-i);
}
array_member.global_data = f.data;
for (var i=0; i<8; i++){
if (array_member.get_value(f.data,i) != array_member.get_value(array_member.global_data,i)) {
throw "Bad array assignment (2)";
}
}
var callback = require("callback");
if (callback.foo(2) !== 2) {
throw new Error("Failed.");
}
if (callback.A_bar(2) !== 4) {
throw new Error("Failed.");
}
if (callback.foobar(3, callback.foo) != callback.foo(3)) {
throw new Error("Failed.");
}
if (callback.foobar(3, foo) != callback.foo(3)) {
throw new Error("Failed.");
}
if (callback.foobar(3, callback.A_bar) != callback.A_bar(3)) {
throw new Error("Failed.");
}
if (callback.foobar(3, callback.foof) != callback.foof(3)) {
throw new Error("Failed.");
}
if (callback.foobar_i(3, callback.foo_i) != callback.foo_i(3)) {
throw new Error("Failed.");
}
if (callback.foobar_d(3.5, callback.foo_d) != callback.foo_d(3.5)) {
throw new Error("Failed.");
}
var a = new callback.A();
if (callback.foobarm(3, a, callback.A.foom_cb_ptr) != a.foom(3)) {
throw new Error("Failed.");
}
var char_binary = require("char_binary");
var t = new char_binary.Test();
if (t.strlen('hile') != 4) {
print(t.strlen('hile'));
throw("bad multi-arg typemap 1");
}
if (t.ustrlen('hile') != 4) {
print(t.ustrlen('hile'));
throw("bad multi-arg typemap 1");
}
if (t.strlen('hil\0') != 4) {
throw("bad multi-arg typemap 2");
}
if (t.ustrlen('hil\0') != 4) {
throw("bad multi-arg typemap 2");
}
/*
* creating a raw char*
*/
var pc = char_binary.new_pchar(5);
char_binary.pchar_setitem(pc, 0, 'h');
char_binary.pchar_setitem(pc, 1, 'o');
char_binary.pchar_setitem(pc, 2, 'l');
char_binary.pchar_setitem(pc, 3, 'a');
char_binary.pchar_setitem(pc, 4, 0);
if (t.strlen(pc) != 4) {
throw("bad multi-arg typemap (3)");
}
if (t.ustrlen(pc) != 4) {
throw("bad multi-arg typemap (3)");
}
char_binary.var_pchar = pc;
if (char_binary.var_pchar != "hola") {
print(char_binary.var_pchar);
throw("bad pointer case (1)");
}
char_binary.var_namet = pc;
if (char_binary.var_namet != "hola") {
throw("bad pointer case (2)");
}
char_binary.delete_pchar(pc);
var char_strings = require("char_strings");
var assertIsEqual = function(expected, actual) {
if (expected !== actual) {
throw new Error("Expected "+expected+", was "+actual);
}
};
assertIsEqual("hi there", char_strings.CharPingPong("hi there"));
assertIsEqual("hi there", char_strings.CharArrayPingPong("hi there"));
assertIsEqual("hi there", char_strings.CharArrayDimsPingPong("hi there"));
var class_ignore = require("class_ignore");
a = new class_ignore.Bar();
if (class_ignore.do_blah(a) != "Bar::blah")
throw "Error";
var class_scope_weird = require("class_scope_weird");
f = new class_scope_weird.Foo();
g = new class_scope_weird.Foo(3);
if (f.bar(3) != 3)
throw RuntimeError;
var complextest = require("complextest");
a = [-1,2];
expected = [-1, -2];
a_c = complextest.Conj(a);
if (a_c.toString() != expected.toString())
throw "Error in Conj(a)";
a_c = complextest.Conjf(a);
if (a_c.toString() != expected.toString())
throw "Error in Conjf(a)";
a_c = complextest.Conj2(a);
if (a_c.toString() != expected.toString())
throw "Error in Conj(a)";
a_c = complextest.Conjf2(a);
if (a_c.toString() != expected.toString())
throw "Error in Conjf(a)";
v = new complextest.VectorStdCplx();
v.add([1,2]);
v.add([2,3]);
v.add([4,3]);
v.add(1);
// TODO: how to check validity?
complextest.CopyHalf(v);
complextest.CopyHalfRef(v);
var constover = require("constover");
p = constover.test("test");
if (p != "test") {
throw "test failed!";
}
p = constover.test_pconst("test");
if (p != "test_pconst") {
throw "test_pconst failed!";
}
f = new constover.Foo();
p = f.test("test");
if (p != "test") {
throw "member-test failed!";
}
p = f.test_pconst("test");
if (p != "test_pconst") {
throw "member-test_pconst failed!";
}
p = f.test_constm("test");
if (p != "test_constmethod") {
throw "member-test_constm failed!";
}
p = f.test_pconstm("test");
if (p != "test_pconstmethod") {
throw "member-test_pconstm failed!";
}
var constructor_copy = require("constructor_copy");
f1 = new constructor_copy.Foo1(3);
f11 = new constructor_copy.Foo1(f1);
if (f1.x != f11.x) {
throw "error in ctor copy for Foo1";
}
var good = 0;
f8 = new constructor_copy.Foo8()
try {
f81 = new constructor_copy.Foo8(f8);
good = 0;
} catch (err) {
good = 1;
}
if (good == 0) {
throw "Error: should not allow calling copy ctor for Foo8";
}
bi = new constructor_copy.Bari(5);
bc = new constructor_copy.Bari(bi);
if (bi.x != bc.x) {
throw "Error in copy ctor of Bari";
}
bd = new constructor_copy.Bard(5);
try {
bc = new constructor_copy.Bard(bd);
good = 0;
} catch (err) {
good = 1;
}
if (good == 0) {
throw "Error: should not allow calling copy ctor for Bard";
}
var cpp11_strongly_typed_enumerations = require("cpp11_strongly_typed_enumerations");
function enumCheck(actual, expected) {
if (actual != expected) {
throw new Error("Enum value mismatch. Expected: " + expected + " Actual: " + actual);
}
return expected + 1;
}
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val3, 13);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val5a, 13);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val6a, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val3, 23);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val5b, 23);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val6b, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Val3, 43);
val = enumCheck(cpp11_strongly_typed_enumerations.Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val3, 53);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val3, 63);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val3, 73);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val3, 83);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val3, 103);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val1, 1121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val2, 1122);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val5c, 1121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val6c, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val1, 1131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val2, 1132);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val5d, 1131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val6d, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val1, 1141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val2, 1142);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val5e, 1141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val6e, val);
// Requires nested class support to work
//val = 0;
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val1, 3121);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val2, 3122);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val3, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val4, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val5f, 3121);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val6f, val);
//
//val = 0;
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val1, 3131);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val2, 3132);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val3, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val4, val);
//
//val = 0;
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val1, 3141);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val2, 3142);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val3, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val4, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val5g, 3141);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val6g, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val1, 2121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val2, 2122);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val5h, 2121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val6h, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val1, 2131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val2, 2132);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val5i, 2131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val6i, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val1, 2141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val2, 2142);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val5j, 2141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val6j, val);
// Requires nested class support to work
//val = 0;
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum12_Val1, 4121);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum12_Val2, 4122);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum12_Val3, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum12_Val4, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum12_Val5k, 4121);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum12_Val6k, val);
//
//val = 0;
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Val1, 4131);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Val2, 4132);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Val3, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Val4, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Val5l, 4131);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Val6l, val);
//
//val = 0;
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum14_Val1, 4141);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum14_Val2, 4142);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum14_Val3, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum14_Val4, val);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum14_Val5m, 4141);
//val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1_Enum14_Val6m, val);
class1 = new cpp11_strongly_typed_enumerations.Class1();
enumCheck(class1.class1Test1(cpp11_strongly_typed_enumerations.Enum1_Val5a), 13);
enumCheck(class1.class1Test2(cpp11_strongly_typed_enumerations.Class1.Enum12_Val5c), 1121);
//enumCheck(class1.class1Test3(cpp11_strongly_typed_enumerations.Class1.Struct1_Enum12_Val5f), 3121);
enumCheck(cpp11_strongly_typed_enumerations.globalTest1(cpp11_strongly_typed_enumerations.Enum1_Val5a), 13);
enumCheck(cpp11_strongly_typed_enumerations.globalTest2(cpp11_strongly_typed_enumerations.Class1.Enum12_Val5c), 1121);
//enumCheck(globalTest3(cpp11_strongly_typed_enumerations.Class1.Struct1_Enum12_Val5f), 3121);
var cpp_enum = require("cpp_enum");
var f = new cpp_enum.Foo()
if(f.hola != cpp_enum.Hello){
print(f.hola);
throw "Error";
}
f.hola = cpp_enum.Foo.Hi
if(f.hola != cpp_enum.Foo.Hi){
print(f.hola);
throw "Error";
}
f.hola = cpp_enum.Hello
if(f.hola != cpp_enum.Hello){
print(f.hola);
throw "Error";
}
cpp_enum.Foo.hi = cpp_enum.Hello
if(cpp_enum.Foo.hi != cpp_enum.Hello){
print(cpp_enum.Foo.hi);
throw "Error";
}
var cpp_namespace = require("cpp_namespace");
var n = cpp_namespace.fact(4);
if (n != 24){
throw ("Bad return value error!");
}
if (cpp_namespace.Foo != 42){
throw ("Bad variable value error!");
}
t = new cpp_namespace.Test();
if (t.method() != "Test::method"){
throw ("Bad method return value error!");
}
if (cpp_namespace.do_method(t) != "Test::method"){
throw ("Bad return value error!");
}
if (cpp_namespace.do_method2(t) != "Test::method"){
throw ("Bad return value error!");
}
cpp_namespace.weird("hello", 4);
delete t;
t2 = new cpp_namespace.Test2();
t3 = new cpp_namespace.Test3();
t4 = new cpp_namespace.Test4();
t5 = new cpp_namespace.Test5();
if (cpp_namespace.foo3(42) != 42){
throw ("Bad return value error!");
}
if (cpp_namespace.do_method3(t2,40) != "Test2::method"){
throw ("Bad return value error!");
}
if (cpp_namespace.do_method3(t3,40) != "Test3::method"){
throw ("Bad return value error!");
}
if (cpp_namespace.do_method3(t4,40) != "Test4::method"){
throw ("Bad return value error!");
}
if (cpp_namespace.do_method3(t5,40) != "Test5::method"){
throw ("Bad return value error!");
}
var cpp_static = require("cpp_static");
cpp_static.StaticFunctionTest.static_func();
cpp_static.StaticFunctionTest.static_func_2(1);
cpp_static.StaticFunctionTest.static_func_3(1,2);
cpp_static.StaticMemberTest.static_int = 10;
if (cpp_static.StaticMemberTest.static_int != 10)
throw "error";
var director_alternating = require("director_alternating");
id = director_alternating.getBar().id();
if (id != director_alternating.idFromGetBar())
throw ("Error, Got wrong id: " + str(id));
var disown = require("disown");
var a = new disown.A();
var tmp = a.thisown;
a.thisown = 0
if (a.thisown) {
throw new Error("Failed.");
}
a.thisown = 1
if (!a.thisown) {
throw new Error("Failed.");
}
a.thisown = tmp
if (a.thisown != tmp) {
throw new Error("Failed.");
}
var b = new disown.B();
b.acquire(a);
if (a.thisown) {
throw new Error("Failed.");
}
var dynamic_cast = require("dynamic_cast");
var f = new dynamic_cast.Foo();
var b = new dynamic_cast.Bar();
var x = f.blah();
var y = b.blah();
var a = dynamic_cast.do_test(y);
if (a != "Bar::test") {
throw new Error("Failed.");
}
var empty_c = require("empty_c");
var empty = require("empty");
var enum_template = require("enum_template");
if (enum_template.MakeETest() != 1)
throw "RuntimeError";
if (enum_template.TakeETest(0) != null)
throw "RuntimeError";
var infinity = require("infinity");
infinity.initialise_MYINFINITY();
var my_infinity = infinity.INFINITY;
var ret_val = infinity.use_infinity(my_infinity);
var namespace_virtual_method = require("namespace_virtual_method");
x = new namespace_virtual_method.Spam();
var native_directive = require("native_directive");
(function main() {
var s = "abc.DEF-123";
if (native_directive.CountAlphas(s) !== 6)
throw "CountAlphas failed";
if (native_directive.CountAlphaCharacters(s) !== 6)
throw "CountAlphaCharacters failed";
})();
var nspace_extend = require("nspace_extend");
// constructors and destructors
var color1 = new nspace_extend.Outer.Inner1.Color();
var color = new nspace_extend.Outer.Inner1.Color(color1);
delete color1;
// class methods
color.colorInstanceMethod(20.0);
nspace_extend.Outer.Inner1.Color.colorStaticMethod(20.0);
var created = nspace_extend.Outer.Inner1.Color.create();
// constructors and destructors
var color2 = new nspace_extend.Outer.Inner2.Color();
color = new nspace_extend.Outer.Inner2.Color(color2);
delete color2;
// class methods
color.colorInstanceMethod(20.0);
nspace_extend.Outer.Inner2.Color.colorStaticMethod(20.0);
created = nspace_extend.Outer.Inner2.Color.create();
// Same class different namespaces
var col1 = new nspace_extend.Outer.Inner1.Color();
var col2 = nspace_extend.Outer.Inner2.Color.create();
col2.colors(col1, col1, col2, col2, col2);
var nspace = require("nspace");
var color1 = new nspace.Outer.Inner1.Color();
var color = new nspace.Outer.Inner1.Color(color1);
delete color1;
// class methods
color.colorInstanceMethod(20.0);
nspace.Outer.Inner1.Color.colorStaticMethod(20.0);
var created = nspace.Outer.Inner1.Color.create();
// class enums
var someClass = new nspace.Outer.SomeClass();
var channel = someClass.GetInner1ColorChannel();
if (channel != nspace.Outer.Inner1.Color.Transmission) {
throw new Error("Failed.");
}
// class anonymous enums
var val1 = nspace.Outer.Inner1.Color.ColorEnumVal1;
var val2 = nspace.Outer.Inner1.Color.ColorEnumVal2;
if (val1 !== 0 || val2 !== 0x22) {
throw new Error("Failed.");
}
// instance member variables
color.instanceMemberVariable = 123;
if (color.instanceMemberVariable !== 123) {
throw new Error("Failed.");
}
// static member variables
nspace.Outer.Inner1.Color.staticMemberVariable = 789;
if (nspace.Outer.Inner1.Color.staticMemberVariable !== 789) {
throw new Error("Failed.");
}
if (nspace.Outer.Inner1.Color.staticConstMemberVariable !== 222) {
throw new Error("Failed.");
}
if (nspace.Outer.Inner1.Color.staticConstEnumMemberVariable !== nspace.Outer.Inner1.Color.Transmission) {
throw new Error("Failed.");
}
// Same class different namespaces
var col1 = new nspace.Outer.Inner1.Color();
var col2 = nspace.Outer.Inner2.Color.create();
col2.colors(col1, col1, col2, col2, col2);
nspace.Outer.Inner1.namespaceFunction(color);
nspace.Outer.Inner1.namespaceVar = 111;
if (nspace.Outer.Inner1.namespaceVar !== 111) {
throw new Error("Failed.");
}
// global enums
var outerChannel1 = someClass.GetInner1Channel();
if (outerChannel1 != nspace.Outer.Inner1.Transmission1) {
throw new Error("Failed.");
}
var outerChannel2 = someClass.GetInner2Channel();
if (outerChannel2 !== nspace.Outer.Inner2.Transmission2) {
throw new Error("Failed.");
}
// turn feature off / ignoring
var ns = new nspace.Outer.namespce();
var nons = new nspace.NoNSpacePlease();
// Derived class
var blue3 = new nspace.Outer.Inner3.Blue();
blue3.blueInstanceMethod();
var blue4 = new nspace.Outer.Inner4.Blue();
blue4.blueInstanceMethod();
var null_pointer = require("null_pointer");
if (!null_pointer.funk(null)) {
throw new Error("Javascript 'null' should be converted into NULL.");
}
if (null_pointer.getnull() != null) {
throw new Error("NULL should be converted into Javascript 'null'.");
}
var overload_copy = require("overload_copy");
f = new overload_copy.Foo();
g = new overload_copy.Foo(f);
// There are no typecheck typemaps in Javascript yet, so most of this test
// does not actually worked - the check functions have thus been commented out.
var overload_null = require("overload_null");
var check = function(expected, actual) {
if (expected !== actual) {
throw new Error(a + " does not equal " + b);
}
};
var o = new overload_null.Overload();
var x = new overload_null.X();
check(1, o.byval1(x));
// check(2, o.byval1(null));
// check(3, o.byval2(null));
check(4, o.byval2(x));
check(5, o.byref1(x));
// check(6, o.byref1(null));
// check(7, o.byref2(null));
check(8, o.byref2(x));
check(9, o.byconstref1(x));
// check(10, o.byconstref1(null));
// check(11, o.byconstref2(null));
check(12, o.byconstref2(x));
// const pointer references
check(13, o.byval1cpr(x));
// check(14, o.byval1cpr(null));
// check(15, o.byval2cpr(null));
check(16, o.byval2cpr(x));
// forward class declaration
check(17, o.byval1forwardptr(x));
// check(18, o.byval1forwardptr(null));
// check(19, o.byval2forwardptr(null));
check(20, o.byval2forwardptr(x));
check(21, o.byval1forwardref(x));
check(22, o.byval2forwardref(x));
var preproc_include = require("preproc_include");
if (preproc_include.multiply10(10) != 100)
throw "RuntimeError";
if (preproc_include.multiply20(10) != 200)
throw "RuntimeError";
if (preproc_include.multiply30(10) != 300)
throw "RuntimeError";
if (preproc_include.multiply40(10) != 400)
throw "RuntimeError";
if (preproc_include.multiply50(10) != 500)
throw "RuntimeError";
if (preproc_include.multiply60(10) != 600)
throw "RuntimeError";
if (preproc_include.multiply70(10) != 700)
throw "RuntimeError";
var preproc = require("preproc");
if (preproc.endif != 1)
throw "RuntimeError";
if (preproc.define != 1)
throw "RuntimeError";
if (preproc.defined != 1)
throw "RuntimeError";
if (2*preproc.one != preproc.two)
throw "RuntimeError";
var rename = require("rename1");
function part1() {
var xyz = new rename.XYZInt();
notxyz = new rename.NotXYZInt();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother2();
xyz.opT2();
xyz.tMethod2(0);
xyz.tMethodNotXYZ2(notxyz);
xyz.opNotXYZ2();
}
function part2() {
var xyz = new rename.XYZDouble();
var notxyz = new rename.NotXYZDouble();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother1();
xyz.opT1();
xyz.tMethod1(0);
xyz.tMethodNotXYZ1(notxyz);
xyz.opNotXYZ1();
}
function part3(){
var xyz = new rename.XYZKlass();
var notxyz = new rename.NotXYZKlass();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother3();
xyz.opT3();
xyz.tMethod3(new rename.Klass());
xyz.tMethodNotXYZ3(notxyz);
xyz.opNotXYZ3();
}
function part4() {
var xyz = new rename.XYZEnu();
var notxyz = new rename.NotXYZEnu();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother4();
xyz.opT4();
xyz.tMethod4(rename.En1);
xyz.tMethodNotXYZ4(notxyz);
xyz.opNotXYZ4();
}
function part5() {
var abc = new rename.ABC();
abc.methodABC(abc);
var k = new rename.Klass();
abc.methodKlass(k);
var a = abc.opABC();
k = abc.opKlass();
}
part1();
part2();
part3();
part4();
part5();
var rename = require("rename2");
function part1() {
var xyz = new rename.XYZInt();
notxyz = new rename.NotXYZInt();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother2();
xyz.opT2();
xyz.tMethod2(0);
xyz.tMethodNotXYZ2(notxyz);
xyz.opNotXYZ2();
}
function part2() {
var xyz = new rename.XYZDouble();
var notxyz = new rename.NotXYZDouble();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother1();
xyz.opT1();
xyz.tMethod1(0);
xyz.tMethodNotXYZ1(notxyz);
xyz.opNotXYZ1();
}
function part3(){
var xyz = new rename.XYZKlass();
var notxyz = new rename.NotXYZKlass();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother3();
xyz.opT3();
xyz.tMethod3(new rename.Klass());
xyz.tMethodNotXYZ3(notxyz);
xyz.opNotXYZ3();
}
function part4() {
var xyz = new rename.XYZEnu();
var notxyz = new rename.NotXYZEnu();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother4();
xyz.opT4();
xyz.tMethod4(rename.En1);
xyz.tMethodNotXYZ4(notxyz);
xyz.opNotXYZ4();
}
function part5() {
var abc = new rename.ABC();
abc.methodABC(abc);
var k = new rename.Klass();
abc.methodKlass(k);
var a = abc.opABC();
k = abc.opKlass();
}
part1();
part2();
part3();
part4();
part5();
var rename = require("rename3");
function part1() {
var xyz = new rename.XYZInt();
notxyz = new rename.NotXYZInt();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother2();
xyz.opT2();
xyz.tMethod2(0);
xyz.tMethodNotXYZ2(notxyz);
xyz.opNotXYZ2();
}
function part2() {
var xyz = new rename.XYZDouble();
var notxyz = new rename.NotXYZDouble();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother1();
xyz.opT1();
xyz.tMethod1(0);
xyz.tMethodNotXYZ1(notxyz);
xyz.opNotXYZ1();
}
function part3(){
var xyz = new rename.XYZKlass();
var notxyz = new rename.NotXYZKlass();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother3();
xyz.opT3();
xyz.tMethod3(new rename.Klass());
xyz.tMethodNotXYZ3(notxyz);
xyz.opNotXYZ3();
}
function part4() {
var xyz = new rename.XYZEnu();
var notxyz = new rename.NotXYZEnu();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother4();
xyz.opT4();
xyz.tMethod4(rename.En1);
xyz.tMethodNotXYZ4(notxyz);
xyz.opNotXYZ4();
}
function part5() {
var abc = new rename.ABC();
abc.methodABC(abc);
var k = new rename.Klass();
abc.methodKlass(k);
var a = abc.opABC();
k = abc.opKlass();
}
part1();
part2();
part3();
part4();
part5();
var rename = require("rename4");
function part1() {
var xyz = new rename.XYZInt();
notxyz = new rename.NotXYZInt();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother2();
xyz.opT2();
xyz.tMethod2(0);
xyz.tMethodNotXYZ2(notxyz);
xyz.opNotXYZ2();
}
function part2() {
var xyz = new rename.XYZDouble();
var notxyz = new rename.NotXYZDouble();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother1();
xyz.opT1();
xyz.tMethod1(0);
xyz.tMethodNotXYZ1(notxyz);
xyz.opNotXYZ1();
}
function part3(){
var xyz = new rename.XYZKlass();
var notxyz = new rename.NotXYZKlass();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother3();
xyz.opT3();
xyz.tMethod3(new rename.Klass());
xyz.tMethodNotXYZ3(notxyz);
xyz.opNotXYZ3();
}
function part4() {
var xyz = new rename.XYZEnu();
var notxyz = new rename.NotXYZEnu();
xyz.opIntPtrA();
xyz.opIntPtrB();
xyz.opAnother4();
xyz.opT4();
xyz.tMethod4(rename.En1);
xyz.tMethodNotXYZ4(notxyz);
xyz.opNotXYZ4();
}
function part5() {
var abc = new rename.ABC();
abc.methodABC(abc);
var k = new rename.Klass();
abc.methodKlass(k);
var a = abc.opABC();
k = abc.opKlass();
}
part1();
part2();
part3();
part4();
part5();
var rename_scope = require("rename_scope");
var a = new rename_scope.Natural_UP();
var b = new rename_scope.Natural_BP();
if (a.rtest() !== 1) {
throw new Error("a.rtest(): Expected 1, was " + a.rtest());
}
if (b.rtest() !== 1) {
throw new Error("b.rtest(): Expected 1, was " + b.rtest());
}
var f = rename_scope.equals;
if (f === undefined) {
throw new Error("Equality operator has not been renamed.");
}
var rename_simple = require("rename_simple");
var NewStruct = rename_simple.NewStruct;
var s = new NewStruct();
// renamed instance variable
if (s.NewInstanceVariable !== 111) {
throw new Error("NewInstanceVariable: Expected 111, was " + s.NewInstanceVariable);
}
// renamed instance method
if (s.NewInstanceMethod() !== 222) {
throw new Error("NewInstanceMethod(): Expected 222, was " + s.NewInstanceMethod());
}
// renamed static method
if (NewStruct.NewStaticMethod() !== 333) {
throw new Error("NewInstanceMethod(): Expected 333, was " + NewStruct.NewStaticMethod());
}
// renamed static variable
if (NewStruct.NewStaticVariable !== 444) {
throw new Error("NewInstanceMethod(): Expected 444, was " + NewStruct.NewStaticVariable);
}
// renamed global function
if (rename_simple.NewFunction() !== 555) {
throw new Error("rename_simple.NewFunction(): Expected 555, was " + rename_simple.NewFunction());
}
// renamed global variable
if (rename_simple.NewGlobalVariable !== 666) {
throw new Error("rename_simple.NewGlobalVariable: Expected 666, was " + rename_simple.NewGlobalVariable);
}
// setting renamed variables
s.NewInstanceVariable = 1111;
if (s.NewInstanceVariable !== 1111) {
throw new Error("NewInstanceVariable: Expected 1111, was " + s.NewInstanceVariable);
}
NewStruct.NewStaticVariable = 4444;
if (NewStruct.NewStaticVariable !== 4444) {
throw new Error("NewInstanceMethod(): Expected 4444, was " + NewStruct.NewStaticVariable);
}
rename_simple.NewGlobalVariable = 6666;
if (rename_simple.NewGlobalVariable !== 6666) {
throw new Error("rename_simple.NewGlobalVariable: Expected 6666, was " + rename_simple.NewGlobalVariable);
}
var ret_by_value = require("ret_by_value");
a = ret_by_value.get_test();
if (a.myInt != 100)
throw "RuntimeError";
if (a.myShort != 200)
throw "RuntimeError";
var string_simple = require("string_simple");
// Test unicode string
var str = "olé";
var copy = string_simple.copy_str(str);
if (str !== copy) {
throw "Error: copy is not equal: original="+str+", copy="+copy;
}
var struct_value = require("struct_value");
b = new struct_value.Bar();
b.a.x = 3;
if (b.a.x != 3)
throw "RuntimeError";
b.b.x = 3;
if (b.b.x != 3)
throw "RuntimeError"
var swig_exception = require("swig_exception");
var c = new swig_exception.Circle(10);
var s = new swig_exception.Square(10);
if (swig_exception.Shape.nshapes != 2) {
throw "Shape.nshapes should be 2, actually " + swig_exception.Shape.nshapes;
}
// ----- Throw exception -----
try {
c.throwException();
throw "Exception wasn't thrown";
} catch (e) {
if (e.message != "OK") {
throw "Exception message should be \"OK\", actually \"" + e.message + "\"";
}
}
// ----- Delete everything -----
c = null;
s = null;
e = null;
/* FIXME: Garbage collection needs to happen before this check will work.
if (swig_exception.Shape.nshapes != 0) {
throw "Shape.nshapes should be 0, actually " + swig_exception.Shape.nshapes;
}
*/
var template_static = require("template_static");
template_static.Foo.bar_double(1);
var typedef_class = require("typedef_class");
a = new typedef_class.RealA();
a.a = 3;
b = new typedef_class.B();
b.testA(a);
var typedef_inherit = require("typedef_inherit");
a = new typedef_inherit.Foo();
b = new typedef_inherit.Bar();
x = typedef_inherit.do_blah(a);
if (x != "Foo::blah")
print("Whoa! Bad return" + x);
x = typedef_inherit.do_blah(b);
if (x != "Bar::blah")
print("Whoa! Bad return" + x);
c = new typedef_inherit.Spam();
d = new typedef_inherit.Grok();
x = typedef_inherit.do_blah2(c);
if (x != "Spam::blah")
print("Whoa! Bad return" + x);
x = typedef_inherit.do_blah2(d);
if (x != "Grok::blah")
print ("Whoa! Bad return" + x);
var typedef_scope = require("typedef_scope");
b = new typedef_scope.Bar();
x = b.test1(42,"hello");
if (x != 42)
print("Failed!!");
x = b.test2(42,"hello");
if (x != "hello")
print("Failed!!");
var typemap_arrays = require("typemap_arrays");
if (typemap_arrays.sumA(null) != 60)
throw "RuntimeError, Sum is wrong";
var typemap_delete = require("typemap_delete");
r = new typemap_delete.Rect(123);
if (r.val != 123)
throw "RuntimeError";
var typemap_namespace = require("typemap_namespace");
if (typemap_namespace.test1("hello") != "hello")
throw "RuntimeError";
if (typemap_namespace.test2("hello") != "hello")
throw "RuntimeError";
var typemap_ns_using = require("typemap_ns_using");
if (typemap_ns_using.spam(37) != 37)
throw "RuntimeError";
var using1 = require("using1");
if (using1.spam(37) != 37)
throw "RuntimeError";
var using2 = require("using2");
if (using2.spam(37) != 37)
throw "RuntimeError";
var varargs = require("varargs");
if (varargs.test("Hello") != "Hello") {
throw new Error("Failed");
}
var f = new varargs.Foo("Greetings")
if (f.str != "Greetings") {
throw new Error("Failed");
}
if (f.test("Hello") != "Hello") {
throw new Error("Failed");
}
if (varargs.test_def("Hello",1) != "Hello") {
throw new Error("Failed");
}
if (varargs.test_def("Hello") != "Hello") {
throw new Error("Failed");
}
if (varargs.test_plenty("Hello") != "Hello") {
throw new Error("Failed");
}
if (varargs.test_plenty("Hello", 1) != "Hello") {
throw new Error("Failed");
}
if (varargs.test_plenty("Hello", 1, 2) != "Hello") {
throw new Error("Failed");
}
var thrown = false;
try {
varargs.test_plenty("Hello", 1, 2, 3);
} catch (err) {
thrown = true;
}
if (!thrown) {
throw new Error("Failed");
}
import abstract_access
d = abstract_access.D()
if d.do_x() != 1:
raise RuntimeError
from abstract_typedef2 import *
a = A_UF()
from abstract_typedef import *
e = Engine()
a = A()
if a.write(e) != 1:
raise RuntimeError
from abstract_virtual import *
d = D()
e = E()
from argcargvtest import *
largs = ["hi", "hola", "hello"]
if mainc(largs) != 3:
raise RuntimeError("bad main typemap")
targs = ("hi", "hola")
if mainv(targs, 1) != "hola":
print(mainv(targs, 1))
raise RuntimeError("bad main typemap")
targs = ("hi", "hola")
if mainv(targs, 1) != "hola":
raise RuntimeError("bad main typemap")
try:
error = 0
mainv("hello", 1)
error = 1
except TypeError:
pass
if error:
raise RuntimeError("bad main typemap")
initializeApp(largs)
import arrays_global
arrays_global.cvar.array_i = arrays_global.cvar.array_const_i
from arrays_global import *
BeginString_FIX44a
cvar.BeginString_FIX44b
BeginString_FIX44c
cvar.BeginString_FIX44d
cvar.BeginString_FIX44d
cvar.BeginString_FIX44b = "12"'\0'"45"
cvar.BeginString_FIX44b
cvar.BeginString_FIX44d
cvar.BeginString_FIX44e
BeginString_FIX44f
test_a("hello", "hi", "chello", "chi")
test_b("1234567", "hi")
from array_member import *
f = Foo()
f.data = cvar.global_data
for i in range(0, 8):
if get_value(f.data, i) != get_value(cvar.global_data, i):
raise RuntimeError, "Bad array assignment"
for i in range(0, 8):
set_value(f.data, i, -i)
cvar.global_data = f.data
for i in range(0, 8):
if get_value(f.data, i) != get_value(cvar.global_data, i):
raise RuntimeError, "Bad array assignment"
from autodoc import *
import _autodoc
import comment_verifier
import inspect
import sys
def check(got, expected, expected_builtin=None, skip=False):
if is_python_builtin() and skip:
# Only skip for builtins
pass
else:
expect = expected
if is_python_builtin() and expected_builtin != None:
expect = expected_builtin
comment_verifier.check(got, expect)
# skip builtin check - the autodoc is missing, but it probably should not be
skip = True
check(inspect.getdoc(A), "Proxy of C++ A class.", "::A")
check(inspect.getdoc(A.funk), "just a string.")
check(inspect.getdoc(A.func0),
"func0(self, arg2, hello) -> int")
check(inspect.getdoc(A.func1),
"func1(A self, short arg2, Tuple hello) -> int")
check(inspect.getdoc(A.func2),
"func2(self, arg2, hello) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"arg2: short\n"
"hello: int tuple[2]")
check(inspect.getdoc(A.func3),
"func3(A self, short arg2, Tuple hello) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"arg2: short\n"
"hello: int tuple[2]")
check(inspect.getdoc(A.func0default),
"func0default(self, e, arg3, hello, f=2) -> int")
check(inspect.getdoc(A.func1default),
"func1default(A self, A e, short arg3, Tuple hello, double f=2) -> int")
check(inspect.getdoc(A.func2default),
"func2default(self, e, arg3, hello, f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg3: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(A.func3default),
"func3default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg3: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(A.func0static),
"func0static(e, arg2, hello, f=2) -> int")
check(inspect.getdoc(_autodoc.A_func0static),
"A_func0static(e, arg2, hello, f=2) -> int")
check(inspect.getdoc(A_func0static),
"A_func0static(e, arg2, hello, f=2) -> int")
check(inspect.getdoc(A.func1static),
"func1static(A e, short arg2, Tuple hello, double f=2) -> int")
check(inspect.getdoc(_autodoc.A_func1static),
"A_func1static(A e, short arg2, Tuple hello, double f=2) -> int")
check(inspect.getdoc(A_func1static),
"A_func1static(A e, short arg2, Tuple hello, double f=2) -> int")
check(inspect.getdoc(A.func2static),
"func2static(e, arg2, hello, f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg2: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(_autodoc.A_func2static),
"A_func2static(e, arg2, hello, f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg2: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(A_func2static),
"A_func2static(e, arg2, hello, f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg2: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(A.func3static),
"func3static(A e, short arg2, Tuple hello, double f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg2: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(_autodoc.A_func3static),
"A_func3static(A e, short arg2, Tuple hello, double f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg2: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(A_func3static),
"A_func3static(A e, short arg2, Tuple hello, double f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg2: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(A.variable_a),
"variable_a"
)
check(inspect.getdoc(A.variable_b),
"variable_b : int"
)
check(inspect.getdoc(A.variable_c),
"variable_c"
)
check(inspect.getdoc(A.variable_d),
"variable_d : int"
)
# Check the low-level functions (not present when using -builtin except for the static ones)
if not is_python_builtin():
check(inspect.getdoc(_autodoc.A_funk), "just a string.")
check(inspect.getdoc(_autodoc.A_func0),
"A_func0(self, arg2, hello) -> int")
check(inspect.getdoc(_autodoc.A_func1),
"A_func1(A self, short arg2, Tuple hello) -> int")
check(inspect.getdoc(_autodoc.A_func2),
"A_func2(self, arg2, hello) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"arg2: short\n"
"hello: int tuple[2]")
check(inspect.getdoc(_autodoc.A_func3),
"A_func3(A self, short arg2, Tuple hello) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"arg2: short\n"
"hello: int tuple[2]")
check(inspect.getdoc(_autodoc.A_func0default),
"A_func0default(self, e, arg3, hello, f=2) -> int")
check(inspect.getdoc(_autodoc.A_func1default),
"A_func1default(A self, A e, short arg3, Tuple hello, double f=2) -> int")
check(inspect.getdoc(_autodoc.A_func2default),
"A_func2default(self, e, arg3, hello, f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg3: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(_autodoc.A_func3default),
"A_func3default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n"
"\n"
"Parameters\n"
"----------\n"
"e: A *\n"
"arg3: short\n"
"hello: int tuple[2]\n"
"f: double")
check(inspect.getdoc(_autodoc.A_variable_a_set), "A_variable_a_set(self, variable_a)")
check(inspect.getdoc(_autodoc.A_variable_a_get), "A_variable_a_get(self) -> int" )
check(inspect.getdoc(_autodoc.A_variable_b_set), "A_variable_b_set(A self, int variable_b)")
check(inspect.getdoc(_autodoc.A_variable_b_get), "A_variable_b_get(A self) -> int")
check(inspect.getdoc(_autodoc.A_variable_c_set),
"A_variable_c_set(self, variable_c)\n"
"\n"
"Parameters\n"
"----------\n"
"variable_c: int"
)
check(inspect.getdoc(_autodoc.A_variable_c_get), "A_variable_c_get(self) -> int")
check(inspect.getdoc(_autodoc.A_variable_d_set),
"A_variable_d_set(A self, int variable_d)\n"
"\n"
"Parameters\n"
"----------\n"
"variable_d: int"
)
check(inspect.getdoc(_autodoc.A_variable_d_get), "A_variable_d_get(A self) -> int")
check(inspect.getdoc(_autodoc.new_C), "new_C(a, b, h) -> C")
check(inspect.getdoc(_autodoc.delete_C), "delete_C(self)")
check(inspect.getdoc(_autodoc.new_D), "new_D(int a, int b, Hola h) -> D")
check(inspect.getdoc(_autodoc.delete_D), "delete_D(D self)")
check(inspect.getdoc(_autodoc.new_E),
"new_E(a, b, h) -> E\n"
"\n"
"Parameters\n"
"----------\n"
"a: special comment for parameter a\n"
"b: another special comment for parameter b\n"
"h: enum Hola"
)
check(inspect.getdoc(_autodoc.delete_E), "delete_E(self)")
check(inspect.getdoc(_autodoc.new_F),
"new_F(int a, int b, Hola h) -> F\n"
"\n"
"Parameters\n"
"----------\n"
"a: special comment for parameter a\n"
"b: another special comment for parameter b\n"
"h: enum Hola"
)
check(inspect.getdoc(_autodoc.delete_F), "delete_F(F self)")
check(inspect.getdoc(_autodoc.B_funk), "B_funk(B self, int c, int d) -> int")
check(inspect.getdoc(_autodoc.TInteger_inout), "TInteger_inout(TInteger self, TInteger t) -> TInteger")
check(inspect.getdoc(B),
"Proxy of C++ B class.",
"::B"
)
check(inspect.getdoc(C.__init__), "__init__(self, a, b, h) -> C", None, skip)
check(inspect.getdoc(D.__init__),
"__init__(D self, int a, int b, Hola h) -> D", None, skip)
check(inspect.getdoc(E.__init__),
"__init__(self, a, b, h) -> E\n"
"\n"
"Parameters\n"
"----------\n"
"a: special comment for parameter a\n"
"b: another special comment for parameter b\n"
"h: enum Hola", None, skip
)
check(inspect.getdoc(F.__init__),
"__init__(F self, int a, int b, Hola h) -> F\n"
"\n"
"Parameters\n"
"----------\n"
"a: special comment for parameter a\n"
"b: another special comment for parameter b\n"
"h: enum Hola", None, skip
)
check(inspect.getdoc(B.funk),
"funk(B self, int c, int d) -> int")
check(inspect.getdoc(funk), "funk(A e, short arg2, int c, int d) -> int")
check(inspect.getdoc(funkdefaults),
"funkdefaults(A e, short arg2, int c, int d, double f=2) -> int")
check(inspect.getdoc(func_input), "func_input(int * INPUT) -> int")
check(inspect.getdoc(func_output), "func_output() -> int")
check(inspect.getdoc(func_inout), "func_inout(int * INOUT) -> int")
check(inspect.getdoc(func_cb), "func_cb(int c, int d) -> int")
check(inspect.getdoc(banana), "banana(S a, S b, int c, Integer d)")
check(inspect.getdoc(TInteger), "Proxy of C++ T< int > class.", "::T< int >")
check(inspect.getdoc(TInteger.__init__), "__init__(TInteger self) -> TInteger", None, skip)
check(inspect.getdoc(TInteger.inout), "inout(TInteger self, TInteger t) -> TInteger")
check(inspect.getdoc(process), "process(int _from, int _in, int var) -> int")
check(inspect.getdoc(process2), "process2(int _from=0, int _in=1, int var=2) -> int")
check(inspect.getdoc(process3), "process3(int _from, int _in, int var) -> int")
check(inspect.getdoc(process4), "process4(int _from=0, int _in=1, int var=2) -> int")
check(inspect.getdoc(process_complex_defval), "process_complex_defval(val=PROCESS_DEFAULT_VALUE, factor=some_type(-1)) -> int")
check(inspect.getdoc(a_structure.__init__), "__init__(a_structure self) -> a_structure", None, skip)
import _callback
from callback import *
if foo(2) != 2:
raise RuntimeError
if A_bar(2) != 4:
raise RuntimeError
if foobar(3, _callback.foo) != foo(3):
raise RuntimeError
if foobar(3, foo) != foo(3):
raise RuntimeError
# Needs some more work for -builtin
# if foobar(3, A.bar) != A.bar(3):
# raise RuntimeError
if foobar(3, A_bar) != A_bar(3):
raise RuntimeError
if foobar(3, foof) != foof(3):
raise RuntimeError
if foobar_i(3, foo_i) != foo_i(3):
raise RuntimeError
if foobar_d(3.5, foo_d) != foo_d(3.5):
raise RuntimeError
a = A()
if foobarm(3, a, A.foom_cb_ptr) != a.foom(3):
raise RuntimeError
from char_binary import *
t = Test()
if t.strlen("hile") != 4:
print t.strlen("hile")
raise RuntimeError, "bad multi-arg typemap"
if t.ustrlen("hile") != 4:
print t.ustrlen("hile")
raise RuntimeError, "bad multi-arg typemap"
if t.strlen("hil\0") != 4:
raise RuntimeError, "bad multi-arg typemap"
if t.ustrlen("hil\0") != 4:
raise RuntimeError, "bad multi-arg typemap"
#
# creating a raw char*
#
pc = new_pchar(5)
pchar_setitem(pc, 0, "h")
pchar_setitem(pc, 1, "o")
pchar_setitem(pc, 2, "l")
pchar_setitem(pc, 3, "a")
pchar_setitem(pc, 4, 0)
if t.strlen(pc) != 4:
raise RuntimeError, "bad multi-arg typemap"
if t.ustrlen(pc) != 4:
raise RuntimeError, "bad multi-arg typemap"
cvar.var_pchar = pc
if cvar.var_pchar != "hola":
print cvar.var_pchar
raise RuntimeError, "bad pointer case"
cvar.var_namet = pc
# if cvar.var_namet != "hola\0":
if cvar.var_namet != "hola":
raise RuntimeError, "bad pointer case"
delete_pchar(pc)
import class_ignore
a = class_ignore.Bar()
if class_ignore.do_blah(a) != "Bar::blah":
raise RuntimeError
import class_scope_weird
f = class_scope_weird.Foo()
g = class_scope_weird.Foo(3)
if f.bar(3) != 3:
raise RuntimeError
def check(got, expected, expected_builtin=None):
if got is None: # Absence of comment is equivalent to empty comment.
got = ""
if got != expected:
import re
p = re.compile(r"^[+-]([^+-].*\S)?(\s+)$", re.M)
def make_trailing_spaces_visible(str):
def replace_trailing_spaces(match):
res = match.group(0)
spaces = match.group(2)
if spaces is not None:
res = res + "{+%d trailing spaces}" % len(spaces)
return res
return re.sub(p, replace_trailing_spaces, str)
from difflib import unified_diff
diff = unified_diff(expected.splitlines(True),
got.splitlines(True), "expected", "got")
lines = []
for line in diff:
line = make_trailing_spaces_visible(line.strip("\r\n"))
lines.append(line + "\n")
raise RuntimeError("Comments don't match:\n" + "".join(lines))
from compactdefaultargs import *
defaults1 = Defaults1(1000)
defaults1 = Defaults1()
if defaults1.ret(10.0) != 10.0:
raise RuntimeError
if defaults1.ret() != -1.0:
raise RuntimeError
defaults2 = Defaults2(1000)
defaults2 = Defaults2()
if defaults2.ret(10.0) != 10.0:
raise RuntimeError
if defaults2.ret() != -1.0:
raise RuntimeError
if defaults2.nodefault(-2) != -2:
raise RuntimeError
import complextest
a = complex(-1, 2)
if complextest.Conj(a) != a.conjugate():
raise RuntimeError, "bad complex mapping"
if complextest.Conjf(a) != a.conjugate():
raise RuntimeError, "bad complex mapping"
if complextest.Conj2(a) != a.conjugate():
raise RuntimeError, "bad complex mapping"
if complextest.Conjf2(a) != a.conjugate():
raise RuntimeError, "bad complex mapping"
v = (complex(1, 2), complex(2, 3), complex(4, 3), 1)
if len(complextest.CopyHalf(v)) != 2:
raise RuntimeError("CopyHalf failed")
if len(complextest.CopyHalfRef(v)) != 2:
raise RuntimeError("CopyHalfRef failed")
p = complextest.ComplexPair()
p.z1 = complex(0, 1)
p.z2 = complex(0, -1)
if complextest.Conj(p.z2) != p.z1:
raise RuntimeError, "bad complex mapping"
import constant_directive
if not isinstance(constant_directive.TYPE1_CONSTANT1, constant_directive.Type1):
raise RuntimeError("Failure: TYPE1_CONSTANT1 type: {}".format(
type(constant_directive.TYPE1_CONSTANT1)))
if not isinstance(constant_directive.getType1Instance(), constant_directive.Type1):
raise RuntimeError("Failure: getType1Instance() type: {}".format(
type(constant_directive.getType1Instance())))
if constant_directive.TYPE1_CONSTANT1.val != 1:
raise RuntimeError("constant_directive.TYPE1_CONSTANT1.val is %r (should be 1)" %
constant_directive.TYPE1_CONSTANT1.val)
if constant_directive.TYPE1_CONSTANT2.val != 2:
raise RuntimeError("constant_directive.TYPE1_CONSTANT2.val is %r (should be 2)" %
constant_directive.TYPE1_CONSTANT2.val)
if constant_directive.TYPE1_CONSTANT3.val != 3:
raise RuntimeError("constant_directive.TYPE1_CONSTANT3.val is %r (should be 3)" %
constant_directive.TYPE1_CONSTANT3.val)
if constant_directive.TYPE1CONST_CONSTANT1.val != 1:
raise RuntimeError("constant_directive.TYPE1CONST_CONSTANT1.val is %r (should be 1)" %
constant_directive.TYPE1CONST_CONSTANT1.val)
if constant_directive.TYPE1CPTR_CONSTANT1.val != 1:
raise RuntimeError("constant_directive.TYPE1CPTR_CONSTANT1.val is %r (should be 1)" %
constant_directive.TYPE1CPTR_CONSTANT1.val)
import constover
import sys
error = 0
p = constover.test("test")
if p != "test":
print "test failed!"
error = 1
p = constover.test_pconst("test")
if p != "test_pconst":
print "test_pconst failed!"
error = 1
f = constover.Foo()
p = f.test("test")
if p != "test":
print "member-test failed!"
error = 1
p = f.test_pconst("test")
if p != "test_pconst":
print "member-test_pconst failed!"
error = 1
p = f.test_constm("test")
if p != "test_constmethod":
print "member-test_constm failed!"
error = 1
p = f.test_pconstm("test")
if p != "test_pconstmethod":
print "member-test_pconstm failed!"
error = 1
sys.exit(error)
from constructor_copy import *
f1 = Foo1(3)
f11 = Foo1(f1)
if f1.x != f11.x:
raise RuntimeError
f8 = Foo8()
try:
f81 = Foo8(f8)
good = 0
except:
good = 1
if not good:
raise RuntimeError
bi = Bari(5)
bc = Bari(bi)
if (bi.x != bc.x):
raise RuntimeError
bd = Bard(5)
try:
bc = Bard(bd)
good = 0
except:
good = 1
if not good:
raise RuntimeError
from constructor_rename import *
x = RenamedConstructor()
import contract
contract.test_preassert(1, 2)
try:
contract.test_preassert(-1)
print "Failed! Preassertions are broken"
except:
pass
contract.test_postassert(3)
try:
contract.test_postassert(-3)
print "Failed! Postassertions are broken"
except:
pass
contract.test_prepost(2, 3)
contract.test_prepost(5, -4)
try:
contract.test_prepost(-3, 4)
print "Failed! Preassertions are broken"
except:
pass
try:
contract.test_prepost(4, -10)
print "Failed! Postassertions are broken"
except:
pass
f = contract.Foo()
f.test_preassert(4, 5)
try:
f.test_preassert(-2, 3)
print "Failed! Method preassertion."
except:
pass
f.test_postassert(4)
try:
f.test_postassert(-4)
print "Failed! Method postassertion"
except:
pass
f.test_prepost(3, 4)
f.test_prepost(4, -3)
try:
f.test_prepost(-4, 2)
print "Failed! Method preassertion."
except:
pass
try:
f.test_prepost(4, -10)
print "Failed! Method postassertion."
except:
pass
contract.Foo_stest_prepost(4, 0)
try:
contract.Foo_stest_prepost(-4, 2)
print "Failed! Static method preassertion"
except:
pass
try:
contract.Foo_stest_prepost(4, -10)
print "Failed! Static method posteassertion"
except:
pass
b = contract.Bar()
try:
b.test_prepost(2, -4)
print "Failed! Inherited preassertion."
except:
pass
d = contract.D()
try:
d.foo(-1, 1, 1, 1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.foo(1, -1, 1, 1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.foo(1, 1, -1, 1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.foo(1, 1, 1, -1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.foo(1, 1, 1, 1, -1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.bar(-1, 1, 1, 1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.bar(1, -1, 1, 1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.bar(1, 1, -1, 1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.bar(1, 1, 1, -1, 1)
print "Failed! Inherited preassertion (D)."
except:
pass
try:
d.bar(1, 1, 1, 1, -1)
print "Failed! Inherited preassertion (D)."
except:
pass
# Namespace
my = contract.myClass(1)
try:
my = contract.myClass(0)
print "Failed! constructor preassertion"
except:
pass
import cpp11_alternate_function_syntax
a = cpp11_alternate_function_syntax.SomeStruct()
res = a.addNormal(4, 5)
if res != 9:
raise RuntimeError, ("SomeStruct::addNormal(4,5) returns ", res, " should be 9.")
res = a.addAlternate(4, 5)
if res != 9:
raise RuntimeError, ("SomeStruct::addAlternate(4,5) returns ", res, " should be 9.")
res = a.addAlternateConst(4, 5)
if res != 9:
raise RuntimeError, ("SomeStruct::addAlternateConst(4,5) returns ", res, " should be 9.")
res = a.addAlternateNoExcept(4, 5)
if res != 9:
raise RuntimeError, ("SomeStruct::addAlternateNoExcept(4,5) returns ", res, " should be 9.")
res = a.addAlternateConstNoExcept(4, 5)
if res != 9:
raise RuntimeError, ("SomeStruct::addAlternateConstNoExcept(4,5) returns ", res, " should be 9.")
import cpp11_decltype
a = cpp11_decltype.A()
a.i = 5
if a.i != 5:
raise RuntimeError, "Assignment to a.i failed."
a.j = 10
if a.j != 10:
raise RuntimeError, "Assignment to a.j failed."
b = a.foo(5)
if b != 10:
raise RuntimeError, "foo(5) should return 10."
b = a.foo(6)
if b != 0:
raise RuntimeError, "foo(6) should return 0."
import cpp11_final_directors
class Derived2(cpp11_final_directors.Derived):
def meth(self):
return 3
b = Derived2()
if b.meth() != 3:
raise RuntimeError
import cpp11_function_objects
import sys
class Test1(cpp11_function_objects.Test):
def __init__(self):
cpp11_function_objects.Test.__init__(self)
def __call__(self, a, b):
self.value = a * b
t = cpp11_function_objects.Test()
if t.value != 0:
raise RuntimeError(
"Runtime cpp11_function_objects failed. t.value should be 0, but is " + str(t.value))
t(1, 2) # adds numbers and sets value
if t.value != 3:
raise RuntimeError(
"Runtime cpp11_function_objects failed. t.value not changed - should be 3, but is " + str(t.value))
t2 = Test1()
a = cpp11_function_objects.testit1(t2, 4, 3)
if a != 12:
raise RuntimeError(
"Runtime cpp11_function_objects failed. t.value not changed - should be 12, but is " + str(a))
import cpp11_hash_tables
def swig_assert_equal(a, b):
if a != b:
raise RuntimeError(str(a) + " != " + str(b))
for x in [cpp11_hash_tables.MapIntInt({1:7}),
cpp11_hash_tables.MultiMapIntInt({1:7}),
cpp11_hash_tables.UnorderedMapIntInt({1:7}),
cpp11_hash_tables.UnorderedMultiMapIntInt({1:7})
]:
swig_assert_equal([(k, v) for k, v in x.iteritems()], [(1, 7)])
swig_assert_equal(x.keys(), [1])
swig_assert_equal(x.values(), [7])
swig_assert_equal(x.items(), [(1, 7)])
swig_assert_equal([k for k in x], [1])
swig_assert_equal([i for i in x.iterkeys()], [1])
swig_assert_equal([i for i in x.itervalues()], [7])
swig_assert_equal([i for i in x.iteritems()], [(1, 7)])
swig_assert_equal(x[1], 7)
swig_assert_equal(2 in x, False)
x[2] = 9
swig_assert_equal(x[2], 9)
del x[2]
swig_assert_equal(2 in x, False)
swig_assert_equal(x.empty(), False)
del x[1]
swig_assert_equal(x.empty(), True)
swig_assert_equal(1 in x, False)
for x in [cpp11_hash_tables.MultiMapIntInt({1:7}),
cpp11_hash_tables.UnorderedMultiMapIntInt({1:7})]:
x[1] = 9
swig_assert_equal(sorted([v for k, v in x.iteritems()]), [7, 9])
swig_assert_equal(len(x), 2)
for x in [cpp11_hash_tables.SetInt([1]),
cpp11_hash_tables.MultiSetInt([1]),
cpp11_hash_tables.UnorderedSetInt([1]),
cpp11_hash_tables.UnorderedMultiSetInt([1])]:
swig_assert_equal([e for e in x], [1])
swig_assert_equal(x[0], 1)
swig_assert_equal(1 in x, True)
swig_assert_equal(2 in x, False)
x.append(2)
swig_assert_equal(2 in x, True)
x.erase(2)
swig_assert_equal(x.empty(), False)
x.erase(1)
swig_assert_equal(x.empty(), True)
for x in [cpp11_hash_tables.MultiSetInt([1]),
cpp11_hash_tables.UnorderedMultiSetInt([1])]:
x.append(1)
swig_assert_equal(x.count(1), 2)
swig_assert_equal(len(x), 2)
import cpp11_initializer_list_extend
c = cpp11_initializer_list_extend.Container([10, 20, 30, 40])
import cpp11_initializer_list
a = cpp11_initializer_list.A()
a = cpp11_initializer_list.A(11.1)
import cpp11_null_pointer_constant
a = cpp11_null_pointer_constant.A()
if a._myA != None:
raise RuntimeError, (
"cpp11_null_pointer_constant: _myA should be None, but is ", a._myA)
b = cpp11_null_pointer_constant.A()
if a._myA != b._myA:
raise RuntimeError, (
"cpp11_null_pointer_constant: a._myA should be the same as b._myA, but ", a._myA, "!=", b._myA)
a._myA = cpp11_null_pointer_constant.A()
if a._myA == None:
raise RuntimeError, (
"cpp11_null_pointer_constant: _myA should be object, but is None")
from cpp11_raw_string_literals import *
import inspect
if cvar.L != 100:
raise RuntimeError
if cvar.u8 != 100:
raise RuntimeError
if cvar.u != 100:
raise RuntimeError
if UStruct.U != 100:
raise RuntimeError
if cvar.R != 100:
raise RuntimeError
if cvar.LR != 100:
raise RuntimeError
if cvar.u8R != 100:
raise RuntimeError
if cvar.uR != 100:
raise RuntimeError
if URStruct.UR != 100:
raise RuntimeError
if cvar.aa != "Wide string":
raise RuntimeError
if cvar.bb != "UTF-8 string":
raise RuntimeError, cvar.wide
if cvar.xx != ")I'm an \"ascii\" \\ string.":
raise RuntimeError, cvar.xx
if cvar.ee != ")I'm an \"ascii\" \\ string.":
raise RuntimeError, cvar.ee
if cvar.ff != "I'm a \"raw wide\" \\ string.":
raise RuntimeError, cvar.ff
if cvar.gg != "I'm a \"raw UTF-8\" \\ string.":
raise RuntimeError, cvar.gg
def check(got, expected):
expected_list = expected.split("\n")
got_list = got.split("\n")
if expected_list != got_list:
raise RuntimeError("\n" + "Expected: " + str(expected_list) + "\n" + "Got : " + str(got_list))
# When getting docstrings, use inspect.getdoc(x) instead of x.__doc__ otherwise the different options
# such as -O and -builtin may produce different initial indentation.
check(inspect.getdoc(RawStringDoc.WW), "Single line documentation comment")
check(inspect.getdoc(RawStringDoc.XX),
"""Multi-line
documentation
comment""")
check(inspect.getdoc(RawStringDoc.YY), """Single line "raw string" documentation comment""")
check(inspect.getdoc(RawStringDoc.ZZ),
"""Documentation comment
as a "raw string"
on multiple lines including a \ backslash""")
check(mm, """)I'm an "ascii" \ string constant with multiple
lines.""")
import cpp11_ref_qualifiers
h = cpp11_ref_qualifiers.Host()
# Basic testing
h.h1()
h.h2()
h.h6()
h.h7()
h.h()
# %feature testing
f = cpp11_ref_qualifiers.Features()
if f.F1() != "F1":
raise RuntimeException("Fail")
if f.F2() != "F2":
raise RuntimeException("Fail")
if f.F3() != "F3":
raise RuntimeException("Fail")
if f.C1(0) != "C1":
raise RuntimeException("Fail")
if f.C2(0) != "C2":
raise RuntimeException("Fail")
if f.C3(0) != "C3":
raise RuntimeException("Fail")
# %rename testing
r = cpp11_ref_qualifiers.Renames()
r.RR1()
r.RR2()
r.RR3()
r.SS1(0)
r.SS2(0)
r.SS3(0)
# Conversion operators
co = cpp11_ref_qualifiers.ConversionOperators()
s = co.StringConvertCopy()
s = co.StringConvertMove()
co2 = cpp11_ref_qualifiers.ConversionOperators2()
s = co2.StringConvertMove()
import cpp11_ref_qualifiers_rvalue_unignore
cpp11_ref_qualifiers_rvalue_unignore.RefQualifier().m1()
cpp11_ref_qualifiers_rvalue_unignore.RefQualifier().m2()
import cpp11_result_of
result = cpp11_result_of.test_result(cpp11_result_of.SQUARE, 3.0)
if result != 9.0:
raise RuntimeError, "test_result(square, 3.0) is not 9.0. Got: " + str(
result)
result = cpp11_result_of.test_result_alternative1(cpp11_result_of.SQUARE, 3.0)
if result != 9.0:
raise RuntimeError, "test_result_alternative1(square, 3.0) is not 9.0. Got: " + str(
result)
import cpp11_rvalue_reference
a = cpp11_rvalue_reference.A()
a.setAcopy(5)
if a.getAcopy() != 5:
raise RunTimeError, ("int A::getAcopy() value is ",
a.getAcopy(), " should be 5")
ptr = a.getAptr()
a.setAptr(ptr)
if a.getAcopy() != 5:
raise RunTimeError, ("after A::setAptr(): int A::getAcopy() value is ", a.getAcopy(
), " should be 5")
a.setAref(ptr)
if a.getAcopy() != 5:
raise RunTimeError, ("after A::setAref(): int A::getAcopy() value is ", a.getAcopy(
), " should be 5")
rvalueref = a.getAmove()
a.setAmove(rvalueref)
if a.getAcopy() != 5:
raise RunTimeError, ("after A::setAmove(): int A::getAcopy() value is ", a.getAcopy(
), " should be 5")
import cpp11_shared_ptr_overload
from cpp11_shared_ptr_overload import MyType
# ref
ret = cpp11_shared_ptr_overload.UseA(MyType("123"))
if ret != "123 ref": raise RuntimeError("UseA fail:" + ret)
ret = cpp11_shared_ptr_overload.UseB(0, MyType("123"))
if ret != "123 ref": raise RuntimeError("UseB fail:" + ret)
ret = cpp11_shared_ptr_overload.UseC(0, MyType("123"), MyType("456"))
if ret != "123 ref": raise RuntimeError("UseC fail:" + ret)
# sharedptr
ret = cpp11_shared_ptr_overload.UseX(MyType("123"))
if ret != "123 sharedptr": raise RuntimeError("UseX fail:" + ret)
ret = cpp11_shared_ptr_overload.UseY(0, MyType("123"))
if ret != "123 sharedptr": raise RuntimeError("UseY fail:" + ret)
ret = cpp11_shared_ptr_overload.UseZ(0, MyType("123"), MyType("456"))
if ret != "123 sharedptr": raise RuntimeError("UseZ fail:" + ret)
# Combo1-4
ret = cpp11_shared_ptr_overload.Combo1(MyType("XXX"))
if ret != "XXXCombo1": raise RuntimeError("Combo1 fail:" + ret)
ret = cpp11_shared_ptr_overload.Combo2(MyType("XXX"))
if ret != "XXXCombo2": raise RuntimeError("Combo2 fail:" + ret)
ret = cpp11_shared_ptr_overload.Combo3(MyType("XXX"))
if ret != "XXXCombo3": raise RuntimeError("Combo3 fail:" + ret)
ret = cpp11_shared_ptr_overload.Combo4(MyType("XXX"))
if ret != "XXXCombo4": raise RuntimeError("Combo4 fail:" + ret)
# Combo5-7
ret = cpp11_shared_ptr_overload.Combo5(MyType("XXX"))
if ret != "XXXCombo5": raise RuntimeError("Combo5 fail:" + ret)
ret = cpp11_shared_ptr_overload.Combo6(MyType("XXX"))
if ret != "XXXCombo6": raise RuntimeError("Combo6 fail:" + ret)
ret = cpp11_shared_ptr_overload.Combo7(MyType("XXX"))
if ret != "XXXCombo7": raise RuntimeError("Combo7 fail:" + ret)
from cpp11_shared_ptr_template_upcast import *
pd = MakePrintableDerived(20)
pd.GetResult()
pd.GetFormatted()
from cpp11_shared_ptr_upcast import *
# This is a port from the Ruby equivalent test and some tests ported from
# Examples/test-suite/ruby/cpp11_shared_ptr_upcast_runme.rb are not working and commented out with:
# not working:
def swig_assert_equal_simple(expected, got):
if expected != got:
raise RuntimeError("Expected: {}. Got: {}")
# non-overloaded
swig_assert_equal_simple(7, derived_num1(Derived(7)))
swig_assert_equal_simple(7, derived_num2([Derived(7)]))
swig_assert_equal_simple(7, derived_num3({0: Derived(7)}))
swig_assert_equal_simple(-1, base_num1(Derived(7)))
swig_assert_equal_simple(-1, base_num2([Derived(7)]))
swig_assert_equal_simple(-1, base_num3({0: Derived(7)}))
swig_assert_equal_simple(999, derived_num1(None))
# not working: swig_assert_equal_simple(999, derived_num2([None]))
# not working: swig_assert_equal_simple(999, derived_num3({0: None}))
swig_assert_equal_simple(999, base_num1(None))
# not working: swig_assert_equal_simple(999, base_num2([None]))
# not working: swig_assert_equal_simple(999, base_num3({0: None}))
# overloaded
swig_assert_equal_simple(7, derived_num(Derived(7)))
swig_assert_equal_simple(7, derived_num([Derived(7)]))
swig_assert_equal_simple(7, derived_num({0: Derived(7)}))
swig_assert_equal_simple(-1, base_num(Derived(7)))
swig_assert_equal_simple(-1, base_num([Derived(7)]))
swig_assert_equal_simple(-1, base_num({0: Derived(7)}))
# ptr to shared_ptr
swig_assert_equal_simple(7, derived2_num1(Derived2(7)))
swig_assert_equal_simple(7, derived2_num2([Derived2(7)]))
swig_assert_equal_simple(7, derived2_num3({0: Derived2(7)}))
swig_assert_equal_simple(-1, base2_num1(Derived2(7)))
# not working: try:
# not working: # Upcast for pointers to shared_ptr in this generic framework has not been implemented
# not working: swig_assert_equal_simple(-1, base2_num2([Derived2(7)]))
# not working: raise RuntimeError, "Failed to catch TypeError"
# not working: except TypeError:
# not working: pass
# not working: try:
# not working: # Upcast for pointers to shared_ptr in this generic framework has not been implemented
# not working: swig_assert_equal_simple(-1, base2_num3({0: Derived2(7)}))
# not working: raise RuntimeError, "Failed to catch TypeError"
# not working: except TypeError:
# not working: pass
swig_assert_equal_simple(888, derived2_num1(None))
swig_assert_equal_simple(999, derived2_num2([None])) # although 888 would be more consistent
swig_assert_equal_simple(999, derived2_num3({0: None})) # although 888 would be more consistent
swig_assert_equal_simple(888, base2_num1(None))
swig_assert_equal_simple(999, base2_num2([None])) # although 888 would be more consistent
swig_assert_equal_simple(999, base2_num3({0: None})) # although 888 would be more consistent
from cpp11_std_array import *
import sys
def failed(a, b, msg):
raise RuntimeError, msg + " " + str(list(a)) + " " + str(list(b))
def compare_sequences(a, b):
if len(a) != len(b):
failed(a, b, "different sizes")
for i in range(len(a)):
if a[i] != b[i]:
failed(a, b, "elements are different")
def compare_containers(pythonlist, swigarray):
compare_sequences(pythonlist, swigarray)
def steps_exception(swigarray, i, j, step):
try:
if i == None and j == None:
a = swigarray[::step]
elif i == None:
a = swigarray[:j:step]
elif j == None:
a = swigarray[i::step]
else:
a = swigarray[i:j:step]
raise RuntimeError, "swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed steps exception for " + str(list(swigarray))
except ValueError, e:
# print("exception: {}".format(e))
pass
def del_exception(swigarray, i, j, step):
try:
if i == None and j == None:
del swigarray[::step]
elif j == None and step == None:
del swigarray[i]
elif i == None:
del swigarray[:j:step]
elif j == None:
del swigarray[i::step]
else:
del swigarray[i:j:step]
raise RuntimeError, "swigarray[" + str(i) + ":" + str(j) + ":" + str(step) + "] missed del exception for " + str(list(swigarray))
except ValueError, e:
# print("exception: {}".format(e))
pass
def setslice_exception(swigarray, newval):
try:
swigarray[::] = newval
raise RuntimeError, "swigarray[::] = " + str(newval) + " missed set exception for swigarray:" + str(list(swigarray))
except TypeError, e:
# print("exception: {}".format(e))
pass
# Check std::array has similar behaviour to a Python list
# except it is not resizable
ps = [0, 1, 2, 3, 4, 5]
ai = ArrayInt6(ps)
compare_containers(ps, ai)
# slices
compare_containers(ps[0:6], ai[0:6])
compare_containers(ps[0:10], ai[0:10])
compare_containers(ps[-10:6], ai[-10:6])
compare_containers(ps[-10:10], ai[-10:10])
compare_containers(ps[0:6:1], ai[0:6:1])
compare_containers(ps[::], ai[::])
compare_containers(ps[::1], ai[::1])
compare_containers([x for x in ps], [x for x in ai])
# Reverse
compare_containers(ps[::-1], ai[::-1])
compare_containers(ps[5::-1], ai[5::-1])
compare_containers(ps[10::-1], ai[10::-1])
# Steps other than +1 and -1 not supported
steps_exception(ai, 0, 6, 3)
steps_exception(ai, None, None, 0)
steps_exception(ai, None, None, 2)
steps_exception(ai, None, None, -2)
steps_exception(ai, 1, 3, 1)
steps_exception(ai, 3, 1, -1)
# Modify content
for i in range(len(ps)):
ps[i] = (ps[i] + 1) * 10
ai[i] = (ai[i] + 1) * 10
compare_containers(ps, ai)
# Delete
del_exception(ai, 0, 6, 3)
del_exception(ai, None, None, 0)
del_exception(ai, None, None, 2)
del_exception(ai, None, None, -2)
del_exception(ai, 1, 3, 1)
del_exception(ai, 3, 1, -1)
del_exception(ai, 0, None, None)
del_exception(ai, 5, None, None)
# Empty
ai = ArrayInt6()
compare_containers([0, 0, 0, 0, 0, 0], ai)
# Set slice
newvals = [10, 20, 30, 40, 50, 60]
ai[::] = newvals
compare_containers(ai, newvals)
newvals = [100, 200, 300, 400, 500, 600]
ai[0:6:1] = newvals
compare_containers(ai, newvals)
newvals = [1000, 2000, 3000, 4000, 5000, 6000]
ai[::-1] = newvals
compare_containers(ai, newvals[::-1])
newvals = [10000, 20000, 30000, 40000, 50000, 60000]
ai[-10:100:1] = newvals
compare_containers(ai, newvals[-10:100:1])
setslice_exception(ai, [1, 2, 3, 4, 5, 6, 7])
setslice_exception(ai, [1, 2, 3, 4, 5])
setslice_exception(ai, [1, 2, 3, 4])
setslice_exception(ai, [1, 2, 3])
setslice_exception(ai, [1, 2])
setslice_exception(ai, [1])
setslice_exception(ai, [])
# Check return
compare_containers(arrayOutVal(), [-2, -1, 0, 0, 1, 2])
compare_containers(arrayOutConstRef(), [-2, -1, 0, 0, 1, 2])
compare_containers(arrayOutRef(), [-2, -1, 0, 0, 1, 2])
compare_containers(arrayOutPtr(), [-2, -1, 0, 0, 1, 2])
# Check passing arguments
ai = arrayInVal([9, 8, 7, 6, 5, 4])
compare_containers(ai, [90, 80, 70, 60, 50, 40])
ai = arrayInConstRef([9, 8, 7, 6, 5, 4])
compare_containers(ai, [90, 80, 70, 60, 50, 40])
ai = ArrayInt6([9, 8, 7, 6, 5, 4])
arrayInRef(ai)
compare_containers(ai, [90, 80, 70, 60, 50, 40])
ai = ArrayInt6([9, 8, 7, 6, 5, 4])
arrayInPtr(ai)
compare_containers(ai, [90, 80, 70, 60, 50, 40])
# fill
ai.fill(111)
compare_containers(ai, [111, 111, 111, 111, 111, 111])
from cpp11_strongly_typed_enumerations import *
def enumCheck(actual, expected):
if actual != expected:
raise RuntimeError(
"Enum value mismatch. Expected " + str(expected) + " Actual: " + str(actual))
return expected + 1
val = 0
val = enumCheck(Enum1_Val1, val)
val = enumCheck(Enum1_Val2, val)
val = enumCheck(Enum1_Val3, 13)
val = enumCheck(Enum1_Val4, val)
val = enumCheck(Enum1_Val5a, 13)
val = enumCheck(Enum1_Val6a, val)
val = 0
val = enumCheck(Enum2_Val1, val)
val = enumCheck(Enum2_Val2, val)
val = enumCheck(Enum2_Val3, 23)
val = enumCheck(Enum2_Val4, val)
val = enumCheck(Enum2_Val5b, 23)
val = enumCheck(Enum2_Val6b, val)
val = 0
val = enumCheck(Val1, val)
val = enumCheck(Val2, val)
val = enumCheck(Val3, 43)
val = enumCheck(Val4, val)
val = 0
val = enumCheck(Enum5_Val1, val)
val = enumCheck(Enum5_Val2, val)
val = enumCheck(Enum5_Val3, 53)
val = enumCheck(Enum5_Val4, val)
val = 0
val = enumCheck(Enum6_Val1, val)
val = enumCheck(Enum6_Val2, val)
val = enumCheck(Enum6_Val3, 63)
val = enumCheck(Enum6_Val4, val)
val = 0
val = enumCheck(Enum7td_Val1, val)
val = enumCheck(Enum7td_Val2, val)
val = enumCheck(Enum7td_Val3, 73)
val = enumCheck(Enum7td_Val4, val)
val = 0
val = enumCheck(Enum8_Val1, val)
val = enumCheck(Enum8_Val2, val)
val = enumCheck(Enum8_Val3, 83)
val = enumCheck(Enum8_Val4, val)
val = 0
val = enumCheck(Enum10_Val1, val)
val = enumCheck(Enum10_Val2, val)
val = enumCheck(Enum10_Val3, 103)
val = enumCheck(Enum10_Val4, val)
val = 0
val = enumCheck(Class1.Enum12_Val1, 1121)
val = enumCheck(Class1.Enum12_Val2, 1122)
val = enumCheck(Class1.Enum12_Val3, val)
val = enumCheck(Class1.Enum12_Val4, val)
val = enumCheck(Class1.Enum12_Val5c, 1121)
val = enumCheck(Class1.Enum12_Val6c, val)
val = 0
val = enumCheck(Class1.Val1, 1131)
val = enumCheck(Class1.Val2, 1132)
val = enumCheck(Class1.Val3, val)
val = enumCheck(Class1.Val4, val)
val = enumCheck(Class1.Val5d, 1131)
val = enumCheck(Class1.Val6d, val)
val = 0
val = enumCheck(Class1.Enum14_Val1, 1141)
val = enumCheck(Class1.Enum14_Val2, 1142)
val = enumCheck(Class1.Enum14_Val3, val)
val = enumCheck(Class1.Enum14_Val4, val)
val = enumCheck(Class1.Enum14_Val5e, 1141)
val = enumCheck(Class1.Enum14_Val6e, val)
# Requires nested class support to work
#val = 0
#val = enumCheck(Class1.Struct1.Enum12_Val1, 3121)
#val = enumCheck(Class1.Struct1.Enum12_Val2, 3122)
#val = enumCheck(Class1.Struct1.Enum12_Val3, val)
#val = enumCheck(Class1.Struct1.Enum12_Val4, val)
#val = enumCheck(Class1.Struct1.Enum12_Val5f, 3121)
#val = enumCheck(Class1.Struct1.Enum12_Val6f, val)
#
#val = 0
#val = enumCheck(Class1.Struct1.Val1, 3131)
#val = enumCheck(Class1.Struct1.Val2, 3132)
#val = enumCheck(Class1.Struct1.Val3, val)
#val = enumCheck(Class1.Struct1.Val4, val)
#
#val = 0
#val = enumCheck(Class1.Struct1.Enum14_Val1, 3141)
#val = enumCheck(Class1.Struct1.Enum14_Val2, 3142)
#val = enumCheck(Class1.Struct1.Enum14_Val3, val)
#val = enumCheck(Class1.Struct1.Enum14_Val4, val)
#val = enumCheck(Class1.Struct1.Enum14_Val5g, 3141)
#val = enumCheck(Class1.Struct1.Enum14_Val6g, val)
val = 0
val = enumCheck(Class2.Enum12_Val1, 2121)
val = enumCheck(Class2.Enum12_Val2, 2122)
val = enumCheck(Class2.Enum12_Val3, val)
val = enumCheck(Class2.Enum12_Val4, val)
val = enumCheck(Class2.Enum12_Val5h, 2121)
val = enumCheck(Class2.Enum12_Val6h, val)
val = 0
val = enumCheck(Class2.Val1, 2131)
val = enumCheck(Class2.Val2, 2132)
val = enumCheck(Class2.Val3, val)
val = enumCheck(Class2.Val4, val)
val = enumCheck(Class2.Val5i, 2131)
val = enumCheck(Class2.Val6i, val)
val = 0
val = enumCheck(Class2.Enum14_Val1, 2141)
val = enumCheck(Class2.Enum14_Val2, 2142)
val = enumCheck(Class2.Enum14_Val3, val)
val = enumCheck(Class2.Enum14_Val4, val)
val = enumCheck(Class2.Enum14_Val5j, 2141)
val = enumCheck(Class2.Enum14_Val6j, val)
# Requires nested class support to work
#val = 0
#val = enumCheck(Class2.Struct1.Enum12_Val1, 4121)
#val = enumCheck(Class2.Struct1.Enum12_Val2, 4122)
#val = enumCheck(Class2.Struct1.Enum12_Val3, val)
#val = enumCheck(Class2.Struct1.Enum12_Val4, val)
#val = enumCheck(Class2.Struct1.Enum12_Val5k, 4121)
#val = enumCheck(Class2.Struct1.Enum12_Val6k, val)
#
#val = 0
#val = enumCheck(Class2.Struct1.Val1, 4131)
#val = enumCheck(Class2.Struct1.Val2, 4132)
#val = enumCheck(Class2.Struct1.Val3, val)
#val = enumCheck(Class2.Struct1.Val4, val)
#val = enumCheck(Class2.Struct1.Val5l, 4131)
#val = enumCheck(Class2.Struct1.Val6l, val)
#
#val = 0
#val = enumCheck(Class2.Struct1.Enum14_Val1, 4141)
#val = enumCheck(Class2.Struct1.Enum14_Val2, 4142)
#val = enumCheck(Class2.Struct1.Enum14_Val3, val)
#val = enumCheck(Class2.Struct1.Enum14_Val4, val)
#val = enumCheck(Class2.Struct1.Enum14_Val5m, 4141)
#val = enumCheck(Class2.Struct1.Enum14_Val6m, val)
class1 = Class1()
enumCheck(class1.class1Test1(Enum1_Val5a), 13)
enumCheck(class1.class1Test2(Class1.Enum12_Val5c), 1121)
#enumCheck(class1.class1Test3(Class1.Struct1.Enum12_Val5f), 3121)
enumCheck(globalTest1(Enum1_Val5a), 13)
enumCheck(globalTest2(Class1.Enum12_Val5c), 1121)
#enumCheck(globalTest3(Class1.Struct1.Enum12_Val5f), 3121)
from cpp11_template_typedefs import *
t = create_TypedefName()
if type(t).__name__ != "SomeTypeInt5":
raise RuntimeError("type(t) is '%s' and should be 'SomeTypeInt5'" % type(t).__name__)
if t.a != "hello":
raise RuntimeError("t.a should be 'hello'")
if t.b != 10:
raise RuntimeError("t.b should be 10")
if t.get_n() != 5:
raise RuntimeError("t.get_n() should be 5")
t_bool = create_TypedefNameBool()
if type(t_bool).__name__ != "SomeTypeBool5":
raise RuntimeError("type(t_bool) is '%s' and should be 'SomeTypeBool5'" % type(t_bool).__name__)
if t_bool.a != "hello":
raise RuntimeError("t_bool.a should be 'hello'")
if t_bool.b != True:
raise RuntimeError("t_bool.b should be True")
if t_bool.get_n() != 15:
raise RuntimeError("t_bool.get_n() should be 15")
if get_SomeType_b(t) != 10:
raise RuntimeError("get_SomeType_b(t) should be 10")
if get_SomeType_b2(t) != 10:
raise RuntimeError("get_SomeType_b2(t) should be 10")
t2 = SomeTypeInt4()
t2.b = 0
t3 = identity(t2)
t3.b = 5
if t2.b != 5:
raise RuntimeError("t2.b should be 5")
if get_bucket_allocator1() != 1:
raise RuntimeError("bucket_allocator1 should be 1")
# SWIG doesn't handle ::MyClass as a template argument. Skip this test.
#if get_bucket_allocator2() != 2:
# raise RuntimeError("bucket_allocator2 should be 2")
from cpp11_thread_local import *
t = ThreadLocals()
if t.stval != 11:
raise RuntimeError
if t.tsval != 22:
raise RuntimeError
if t.tscval99 != 99:
raise RuntimeError
cvar.etval = -11
if cvar.etval != -11:
raise RuntimeError
cvar.stval = -22
if cvar.stval != -22:
raise RuntimeError
cvar.tsval = -33
if cvar.tsval != -33:
raise RuntimeError
cvar.etval = -44
if cvar.etval != -44:
raise RuntimeError
cvar.teval = -55
if cvar.teval != -55:
raise RuntimeError
cvar.ectval = -66
if cvar.ectval != -66:
raise RuntimeError
cvar.ecpptval = -66
if cvar.ecpptval != -66:
raise RuntimeError
from cpp11_type_aliasing import *
if get_host_target().bits != 32:
raise RuntimeError("get_host_target().bits should return 32")
if mult2(10) != 20:
raise RuntimeError("mult2(10) should return 20")
int_ptr = allocate_int()
inplace_mult2(int_ptr)
if read_int(int_ptr) != 24:
raise RuntimeError("read_int should return 24")
free_int(int_ptr)
pair = PairSubclass(3, 4)
if pair.first() != 3:
raise RuntimeError("pair.first() should return 3")
if pair.second() != 4:
raise RuntimeError("pair.second() should return 4")
if pair.a != 3:
raise RuntimeError("pair.a should be 3")
if plus1(5) != 6:
raise RuntimeError("plus1(5) should return 6")
if call(mult2_cb, 7) != 14:
raise RuntimeError("call(mult2_cb, 7) should return 14")
if call(get_callback(), 7) != 14:
raise RuntimeError("call(get_callback(), 7) should return 14")
from cpp11_type_traits import *
if Elaborate(0, 0) != 1:
raise RuntimeError("Elaborate should have returned 1")
if Elaborate(0, 0.0) != 2:
raise RuntimeError("Elaborate should have returned 2")
import cpp11_uniform_initialization
var1 = cpp11_uniform_initialization.cvar.var1
if var1.x != 5:
raise RuntimeError
var2 = cpp11_uniform_initialization.cvar.var2
if var2.getX() != 2:
raise RuntimeError
m = cpp11_uniform_initialization.MoreInit()
if m.charptr != None:
raise RuntimeError, m.charptr
m.charptr = "hello sir"
if m.charptr != "hello sir":
raise RuntimeError, m.charptr
if m.more1(m.vi) != 15:
raise RuntimeError, m.vi
if m.more1([-1, 1, 2]) != 2:
raise RuntimeError, m.vi
if m.more1() != 10:
raise RuntimeError
from cpp14_binary_integer_literals import *
if cvar.b1 != 1:
raise RuntimeError
if cvar.b2 != 2:
raise RuntimeError
if cvar.b3 != 3:
raise RuntimeError
if cvar.b4 != 4:
raise RuntimeError
if cvar.b5 != 5:
raise RuntimeError
from cpp17_hex_floating_literals import *
if cvar.f1 != 0.:
raise RuntimeError
if cvar.f2 != 0.:
raise RuntimeError
if cvar.f3 != 0.:
raise RuntimeError
if cvar.f4 != 7.5:
raise RuntimeError
if cvar.f5 != 20.:
raise RuntimeError
if cvar.f6 != 64.:
raise RuntimeError
if cvar.f7 != 11452.:
raise RuntimeError
if cvar.f8 != 149140.:
raise RuntimeError
if cvar.f9 != 18253638.:
raise RuntimeError
from cpp17_nested_namespaces import *
A1Struct().A1Method()
B1Struct().B1Method()
C1Struct().C1Method()
createA1Struct().A1Method()
createB1Struct().B1Method()
createC1Struct().C1Method()
B2Struct().B2Method()
C2Struct().C2Method()
createB2Struct().B2Method()
createC2Struct().C2Method()
B3Struct().B3Method()
C3Struct().C3Method()
createB3Struct().B3Method()
createC3Struct().C3Method()
from cpp17_u8_char_literals import *
if cvar.a != "a":
raise RuntimeError
if cvar.u != "u":
raise RuntimeError
if cvar.u8 != "8":
raise RuntimeError
import cpp_enum
f = cpp_enum.Foo()
if f.hola != f.Hello:
print f.hola
raise RuntimeError
f.hola = f.Hi
if f.hola != f.Hi:
print f.hola
raise RuntimeError
f.hola = f.Hello
if f.hola != f.Hello:
print f.hola
raise RuntimeError
cpp_enum.cvar.hi = cpp_enum.Hello
if cpp_enum.cvar.hi != cpp_enum.Hello:
print cpp_enum.cvar.hi
raise RuntimeError
# Note: This example assumes that namespaces are flattened
import cpp_namespace
n = cpp_namespace.fact(4)
if n != 24:
raise RuntimeError("Bad return value!")
if cpp_namespace.cvar.Foo != 42:
raise RuntimeError("Bad variable value!")
t = cpp_namespace.Test()
if t.method() != "Test::method":
raise RuntimeError("Bad method return value!")
if cpp_namespace.do_method(t) != "Test::method":
raise RuntimeError("Bad return value!")
if cpp_namespace.do_method2(t) != "Test::method":
raise RuntimeError("Bad return value!")
cpp_namespace.weird("hello", 4)
del t
t2 = cpp_namespace.Test2()
t3 = cpp_namespace.Test3()
t4 = cpp_namespace.Test4()
t5 = cpp_namespace.Test5()
if cpp_namespace.foo3(42) != 42:
raise RuntimeError("Bad return value!")
if cpp_namespace.do_method3(t2, 40) != "Test2::method":
raise RuntimeError("Bad return value!")
if cpp_namespace.do_method3(t3, 40) != "Test3::method":
raise RuntimeError("Bad return value!")
if cpp_namespace.do_method3(t4, 40) != "Test4::method":
raise RuntimeError("Bad return value!")
if cpp_namespace.do_method3(t5, 40) != "Test5::method":
raise RuntimeError("Bad return value!")
from cpp_parameters import *
# Testing correct and incorrect parameter counts being passed (kwargs and non-kwargs)
# Note that the implementation depends a lot on whether zero, one, two or more args are being wrapped
def is_python_fastproxy():
"""Return True if SWIG is generating Python code using -fastproxy."""
import cpp_parameters
# Note: _swig_new_instance_method is only generated when using -fastproxy
return hasattr(cpp_parameters, "_swig_new_instance_method")
# Zero parameters expected
x = Zero()
try:
x = Zero(z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x = Zero(0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.zero(z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.zero(0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Zero.stat_zero(z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Zero.stat_zero(0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_zero(z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_zero(0)
raise RuntimeError("Missed throw")
except TypeError:
pass
# One mandatory parameter expected
x = One(1)
try:
x = One(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x = One(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.one(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.one(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
One.stat_one(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
One.stat_one(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_one(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_one(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
# Two mandatory parameters expected
x = Two(1, 2)
try:
x = Two(a=1, b=2, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x = Two(1, 2, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.two(a=1, b=2, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.two(1, 2, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Two.stat_two(a=1, b=2, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Two.stat_two(1, 2, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_two(a=1, b=2, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_two(1, 2, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
# Single optional parameter expected
x = Single(1)
try:
x = Single(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x = Single(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.single(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.single(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Single.stat_single(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Single.stat_single(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_single(a=1, z=0)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_single(1, 0)
raise RuntimeError("Missed throw")
except TypeError:
pass
# Test that -builtin option throws TypeError if kwargs are used even when they look like they should work, kwargs are not supported unless using -keyword.
# Also same for -fastproxy option except that kwargs are supported by default for constructors. TODO: Fix inconsistency.
if is_python_builtin() or is_python_fastproxy():
# One mandatory parameter in API
x = One(1)
if is_python_fastproxy():
x = One(a=1)
else:
try:
x = One(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.one(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
One.stat_one(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_one(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
# Two mandatory parameters in API
x = Two(1, 2)
if is_python_fastproxy():
x = Two(a=1, b=2)
else:
try:
x = Two(a=1, b=2)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.two(a=1, b=2)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Two.stat_two(a=1, b=2)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_two(a=1, b=2)
raise RuntimeError("Missed throw")
except TypeError:
pass
# Single optional parameter in API
x = Single(1)
if is_python_fastproxy():
x = Single(a=1)
else:
try:
x = Single(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
x.single(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
Single.stat_single(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
try:
global_single(a=1)
raise RuntimeError("Missed throw")
except TypeError:
pass
else:
# Non-builtin should work as expected
# One mandatory parameter in API
x = One(a=1)
x.one(a=1)
One.stat_one(a=1)
global_one(a=1)
# Two mandatory parameters in API
x = Two(a=1, b=2)
x.two(a=1, b=2)
Two.stat_two(a=1, b=2)
global_two(a=1, b=2)
# Single optional parameter in API
x = Single(a=1)
x.single(a=1)
Single.stat_single(a=1)
global_single(a=1)
#!/usr/bin/evn python
from cpp_static import *
StaticFunctionTest.static_func()
StaticFunctionTest.static_func_2(1)
StaticFunctionTest.static_func_3(1, 2)
if is_python_builtin():
if not StaticMemberTest.static_int == 99: raise RuntimeError("static_int not 99")
if not StaticMemberTest.grab_int() == 99: raise RuntimeError("static_int not 99")
StaticMemberTest.static_int = 10
if not StaticMemberTest.static_int == 10: raise RuntimeError("static_int not 10")
if not StaticMemberTest.grab_int() == 10: raise RuntimeError("static_int not 10")
if not StaticBase.statty == 11: raise RuntimeError("statty not 11")
if not StaticBase.grab_statty_base() == 11: raise RuntimeError("statty not 11")
if not StaticDerived.statty == 111: raise RuntimeError("statty not 111")
if not StaticDerived.grab_statty_derived() == 111: raise RuntimeError("statty not 111")
StaticBase.statty = 22
StaticDerived.statty = 222
if not StaticBase.statty == 22: raise RuntimeError("statty not 22")
if not StaticBase.grab_statty_base() == 22: raise RuntimeError("statty not 22")
if not StaticDerived.statty == 222: raise RuntimeError("statty not 222")
if not StaticDerived.grab_statty_derived() == 222: raise RuntimeError("statty not 222")
# Restore
StaticMemberTest.static_int = 99
StaticBase.statty = 11
StaticDerived.statty = 111
if not cvar.StaticMemberTest_static_int == 99: raise RuntimeError("cvar static_int not 99")
if not StaticMemberTest.grab_int() == 99: raise RuntimeError("cvar static_int not 99")
cvar.StaticMemberTest_static_int = 10
if not cvar.StaticMemberTest_static_int == 10: raise RuntimeError("cvar static_int not 10")
if not StaticMemberTest.grab_int() == 10: raise RuntimeError("cvar static_int not 10")
if not cvar.StaticBase_statty == 11: raise RuntimeError("cvar statty not 11")
if not StaticBase.grab_statty_base() == 11: raise RuntimeError("cvar statty not 11")
if not cvar.StaticDerived_statty == 111: raise RuntimeError("cvar statty not 111")
if not StaticDerived.grab_statty_derived() == 111: raise RuntimeError("cvar statty not 111")
cvar.StaticBase_statty = 22
cvar.StaticDerived_statty = 222
if not cvar.StaticBase_statty == 22: raise RuntimeError("cvar statty not 22")
if not StaticBase.grab_statty_base() == 22: raise RuntimeError("cvar statty not 22")
if not cvar.StaticDerived_statty == 222: raise RuntimeError("cvar statty not 222")
if not StaticDerived.grab_statty_derived() == 222: raise RuntimeError("cvar statty not 222")
# Restore
cvar.StaticMemberTest_static_int = 99
cvar.StaticBase_statty = 11
cvar.StaticDerived_statty = 111
# Low-level layer testing
if not is_python_builtin():
from cpp_static import _cpp_static
if not _cpp_static.StaticMemberTest_static_int_get() == 99: raise RuntimeError("low-level static_int not 99")
if not StaticMemberTest.grab_int() == 99: raise RuntimeError("low-level static_int not 99")
_cpp_static.StaticMemberTest_static_int_set(10)
if not _cpp_static.StaticMemberTest_static_int_get() == 10: raise RuntimeError("low-level static_int not 10")
if not StaticMemberTest.grab_int() == 10: raise RuntimeError("low-level static_int not 10")
if not _cpp_static.StaticBase_statty_get() == 11: raise RuntimeError("low-level statty not 11")
if not StaticBase.grab_statty_base() == 11: raise RuntimeError("low-level statty not 11")
if not _cpp_static.StaticDerived_statty_get() == 111: raise RuntimeError("low-level statty not 111")
if not StaticDerived.grab_statty_derived() == 111: raise RuntimeError("low-level statty not 111")
_cpp_static.StaticBase_statty_set(22)
_cpp_static.StaticDerived_statty_set(222)
if not _cpp_static.StaticBase_statty_get() == 22: raise RuntimeError("low-level statty not 22")
if not StaticBase.grab_statty_base() == 22: raise RuntimeError("low-level statty not 22")
if not _cpp_static.StaticDerived_statty_get() == 222: raise RuntimeError("low-level statty not 222")
if not StaticDerived.grab_statty_derived() == 222: raise RuntimeError("low-level statty not 222")
import default_args_c
if default_args_c.foo1() != 1:
raise RuntimeError("failed")
if default_args_c.foo43() != 43:
raise RuntimeError("failed")
f = default_args_c.FooStruct()
f.no_arg()
f.one_req(None)
f.one_opt()
f.one_opt(None)
f.two_arg(None)
f.two_arg(None, None)
default_args_c.StaticStruct.no_arg()
default_args_c.StaticStruct.one_req(None)
default_args_c.StaticStruct.one_opt()
default_args_c.StaticStruct.one_opt(None)
default_args_c.StaticStruct.two_arg(None)
default_args_c.StaticStruct.two_arg(None, None)
default_args_c.global_opts1()
default_args_c.global_opts1(None)
default_args_c.global_opts2(None)
default_args_c.global_opts2(None, None)
# Note that this test is also used by python_default_args_runme.py hence
# the use of __main__ and the run function
def run(module_name):
default_args = __import__(module_name)
ec = default_args.EnumClass()
if not ec.blah():
raise RuntimeError("EnumClass::blah() default arguments don't work")
de = default_args.DerivedEnumClass()
de.accelerate()
de.accelerate(default_args.EnumClass.SLOW)
if default_args.Statics_staticMethod() != 60:
raise RuntimeError
if default_args.cfunc1(1) != 2:
raise RuntimeError
if default_args.cfunc2(1) != 3:
raise RuntimeError
if default_args.cfunc3(1) != 4:
raise RuntimeError
f = default_args.Foo()
f.newname()
f.newname(1)
f.defaulted1()
f.defaulted2()
if f.double_if_void_ptr_is_null(2, None) != 4:
raise RuntimeError
if f.double_if_void_ptr_is_null(3) != 6:
raise RuntimeError
if f.double_if_handle_is_null(4, None) != 8:
raise RuntimeError
if f.double_if_handle_is_null(5) != 10:
raise RuntimeError
if f.double_if_dbl_ptr_is_null(6, None) != 12:
raise RuntimeError
if f.double_if_dbl_ptr_is_null(7) != 14:
raise RuntimeError
try:
f = default_args.Foo(1)
error = 1
except:
error = 0
if error:
raise RuntimeError("Foo::Foo ignore is not working")
try:
f = default_args.Foo(1, 2)
error = 1
except:
error = 0
if error:
raise RuntimeError("Foo::Foo ignore is not working")
try:
f = default_args.Foo(1, 2, 3)
error = 1
except:
error = 0
if error:
raise RuntimeError("Foo::Foo ignore is not working")
try:
m = f.meth(1)
error = 1
except:
error = 0
if error:
raise RuntimeError("Foo::meth ignore is not working")
try:
m = f.meth(1, 2)
error = 1
except:
error = 0
if error:
raise RuntimeError("Foo::meth ignore is not working")
try:
m = f.meth(1, 2, 3)
error = 1
except:
error = 0
if error:
raise RuntimeError("Foo::meth ignore is not working")
Klass_inc = default_args.Klass.inc
if Klass_inc(100, default_args.Klass(22)).val != 122:
raise RuntimeError("Klass::inc failed")
if Klass_inc(100).val != 99:
raise RuntimeError("Klass::inc failed")
if Klass_inc().val != 0:
raise RuntimeError("Klass::inc failed")
tricky_failure = False
tricky = default_args.TrickyInPython()
if tricky.value_m1(10) != -1:
print "trickyvalue_m1 failed"
tricky_failure = True
if tricky.value_m1(10, 10) != 10:
print "trickyvalue_m1 failed"
tricky_failure = True
if tricky.value_0xabcdef(10) != 0xabcdef:
print "trickyvalue_0xabcdef failed"
tricky_failure = True
if tricky.value_0644(10) != 420:
print "trickyvalue_0644 failed"
tricky_failure = True
if tricky.value_perm(10) != 420:
print "trickyvalue_perm failed"
tricky_failure = True
if tricky.value_m01(10) != -1:
print "trickyvalue_m01 failed"
tricky_failure = True
if not tricky.booltest2():
print "booltest2 failed"
tricky_failure = True
if tricky.max_32bit_int1() != 0x7FFFFFFF:
print "max_32bit_int1 failed"
tricky_failure = True
if tricky.min_32bit_int1() != -2147483648:
print "min_32bit_int1 failed"
tricky_failure = True
if tricky.max_32bit_int2() != 0x7FFFFFFF:
print "max_32bit_int2 failed"
tricky_failure = True
tricky.too_big_32bit_int1()
tricky.too_small_32bit_int1()
tricky.too_big_32bit_int2()
tricky.too_small_32bit_int2()
if tricky_failure:
raise RuntimeError
default_args.seek()
default_args.seek(10)
if not default_args.booltest():
raise RuntimeError("booltest failed")
if default_args.slightly_off_square(10) != 102:
raise RuntimeError
if default_args.slightly_off_square() != 291:
raise RuntimeError
# It is difficult to test the python:cdefaultargs feature properly as -builtin
# and -fastproxy do not use the Python layer for default args
if default_args.CDA().cdefaultargs_test1() != 1:
raise RuntimeError
if default_args.CDA().cdefaultargs_test2() != 1:
raise RuntimeError
if default_args.chartest1() != "x":
raise RuntimeError
if default_args.chartest2() != "\0":
raise RuntimeError
if default_args.chartest3() != "\1":
raise RuntimeError
if default_args.chartest4() != "\n":
raise RuntimeError
if default_args.chartest5() != "B":
raise RuntimeError
if default_args.chartest6() != "C":
raise RuntimeError
if __name__ == "__main__":
run("default_args")
from default_arg_values import *
d = Display()
if d.draw1() != 0:
raise RuntimeError
if d.draw1(12) != 12:
raise RuntimeError
p = createPtr(123)
if d.draw2() != 0:
raise RuntimeError
if d.draw2(p) != 123:
raise RuntimeError
if d.bool0() != False or type(d.bool0()) != type(False):
raise RuntimeError
if d.bool1() != True or type(d.bool1()) != type(True):
raise RuntimeError
if d.mybool0() != False or type(d.mybool0()) != type(False):
raise RuntimeError
if d.mybool1() != True or type(d.mybool1()) != type(True):
raise RuntimeError
import _default_constructor
# This test is expected to fail with -builtin option.
# It uses the old static syntax (e.g., dc.new_A() rather than dc.A()),
# which is not provided with the -builtin option.
if _default_constructor.is_python_builtin():
exit(0)
dc = _default_constructor
a = dc.new_A()
dc.delete_A(a)
aa = dc.new_AA()
dc.delete_AA(aa)
try:
b = dc.new_B()
print "Whoa. new_BB created."
except:
pass
del_b = dc.delete_B
try:
bb = dc.new_BB()
print "Whoa. new_BB created."
except:
pass
del_bb = dc.delete_BB
try:
c = dc.new_C()
print "Whoa. new_C created."
except:
pass
del_c = dc.delete_C
cc = dc.new_CC()
dc.delete_CC(cc)
try:
d = dc.new_D()
print "Whoa. new_D created"
except:
pass
del_d = dc.delete_D
try:
dd = dc.new_DD()
print "Whoa. new_DD created"
except:
pass
dd = dc.delete_DD
try:
ad = dc.new_AD()
print "Whoa. new_AD created"
except:
pass
del_ad = dc.delete_AD
e = dc.new_E()
dc.delete_E(e)
ee = dc.new_EE()
dc.delete_EE(ee)
try:
eb = dc.new_EB()
print "Whoa. new_EB created"
except:
pass
del_eb = dc.delete_EB
f = dc.new_F()
try:
del_f = dc.delete_F
print "Whoa. delete_F created"
except AttributeError:
pass
dc.F_destroy(f)
g = dc.new_G()
try:
del_g = dc.delete_G
print "Whoa. delete_G created"
except AttributeError:
pass
dc.G_destroy(g)
gg = dc.new_GG()
dc.delete_GG(gg)
import default_constructor
hh = default_constructor.HH(1, 1)
import director_abstract
class MyFoo(director_abstract.Foo):
def __init__(self):
director_abstract.Foo.__init__(self)
def ping(self):
return "MyFoo::ping()"
a = MyFoo()
if a.ping() != "MyFoo::ping()":
raise RuntimeError, a.ping()
if a.pong() != "Foo::pong();MyFoo::ping()":
raise RuntimeError, a.pong()
class MyExample1(director_abstract.Example1):
def Color(self, r, g, b):
return r
class MyExample2(director_abstract.Example2):
def Color(self, r, g, b):
return g
class MyExample3(director_abstract.Example3_i):
def Color(self, r, g, b):
return b
me1 = MyExample1()
if director_abstract.Example1_get_color(me1, 1, 2, 3) != 1:
raise RuntimeError
me2 = MyExample2(1, 2)
if MyExample2.get_color(me2, 1, 2, 3) != 2:
raise RuntimeError
me3 = MyExample3()
if MyExample3.get_color(me3, 1, 2, 3) != 3:
raise RuntimeError
error = 1
try:
me1 = director_abstract.Example1()
except:
error = 0
if (error):
raise RuntimeError
error = 1
try:
me2 = director_abstract.Example2()
except:
error = 0
if (error):
raise RuntimeError
error = 1
try:
me3 = director_abstract.Example3_i()
except:
error = 0
if (error):
raise RuntimeError
try:
f = director_abstract.A.f
except:
raise RuntimeError
from director_alternating import *
id = getBar().id()
if id != idFromGetBar():
raise RuntimeError, "Got wrong id: " + str(id)
import director_basic
class PyFoo(director_basic.Foo):
def ping(self):
return "PyFoo::ping()"
a = PyFoo()
if a.ping() != "PyFoo::ping()":
raise RuntimeError, a.ping()
if a.pong() != "Foo::pong();PyFoo::ping()":
raise RuntimeError, a.pong()
b = director_basic.Foo()
if b.ping() != "Foo::ping()":
raise RuntimeError, b.ping()
if b.pong() != "Foo::pong();Foo::ping()":
raise RuntimeError, b.pong()
a = director_basic.A1(1)
if a.rg(2) != 2:
raise RuntimeError
class PyClass(director_basic.MyClass):
def method(self, vptr):
self.cmethod = 7
pass
def vmethod(self, b):
b.x = b.x + 31
return b
b = director_basic.Bar(3)
d = director_basic.MyClass()
c = PyClass()
cc = director_basic.MyClass_get_self(c)
dd = director_basic.MyClass_get_self(d)
bc = cc.cmethod(b)
bd = dd.cmethod(b)
cc.method(b)
if c.cmethod != 7:
raise RuntimeError
if bc.x != 34:
raise RuntimeError
if bd.x != 16:
raise RuntimeError
class PyMulti(director_basic.Foo, director_basic.MyClass):
def __init__(self):
director_basic.Foo.__init__(self)
director_basic.MyClass.__init__(self)
pass
def vmethod(self, b):
b.x = b.x + 31
return b
def ping(self):
return "PyFoo::ping()"
a = 0
for i in range(0, 100):
pymult = PyMulti()
pymult.pong()
del pymult
pymult = PyMulti()
p1 = director_basic.Foo_get_self(pymult)
p2 = director_basic.MyClass_get_self(pymult)
p1.ping()
p2.vmethod(bc)
from director_classic import *
class TargetLangPerson(Person):
def __init__(self):
Person.__init__(self)
def id(self):
identifier = "TargetLangPerson"
return identifier
class TargetLangChild(Child):
def __init__(self):
Child.__init__(self)
def id(self):
identifier = "TargetLangChild"
return identifier
class TargetLangGrandChild(GrandChild):
def __init__(self):
GrandChild.__init__(self)
def id(self):
identifier = "TargetLangGrandChild"
return identifier
# Semis - don't override id() in target language
class TargetLangSemiPerson(Person):
def __init__(self):
Person.__init__(self)
# No id() override
class TargetLangSemiChild(Child):
def __init__(self):
Child.__init__(self)
# No id() override
class TargetLangSemiGrandChild(GrandChild):
def __init__(self):
GrandChild.__init__(self)
# No id() override
# Orphans - don't override id() in C++
class TargetLangOrphanPerson(OrphanPerson):
def __init__(self):
OrphanPerson.__init__(self)
def id(self):
identifier = "TargetLangOrphanPerson"
return identifier
class TargetLangOrphanChild(OrphanChild):
def __init__(self):
OrphanChild.__init__(self)
def id(self):
identifier = "TargetLangOrphanChild"
return identifier
def check(person, expected):
debug = 0
# Normal target language polymorphic call
ret = person.id()
if (debug):
print(ret)
if (ret != expected):
raise RuntimeError(
"Failed. Received: " + str(ret) + " Expected: " + expected)
# Polymorphic call from C++
caller = Caller()
caller.setCallback(person)
ret = caller.call()
if (debug):
print(ret)
if (ret != expected):
raise RuntimeError(
"Failed. Received: " + str(ret) + " Expected: " + expected)
# Polymorphic call of object created in target language and passed to C++
# and back again
baseclass = caller.baseClass()
ret = baseclass.id()
if (debug):
print(ret)
if (ret != expected):
raise RuntimeError(
"Failed. Received: " + str(ret) + " Expected: " + expected)
caller.resetCallback()
if (debug):
print("----------------------------------------")
person = Person()
check(person, "Person")
del person
person = Child()
check(person, "Child")
del person
person = GrandChild()
check(person, "GrandChild")
del person
person = TargetLangPerson()
check(person, "TargetLangPerson")
del person
person = TargetLangChild()
check(person, "TargetLangChild")
del person
person = TargetLangGrandChild()
check(person, "TargetLangGrandChild")
del person
# Semis - don't override id() in target language
person = TargetLangSemiPerson()
check(person, "Person")
del person
person = TargetLangSemiChild()
check(person, "Child")
del person
person = TargetLangSemiGrandChild()
check(person, "GrandChild")
del person
# Orphans - don't override id() in C++
person = OrphanPerson()
check(person, "Person")
del person
person = OrphanChild()
check(person, "Child")
del person
person = TargetLangOrphanPerson()
check(person, "TargetLangOrphanPerson")
del person
person = TargetLangOrphanChild()
check(person, "TargetLangOrphanChild")
del person
from director_default import *
f = Foo()
f = Foo(1)
f = Bar()
f = Bar(1)
import director_detect
class MyBar(director_detect.Bar):
def __init__(self, val=2):
director_detect.Bar.__init__(self)
self.val = val
def get_value(self):
self.val = self.val + 1
return self.val
def get_class(self):
self.val = self.val + 1
return director_detect.A()
def just_do_it(self):
self.val = self.val + 1
def clone(self):
return MyBar(self.val)
pass
b = MyBar()
f = b.baseclass()
v = f.get_value()
a = f.get_class()
f.just_do_it()
c = b.clone()
vc = c.get_value()
if (v != 3) or (b.val != 5) or (vc != 6):
raise RuntimeError, "Bad virtual detection"
import director_enum
class MyFoo(director_enum.Foo):
def say_hi(self, val):
return val
b = director_enum.Foo()
a = MyFoo()
if a.say_hi(director_enum.hello) != b.say_hello(director_enum.hi):
raise RuntimeError
from director_exception import *
class MyException(Exception):
def __init__(self, a, b):
self.msg = a + b
class MyFoo(Foo):
def ping(self):
raise NotImplementedError, "MyFoo::ping() EXCEPTION"
class MyFoo2(Foo):
def ping(self):
return True
pass # error: should return a string
class MyFoo3(Foo):
def ping(self):
raise MyException("foo", "bar")
class MyFoo4(Foo):
def ping(self, *args):
print(type("bad", "call")) # throws TypeError message: type() takes 1 or 3 arguments
return "Foo4.ping"
# Check that the NotImplementedError raised by MyFoo.ping() is returned by
# MyFoo.pong().
ok = 0
a = MyFoo()
b = launder(a)
try:
b.pong()
except NotImplementedError, e:
if str(e) == "MyFoo::ping() EXCEPTION":
ok = 1
else:
print "Unexpected error message: %s" % str(e)
except:
pass
if not ok:
raise RuntimeError
# Check that the director returns the appropriate TypeError if the return type
# is wrong.
ok = 0
a = MyFoo2()
b = launder(a)
try:
b.pong()
except TypeError, e:
# fastdispatch mode adds on Additional Information to the exception message - just check the main exception message exists
if str(e).startswith("SWIG director type mismatch in output value of type 'std::string'"):
ok = 1
else:
print "Unexpected error message: %s" % str(e)
if not ok:
raise RuntimeError
# Check that the director can return an exception which requires two arguments
# to the constructor, without mangling it.
ok = 0
a = MyFoo3()
b = launder(a)
try:
b.pong()
except MyException, e:
if e.msg == "foobar":
ok = 1
else:
print "Unexpected error message: %s" % str(e)
if not ok:
raise RuntimeError
# Check that the director returns the appropriate TypeError thrown in a director method
ok = 0
a = MyFoo4()
b = launder(a)
try:
b.pong()
except TypeError as e:
if str(e).startswith("type() takes 1 or 3 arguments"):
ok = 1
else:
print "Unexpected error message: %s" % str(e)
if not ok:
raise RuntimeError
# This is expected to fail with -builtin option
# Throwing builtin classes as exceptions not supported
if not is_python_builtin():
try:
raise Exception2()
except Exception2:
pass
try:
raise Exception1()
except Exception1:
pass
# Test case from bug #1506850
#"When threading is enabled, the interpreter will infinitely wait on a mutex the second
# time this type of extended method is called. Attached is an example
# program that waits on the mutex to be unlocked."
from director_extend import *
class MyObject(SpObject):
def __init__(self):
SpObject.__init__(self)
return
def getFoo(self):
return 123
m = MyObject()
if m.dummy() != 666:
raise RuntimeError, "1st call"
if m.dummy() != 666: # Locked system
raise RuntimeError, "2nd call"
from director_finalizer import *
class MyFoo(Foo):
def __del__(self):
self.orStatus(2)
try:
Foo.__del__(self)
except:
pass
resetStatus()
a = MyFoo()
del a
if getStatus() != 3:
raise RuntimeError
resetStatus()
a = MyFoo()
launder(a)
if getStatus() != 0:
raise RuntimeError
del a
if getStatus() != 3:
raise RuntimeError
resetStatus()
a = MyFoo().__disown__()
deleteFoo(a)
if getStatus() != 3:
raise RuntimeError
resetStatus()
a = MyFoo().__disown__()
deleteFoo(launder(a))
if getStatus() != 3:
raise RuntimeError
resetStatus()
from director_frob import *
foo = Bravo()
s = foo.abs_method()
if s != "Bravo::abs_method()":
raise RuntimeError, s
from director_keywords import *
f = Foo()
f.check_self(20)
from director_nested import *
class A(FooBar_int):
def do_step(self):
return "A::do_step;"
def get_value(self):
return "A::get_value"
pass
a = A()
if a.step() != "Bar::step;Foo::advance;Bar::do_advance;A::do_step;":
raise RuntimeError, "Bad A virtual resolution"
class B(FooBar_int):
def do_advance(self):
return "B::do_advance;" + self.do_step()
def do_step(self):
return "B::do_step;"
def get_value(self):
return 1
pass
b = B()
if b.step() != "Bar::step;Foo::advance;B::do_advance;B::do_step;":
raise RuntimeError, "Bad B virtual resolution"
class C(FooBar_int):
def do_advance(self):
return "C::do_advance;" + FooBar_int.do_advance(self)
def do_step(self):
return "C::do_step;"
def get_value(self):
return 2
def get_name(self):
return FooBar_int.get_name(self) + " hello"
pass
cc = C()
c = FooBar_int_get_self(cc)
c.advance()
if c.get_name() != "FooBar::get_name hello":
raise RuntimeError
if c.name() != "FooBar::get_name hello":
raise RuntimeError
import director_pass_by_value
passByVal = None
class director_pass_by_value_Derived(director_pass_by_value.DirectorPassByValueAbstractBase):
def virtualMethod(self, b):
global passByVal
passByVal = b
# bug was the passByVal global object was destroyed after the call to virtualMethod had finished.
director_pass_by_value.Caller().call_virtualMethod(director_pass_by_value_Derived())
ret = passByVal.getVal();
if ret != 0x12345678:
raise RuntimeError("Bad return value, got " + hex(ret))
import director_profile
class MyB(director_profile.B):
def vfi(self, a):
return a + 3
a = director_profile.A()
myb = MyB()
b = director_profile.B.get_self(myb)
fi = b.fi
i = 50000
a = 1
while i:
a = fi(a) # 1
a = fi(a) # 2
a = fi(a) # 3
a = fi(a) # 4
a = fi(a) # 5
a = fi(a) # 6
a = fi(a) # 7
a = fi(a) # 8
a = fi(a) # 9
a = fi(a) # 10
a = fi(a) # 1
a = fi(a) # 2
a = fi(a) # 3
a = fi(a) # 4
a = fi(a) # 5
a = fi(a) # 6
a = fi(a) # 7
a = fi(a) # 8
a = fi(a) # 9
a = fi(a) # 20
i -= 1
print a
import director_property
class PyFoo(director_property.Foo):
a = property(director_property.Foo.getA, director_property.Foo.setA)
def ping(self):
return "PyFoo::ping()"
foo = PyFoo()
foo.setA("BLABLA")
if foo.getA() != "BLABLA":
raise RuntimeError
foo.a = "BIBI"
if foo.a != "BIBI":
raise RuntimeError
from director_protected import *
class FooBar(Bar):
def ping(self):
return "FooBar::ping();"
class FooBar2(Bar):
def ping(self):
return "FooBar2::ping();"
def pang(self):
return "FooBar2::pang();"
class FooBar3(Bar):
def cheer(self):
return "FooBar3::cheer();"
b = Bar()
f = b.create()
fb = FooBar()
fb2 = FooBar2()
fb3 = FooBar3()
try:
s = fb.used()
if s != "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();":
raise RuntimeError
pass
except:
raise RuntimeError, "bad FooBar::used"
try:
s = fb2.used()
if s != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();":
raise RuntimeError
pass
except:
raise RuntimeError, "bad FooBar2::used"
try:
s = b.pong()
if s != "Bar::pong();Foo::pong();Bar::ping();":
raise RuntimeError
pass
except:
raise RuntimeError, "bad Bar::pong"
try:
s = f.pong()
if s != "Bar::pong();Foo::pong();Bar::ping();":
raise RuntimeError
pass
except:
raise RuntimeError, " bad Foo::pong"
try:
s = fb.pong()
if s != "Bar::pong();Foo::pong();FooBar::ping();":
raise RuntimeError
pass
except:
raise RuntimeError, " bad FooBar::pong"
protected = 1
try:
b.ping()
protected = 0
except:
pass
if not protected:
raise RuntimeError, "Foo::ping is protected"
protected = 1
try:
f.ping()
protected = 0
except:
pass
if not protected:
raise RuntimeError, "Foo::ping is protected"
protected = 1
try:
f.pang()
protected = 0
except:
pass
if not protected:
raise RuntimeError, "FooBar::pang is protected"
protected = 1
try:
b.cheer()
protected = 0
except:
pass
if not protected:
raise RuntimeError, "Bar::cheer is protected"
protected = 1
try:
f.cheer()
protected = 0
except:
pass
if not protected:
raise RuntimeError, "Foo::cheer is protected"
if fb3.cheer() != "FooBar3::cheer();":
raise RuntimeError, "bad fb3::cheer"
if fb2.callping() != "FooBar2::ping();":
raise RuntimeError, "bad fb2.callping"
if fb2.callcheer() != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();":
raise RuntimeError, "bad fb2.callcheer"
if fb3.callping() != "Bar::ping();":
raise RuntimeError, "bad fb3.callping"
if fb3.callcheer() != "FooBar3::cheer();":
raise RuntimeError, "bad fb3.callcheer"
from director_smartptr import *
class director_smartptr_MyBarFoo(Foo):
def ping(self):
return "director_smartptr_MyBarFoo.ping()"
def pong(self):
return "director_smartptr_MyBarFoo.pong();" + self.ping()
def upcall(self, fooBarPtr):
return "override;" + fooBarPtr.FooBarDo()
def makeFoo(self):
return Foo()
class director_smartptr_MyBarFooDerived(FooDerived):
def ping(self):
return "director_smartptr_MyBarFooDerived.ping()"
def pong(self):
return "director_smartptr_MyBarFooDerived.pong();" + self.ping()
def upcall(self, fooBarPtr):
return "overrideDerived;" + fooBarPtr.FooBarDo()
def makeFoo(self):
return Foo()
def check(got, expected):
if (got != expected):
raise RuntimeError, "Failed, got: " + got + " expected: " + expected
fooBar = FooBar()
myBarFoo = director_smartptr_MyBarFoo()
check(myBarFoo.ping(), "director_smartptr_MyBarFoo.ping()")
check(Foo.callPong(myBarFoo), "director_smartptr_MyBarFoo.pong();director_smartptr_MyBarFoo.ping()")
check(Foo.callUpcall(myBarFoo, fooBar), "override;Bar::Foo2::Foo2Bar()")
myFoo = myBarFoo.makeFoo()
check(myFoo.pong(), "Foo::pong();Foo::ping()")
check(Foo.callPong(myFoo), "Foo::pong();Foo::ping()")
check(myFoo.upcall(FooBar()), "Bar::Foo2::Foo2Bar()")
myFoo2 = Foo().makeFoo()
check(myFoo2.pong(), "Foo::pong();Foo::ping()")
check(Foo.callPong(myFoo2), "Foo::pong();Foo::ping()")
check(myFoo2.upcall(FooBar()), "Bar::Foo2::Foo2Bar()")
myBarFooDerived = director_smartptr_MyBarFooDerived()
check(myBarFooDerived.ping(), "director_smartptr_MyBarFooDerived.ping()")
check(FooDerived.callPong(myBarFooDerived), "director_smartptr_MyBarFooDerived.pong();director_smartptr_MyBarFooDerived.ping()")
check(FooDerived.callUpcall(myBarFooDerived, fooBar), "overrideDerived;Bar::Foo2::Foo2Bar()")
import director_stl
class MyFoo(director_stl.Foo):
def ping(self, s):
return "MyFoo::ping():" + s
def pident(self, arg):
return arg
def vident(self, v):
return v
def vidents(self, v):
return v
def vsecond(self, v1, v2):
return v2
a = MyFoo()
a.tping("hello")
a.tpong("hello")
p = (1, 2)
a.pident(p)
v = (3, 4)
a.vident(v)
a.tpident(p)
a.tvident(v)
v1 = (3, 4)
v2 = (5, 6)
a.tvsecond(v1, v2)
vs = ("hi", "hello")
vs
a.tvidents(vs)
from director_string import *
class B(A):
def __init__(self, string):
A.__init__(self, string)
def get_first(self):
return A.get_first(self) + " world!"
def process_text(self, string):
A.process_text(self, string)
self.smem = "hello"
b = B("hello")
b.get(0)
if b.get_first() != "hello world!":
print b.get_first()
raise RuntimeError
b.call_process_func()
if b.smem != "hello":
print smem
raise RuntimeError
from director_thread import Foo
class Derived(Foo):
def __init__(self):
Foo.__init__(self)
def do_foo(self):
self.val = self.val - 1
d = Derived()
d.run()
if d.val >= 0:
print d.val
raise RuntimeError
d.stop()
import director_unroll
class MyFoo(director_unroll.Foo):
def ping(self):
return "MyFoo::ping()"
a = MyFoo()
b = director_unroll.Bar()
b.set(a)
c = b.get()
if not (a.this == c.this):
print a, c
raise RuntimeError
from director_wstring import *
class B(A):
def __init__(self, string):
A.__init__(self, string)
def get_first(self):
return A.get_first(self) + u" world!"
def process_text(self, s):
self.smem = s
b = B(u"hello")
b.get(0)
if b.get_first() != u"hello world!":
print b.get_first()
raise RuntimeError
b.call_process_func()
if b.smem != u"hello":
print smem
raise RuntimeError
from disown import *
a = A()
tmp = a.thisown
a.thisown = 0
if a.thisown:
raise RuntimeError
a.thisown = 1
if (not a.thisown):
raise RuntimeError
a.thisown = tmp
if (a.thisown != tmp):
raise RuntimeError
b = B()
b.acquire(a)
if a.thisown:
raise RuntimeError
import doxygen_alias
import inspect
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_alias.make_something),
"""\
A function returning something.
:rtype: :py:class:`Something`
:return: A new object which may be None.""")
import doxygen_basic_notranslate
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function),
r"""\brief
Brief description.
The comment text
\author Some author
\return Some number
\sa function2"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function1),
r"""Single line comment """
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function2),
r"""A test of a very very very very very very very very very very very very very very very very
very very very very very long comment string."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function3),
r"""*Overload 1:*
A test for overloaded functions
This is function \b one
|
*Overload 2:*
A test for overloaded functions
This is function \b two"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function4),
r"""A test of some mixed tag usage
\if CONDITION
This \a code fragment shows us something \.
\par Minuses:
\arg it's senseless
\arg it's stupid
\arg it's null
\warning This may not work as expected
\code
int main() { while(true); }
\endcode
\endif"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function5),
r"""This is a post comment. """
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function6),
r"""Test for default args
@param a Some parameter, default is 42"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function7),
r"""Test for a parameter with difficult type
(mostly for python)
@param a Very strange param"""
)
import doxygen_basic_translate
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function),
"""\
Brief description.
The comment text.
Author: Some author
:rtype: int
:return: Some number
See also: function2"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function2),
"""\
A test of a very very very very very very very very very very very very very very very very
very very very very very long comment string."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function3),
"""*Overload 1:*
A test for overloaded functions
This is function **one**
|
*Overload 2:*
A test for overloaded functions
This is function **two**"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function4),
"""\
A test of some mixed tag usage
If: CONDITION {
This *code* fragment shows us something .
Title: Minuses:
* it\'s senseless
* it\'s stupid
* it\'s null
Warning: This may not work as expected
.. code-block:: c++
int main() { while(true); }
// Test blank line in code block
}"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function5),
"""This is a post comment."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function6),
"""\
Test for default args
:type a: int, optional
:param a: Some parameter, default is 42"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function7),
"""\
Test for a parameter with difficult type
(mostly for python)
:type a: :py:class:`Shape`
:param a: Very strange param"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function8),
"""\
Test variadic function
:param ...: extra args"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.function9),
"""\
Test unnamed argument
:param baz: Description of baz"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate.Atan2),
"""\
Multiple parameters test.
:type y: float
:param y: Vertical coordinate.
:type x: float
:param x: Horizontal coordinate.
:rtype: float
:return: Arc tangent of ``y/x``."""
)
import doxygen_basic_translate_style2
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function),
"""\
Brief description.
The comment text.
Author: Some author
:rtype: int
:return: Some number
See also: function2"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function2),
"""\
A test of a very very very very very very very very very very very very very very very very
very very very very very long comment string."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function3),
"""*Overload 1:*
A test for overloaded functions
This is function **one**
|
*Overload 2:*
A test for overloaded functions
This is function **two**"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function4),
"""\
A test of some mixed tag usage
If: CONDITION {
This *code* fragment shows us something .
Title: Minuses:
* it\'s senseless
* it\'s stupid
* it\'s null
Warning: This may not work as expected
.. code-block:: c++
int main() { while(true); }
// Test blank line in code block
}"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function5),
"""This is a post comment."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function6),
"""\
Test for default args
:type a: int, optional
:param a: Some parameter, default is 42"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.function7),
"""\
Test for a parameter with difficult type
(mostly for python)
:type a: :py:class:`Shape`
:param a: Very strange param"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style2.Atan2),
"""\
Multiple parameters test.
:type y: float
:param y: Vertical coordinate.
:type x: float
:param x: Horizontal coordinate.
:rtype: float
:return: Arc tangent of ``y/x``."""
)
import doxygen_basic_translate_style3
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function),
"""\
Brief description.
The comment text.
Author: Some author
:rtype: int
:return: Some number
See also: function2"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function2),
"""\
A test of a very very very very very very very very very very very very very very very very
very very very very very long comment string."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function3),
"""*Overload 1:*
A test for overloaded functions
This is function **one**
|
*Overload 2:*
A test for overloaded functions
This is function **two**"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function4),
"""\
A test of some mixed tag usage
If: CONDITION {
This *code* fragment shows us something .
Title: Minuses:
* it\'s senseless
* it\'s stupid
* it\'s null
Warning: This may not work as expected
.. code-block:: c++
int main() { while(true); }
int testBlankLine() {}
}"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function5),
"""This is a post comment."""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function6),
"""\
Test for default args
:type a: int, optional
:param a: Some parameter, default is 42"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.function7),
"""\
Test for a parameter with difficult type
(mostly for python)
:type a: :py:class:`Shape`
:param a: Very strange param"""
)
comment_verifier.check(inspect.getdoc(doxygen_basic_translate_style3.Atan2),
"""\
Multiple parameters test.
:type y: float
:param y: Vertical coordinate.
:type x: float
:param x: Horizontal coordinate.
:rtype: float
:return: Arc tangent of ``y/x``."""
)
import doxygen_code_blocks
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_code_blocks.function),
"""\
Test for code blocks
.. code-block:: c++
simple code block
More advanced usage with C++ characters:
.. code-block:: c++
std::vector<int> first; // empty vector of ints
std::vector<int> second (4,100); // four ints with value 100
std::vector<int> third (second.begin(),second.end()); // iterating through second
std::vector<int> fourth (third); // a copy of third
// the iterator constructor can also be used to construct from arrays:
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
std::cout << "The contents of fifth are:";
for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\\n';
A code block for C:
.. code-block:: c
printf("hello world");
A code block for Java:
.. code-block:: java
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
A code block for python:
.. code-block:: python
print('hello world')
A python doctest example:
>>> 1 + 1
2""")
import doxygen_ignore
import inspect
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_ignore.func),
"""\
A contrived example of ignoring too many commands in one comment.
This is specific to **Python**.
Command ignored, but anything here is still included.""")
import doxygen_misc_constructs
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.getAddress),
r"""Returns address of file line.
:type fileName: int
:param fileName: name of the file, where the source line is located
:type line: int
:param line: line number
:type isGetSize: boolean, optional
:param isGetSize: if set, for every object location both address and size are returned
Connection::getId() """)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.CConnectionConfig),
r"""This class contains information for connection to winIDEA. Its methods
return reference to self, so we can use it like this:
CConnectionConfig config = new CConnectionConfig();
config.discoveryPort(5534).dllPath("C:\\myWinIDEA\\connect.dll").id("main");
All parameters are optional. Set only what is required, default values are
used for unspecified parameters.
advancedWinIDEALaunching.py Python example.""")
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.waitTime),
r"""Determines how long the ``isystem.connect`` should wait for running
instances to respond. Only one of ``lfWaitXXX`` flags from IConnect::ELaunchFlags
may be specified."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.getConnection),
r"""This function returns connection id."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.getFirstLetter),
r""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.ClassWithNestedEnum),
r"""Class description."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.showList),
r"""An example of a list in a documentation comment.
- The first item of the list.
- The second list item, on
several indented lines,
showing that the indentation
is preserved.
- And the final list item after it.
And this is not a list item any more."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.isNoSpaceValidA),
r"""This comment without space after '*' is valid in Doxygen."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.isNoSpaceValidB),
r""".This comment without space after '*' is valid in Doxygen."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.isNoSpaceValidC),
r""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.backslashA),
r"""Backslash following``word`` is a valid doxygen command. Output contains
'followingword' with 'word' in code font."""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.backslashB),
r"""Doxy command without trailing space is ignored - nothing appears
on output. Standalone \ and '\' get to output.
Standalone @ and '@' get to output.
Commands "in quoted \b strings are treated as plain text".
Commands not recognized by Doxygen are ignored.
Backslashes in DOS paths d:and words
following them do not appear on output, we must quote them with
double quotes: "d:\xyz\qwe\myfile", "@something". Single quotes do not help:
'd:'. Escaping works: d:\xyz\qwe\myfile. Unix
paths of course have no such problems: /xyz/qwe/myfile
Commands for escaped symbols:
$ @ \ & ~ < > # % " . :: @text ::text"""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.backslashC),
r"""Backslash e at end of *line* froze SWIG
*with* old comment parser.
See also: MyClass::fun(char,
float)"""
)
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.cycle),
r"""The next line contains expression:
['retVal < 10', 'g_counter == 23 && g_mode & 3']
Both words should be emphasized **isystem.connect**.
But not the last period. For **example**, comma should not be emphasized.
Similar **for**: double colon.
Spaces at the start of line should be taken into account:
:type id: int
:param id: used as prefix in log
statements. The default value is empty string, which is OK if
there is only one app. instance. Example:
ctrl.setBP("func1");
If we set the id to ``main_``, we get:
main_ctrl.setBP("func1");
:type fileName: string
:param fileName: name of the log file"""
);
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.doc_ends_with_quote),
r'''This doc comment ends with a quote: "and that's ok"'''
);
comment_verifier.check(inspect.getdoc(doxygen_misc_constructs.doc_with_triple_quotes),
r'''This comment contains embedded triple-quoted string:
"""How quaint"""'''
);
import doxygen_parsing
import inspect
import string
import os
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_parsing.someFunction),
"The function comment")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeClass),
"The class comment")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeStruct),
"The struct comment")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherClass),
"SomeAnotherClass description")
# There doesn't seem to be any way to specify the doc string for __init__ when
# using "-builtin" (see http://stackoverflow.com/q/11913492/15275), so skip
# this test in this case.
if not doxygen_parsing.is_python_builtin():
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherClass.__init__),
r"""*Overload 1:*
First overloaded constructor.
|
*Overload 2:*
Second overloaded constructor.""")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherClass.classMethod),
r"""The class method comment.
SomeAnotherClass#classMethodExtended(int, int) a link text""")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherClass.classMethodExtended),
r"""The class method with parameter
:type a: int
:param a: Parameter a
:type b: int
:param b: Parameter b"""
)
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherClass.classMethodExtended2),
r"""The class method with parameter
:type a: int
:param a: Parameter a
:type b: int
:param b: Parameter b"""
)
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherStruct.structMethod),
r"""The struct method comment""")
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherStruct.structMethodExtended),
r"""The struct method with parameter
:type a: int
:param a: Parameter a
:type b: int
:param b: Parameter b"""
)
comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeAnotherStruct.structMethodExtended2),
r"""The struct method with parameter
:type a: int
:param a: Parameter a
:type b: int
:param b: Parameter b""")
import doxygen_translate_links
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_translate_links.function),
r"""Testing typenames converting in @ link
superFunc(int,std::string)
Test for std_string member
superFunc(int,long,void*)
Test for simple types
superFunc(Shape::superType*)
Test for custom types
superFunc(int**[13])
Test for complex types
same works for 'See also:' links:
See also: superFunc(int,std::string)
See also: superFunc(int,long,void*)
See also: superFunc(Shape::superType*)
See also: superFunc(int**[13])
some failing params:
See also: superFunc()
See also: superFunc()
See also: superFunc()""")
import doxygen_translate
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_translate.function),
r"""*Hello*
* some list item
Authors: lots of them
Author: Zubr
**boldword**
``codeword``
'citationword'
.. code-block:: c++
some test code
Conditional comment: SOMECONDITION
Some conditional comment
End of conditional comment.
Copyright: some copyright
Deprecated: Now use another function
*italicword*
Example: someFile.txt
Some details on using the example
:raises: SuperError
If: ANOTHERCONDITION {
First part of comment
If: SECONDCONDITION {
Nested condition text
}Else if: THIRDCONDITION {
The third condition text
}Else: { The last text block
}
}Else: { Second part of comment
If: CONDITION {
Second part extended
}
}
If not: SOMECONDITION {
This is printed if not
}
Image: testImage.bmp("Hello, world!")
* Some unordered list
* With lots of items
* lots of lots of items
someMember Some description follows
Notes: Here
is the note!
This is an overloaded member function, provided for convenience.
It differs from the above function only in what argument(s) it accepts.
``someword``
Title: The paragraph title
The paragraph text.
Maybe even multiline
:type a: int
:param a: the first param
Remarks: Some remark text
Another remarks section
:rtype: int
:return: Whatever
:rtype: int
:return: it
:rtype: int
:return: may return
See also: someOtherMethod
See also: function
Since: version 0.0.0.1
:raises: superException
:raises: RuntimeError
TODO: Some very important task
:type b: float
:param b: B is mentioned again...
very long
text with tags <sometag>
Version: 0.0.0.2
Warning: This is senseless!
Here goes test of symbols:
$ @ \ & ~ < > # % " . ::
And here goes simple text"""
)
comment_verifier.check(inspect.getdoc(doxygen_translate.htmlFunction),
r"""Test for html tags. See Doxygen doc for list of tags recognized by Doxygen.
This is link ("http://acme.com/index.html")
**bold**
Quote:
Quotation block.
("http://www.worldwildlife.org/who/index.html")
center
``this is code``
Starts an item title.
Starts an item description.
Starts a piece of text displayed in a typewriter font.
Starts a section with a specific style (HTML only)
**Starts a piece of text displayed in an italic font.**
'Form' does not generate any output.
--------------------------------------------------------------------
# Heading 1
## Heading 2
### Heading 3
*Starts a piece of text displayed in an italic font.*
Input tag.
Image: src="slika.png"
Meta tag.
Multicol is ignored by doxygen.
* List item 1.
* List item 2.
Starts a new paragraph.
Starts a preformatted fragment.
Starts a section of text displayed in a smaller font.
'Starts an inline text fragment with a specific style.'
**Starts a section of bold text.**
Starts a piece of text displayed in subscript.
Starts a piece of text displayed in superscript.
Animals
| Column 1 | Column 2 |
-----------------------
| cow | dog |
| cat | mouse |
| horse | parrot |
Starts a piece of text displayed in a typewriter font.
Starts a piece of text displayed in a typewriter font.
* List item 1.
* List item 2.
* List item 3.
*Starts a piece of text displayed in an italic font.*
<u>underlined \b bold text - doxy commands are ignored inside 'htmlonly' section </u>""")
comment_verifier.check(inspect.getdoc(doxygen_translate.htmlTableFunction),
r"""The meaning of flags:
:type byFlags: int
:param byFlags: bits marking required items:
| Size in bits| Items Required |
--------------------------------
| 1 - 8 | 1 |
| 9 - 16 | 2 |
| 17 - 32 | 4 |
Almost all combinations of above flags are supported by
``htmlTable...`` functions.""")
comment_verifier.check(inspect.getdoc(doxygen_translate.htmlEntitiesFunction),
r"""All entities are treated as commands (C) TM (R)
should work also<in text
>
&
'
"
`
'
"
"
-
--
x
-
.
~
<=
>=
<--
-->
Not an html entity - ignored by Doxygen.
Not an &text html entity - ampersand is replaced with entity.""")
import dynamic_cast
f = dynamic_cast.Foo()
b = dynamic_cast.Bar()
x = f.blah()
y = b.blah()
a = dynamic_cast.do_test(y)
if a != "Bar::test":
print "Failed!!"
import empty_c
import empty
import _enums
_enums.bar2(1)
_enums.bar3(1)
_enums.bar1(1)
if _enums.cvar.enumInstance != 2:
raise RuntimeError
if _enums.cvar.Slap != 10:
raise RuntimeError
if _enums.cvar.Mine != 11:
raise RuntimeError
if _enums.cvar.Thigh != 12:
raise RuntimeError
import enum_forward
f1 = enum_forward.get_enum1()
f1 = enum_forward.test_function1(f1)
f2 = enum_forward.get_enum2()
f2 = enum_forward.test_function2(f2)
f3 = enum_forward.get_enum3()
f3 = enum_forward.test_function3(f3)
import enum_template
if enum_template.MakeETest() != 1:
raise RuntimeError
if enum_template.TakeETest(0) != None:
raise RuntimeError
import exception_classname
a = exception_classname.Exception()
if a.testfunc() != 42:
raise RuntimeError("Not 42!")
from exception_order import *
# This test is expected to fail with -builtin option.
# Throwing builtin classes as exceptions not supported
if is_python_builtin():
exit(0)
a = A()
try:
a.foo()
except E1, e:
pass
except:
raise RuntimeError, "bad exception order"
try:
a.bar()
except E2, e:
pass
except:
raise RuntimeError, "bad exception order"
try:
a.foobar()
except RuntimeError, e:
if e.args[0] != "postcatch unknown":
print "bad exception order",
raise RuntimeError, e.args
try:
a.barfoo(1)
except E1, e:
pass
except:
raise RuntimeError, "bad exception order"
try:
a.barfoo(2)
except E2, e:
pass
except:
raise RuntimeError, "bad exception order"
import extend_placement
foo = extend_placement.Foo()
foo = extend_placement.Foo(1)
foo = extend_placement.Foo(1, 1)
foo.spam()
foo.spam("hello")
foo.spam(1)
foo.spam(1, 1)
foo.spam(1, 1, 1)
foo.spam(extend_placement.Foo())
foo.spam(extend_placement.Foo(), 1.0)
bar = extend_placement.Bar()
bar = extend_placement.Bar(1)
bar.spam()
bar.spam("hello")
bar.spam(1)
bar.spam(1, 1)
bar.spam(1, 1, 1)
bar.spam(extend_placement.Bar())
bar.spam(extend_placement.Bar(), 1.0)
foo = extend_placement.FooTi()
foo = extend_placement.FooTi(1)
foo = extend_placement.FooTi(1, 1)
foo.spam()
foo.spam("hello")
foo.spam(1)
foo.spam(1, 1)
foo.spam(1, 1, 1)
foo.spam(extend_placement.Foo())
foo.spam(extend_placement.Foo(), 1.0)
bar = extend_placement.BarTi()
bar = extend_placement.BarTi(1)
bar.spam()
bar.spam("hello")
bar.spam(1)
bar.spam(1, 1)
bar.spam(1, 1, 1)
bar.spam(extend_placement.Bar())
bar.spam(extend_placement.Bar(), 1.0)
from extend_template_method import *
em = ExtendMe()
ret_double = em.do_stuff_double(1, 1.1)
if ret_double != 1.1:
raise RuntimeError("double failed " + ret_double)
ret_string = em.do_stuff_string(1, "hello there")
if ret_string != "hello there":
raise RuntimeError("string failed " + ret_string)
ret_double = em.do_overloaded_stuff(1.1)
if ret_double != 1.1:
raise RuntimeError("double failed " + ret_double)
ret_string = em.do_overloaded_stuff("hello there")
if ret_string != "hello there":
raise RuntimeError("string failed " + ret_string)
if ExtendMe.static_method(123) != 123:
raise RuntimeError("static_method failed")
em2 = ExtendMe(123)
em = TemplateExtend()
ret_double = em.do_template_stuff_double(1, 1.1)
if ret_double != 1.1:
raise RuntimeError("double failed " + ret_double)
ret_string = em.do_template_stuff_string(1, "hello there")
if ret_string != "hello there":
raise RuntimeError("string failed " + ret_string)
ret_double = em.do_template_overloaded_stuff(1.1)
if ret_double != 1.1:
raise RuntimeError("double failed " + ret_double)
ret_string = em.do_template_overloaded_stuff("hello there")
if ret_string != "hello there":
raise RuntimeError("string failed " + ret_string)
if TemplateExtend.static_template_method(123) != 123:
raise RuntimeError("static_template_method failed")
em2 = TemplateExtend(123)
from extend_template_ns import *
f = Foo_One()
if f.test1(37) != 37:
raise RuntimeError
if f.test2(42) != 42:
raise RuntimeError
import extend_template
f = extend_template.Foo_0()
if f.test1(37) != 37:
raise RuntimeError
if f.test2(42) != 42:
raise RuntimeError
from extend_variable import *
if Foo.Bar != 42:
raise RuntimeError
import extern_c
extern_c.RealFunction(2)
import sys
import file_test
if sys.version_info[0:2] < (3, 0):
file_test.nfile(sys.stdout)
cstdout = file_test.GetStdOut()
file_test.nfile(cstdout)
file_test.nfile_name("test.dat")
import friends
a = friends.A(2)
if friends.get_val1(a) != 2:
raise RuntimeError
if friends.get_val2(a) != 4:
raise RuntimeError
if friends.get_val3(a) != 6:
raise RuntimeError
# nice overload working fine
if friends.get_val1(1, 2, 3) != 1:
raise RuntimeError
b = friends.B(3)
# David's case
if friends.mix(a, b) != 5:
raise RuntimeError
di = friends.D_d(2)
dd = friends.D_d(3.3)
# incredible template overloading working just fine
if friends.get_val1(di) != 2:
raise RuntimeError
if friends.get_val1(dd) != 3.3:
raise RuntimeError
friends.set(di, 4)
friends.set(dd, 1.3)
if friends.get_val1(di) != 4:
raise RuntimeError
if friends.get_val1(dd) != 1.3:
raise RuntimeError
from funcptr_cpp import *
if call1(ADD_BY_VALUE, 10, 11) != 21:
raise RuntimeError
if call2(ADD_BY_POINTER, 12, 13) != 25:
raise RuntimeError
if call3(ADD_BY_REFERENCE, 14, 15) != 29:
raise RuntimeError
if call1(ADD_BY_VALUE_C, 2, 3) != 5:
raise RuntimeError
if callconst1(ADD_BY_VALUE_C, 2, 3) != 5:
raise RuntimeError
from functors import *
a = Functor0(10)
b = Functor1(10)
c = Functor2(10)
if a()!=-10:
raise RuntimeError("a failed")
if b(1)!=11:
raise RuntimeError("b failed")
if c(1, 2)!=13:
raise RuntimeError("c failed")
from fvirtual import *
sw = NodeSwitch()
n = Node()
i = sw.addChild(n)
if i != 2:
raise RuntimeError, "addChild"
from global_functions import *
def check(a, b):
if a != b:
raise RuntimeError("Failed: " + str(a) + " != " + str(b))
global_void()
check(global_one(1), 1)
check(global_two(2, 2), 4)
fail = True
try:
global_void(1)
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
global_one()
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
global_one(2, 2)
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
global_two(1)
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
global_two(3, 3, 3)
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
from global_namespace import *
k1 = Klass1()
k2 = Klass2()
k3 = Klass3()
k4 = Klass4()
k5 = Klass5()
k6 = Klass6()
k7 = Klass7()
KlassMethods.methodA(k1, k2, k3, k4, k5, k6, k7)
KlassMethods.methodB(k1, k2, k3, k4, k5, k6, k7)
k1 = getKlass1A()
k2 = getKlass2A()
k3 = getKlass3A()
k4 = getKlass4A()
k5 = getKlass5A()
k6 = getKlass6A()
k7 = getKlass7A()
KlassMethods.methodA(k1, k2, k3, k4, k5, k6, k7)
KlassMethods.methodB(k1, k2, k3, k4, k5, k6, k7)
k1 = getKlass1B()
k2 = getKlass2B()
k3 = getKlass3B()
k4 = getKlass4B()
k5 = getKlass5B()
k6 = getKlass6B()
k7 = getKlass7B()
KlassMethods.methodA(k1, k2, k3, k4, k5, k6, k7)
KlassMethods.methodB(k1, k2, k3, k4, k5, k6, k7)
XYZMethods.methodA(XYZ1(), XYZ2(), XYZ3(), XYZ4(), XYZ5(), XYZ6(), XYZ7())
XYZMethods.methodB(XYZ1(), XYZ2(), XYZ3(), XYZ4(), XYZ5(), XYZ6(), XYZ7())
TheEnumMethods.methodA(theenum1, theenum2, theenum3)
TheEnumMethods.methodA(theenum1, theenum2, theenum3)
from global_ns_arg import *
a = foo(1)
b = bar_fn()
import global_vars
global_vars.init()
b = global_vars.cvar.b
if b != "string b":
raise RuntimeError("Unexpected string: " + b)
global_vars.cvar.b = "a string value"
b = global_vars.cvar.b
if b != "a string value":
raise RuntimeError("Unexpected string: " + b)
x = global_vars.cvar.x
if x != 1234:
raise RuntimeError("Unexpected x: " + str(x))
global_vars.cvar.x = 9876
x = global_vars.cvar.x
if x != 9876:
raise RuntimeError("Unexpected string: " + str(x))
fail = True
try:
global_vars.cvar.notexist = "something"
except AttributeError, e:
fail = False
if fail:
raise RuntimeError("AttributeError should have been thrown")
fail = True
try:
g = global_vars.cvar.notexist
except AttributeError, e:
fail = False
if fail:
raise RuntimeError("AttributeError should have been thrown")
import grouping
x = grouping.test1(42)
if x != 42:
raise RuntimeError
grouping.test2(42)
x = grouping.do_unary(37, grouping.NEGATE)
if x != -37:
raise RuntimeError
grouping.cvar.test3 = 42
grouping.test3 = 42
import iadd
f = iadd.Foo()
f.AsA.x = 3
f.AsA += f.AsA
if f.AsA.x != 6:
raise RuntimeError
from ignore_parameter import *
def check(a, b):
if a != b:
raise RuntimeError("'%s' != '%s'" % (a, b))
check(jaguar(200, 0), "hello")
check(lotus("foo", 1), 101)
check(tvr("bar", 2), 8.8)
check(ferrari(), 101)
check(fiat(17), 17)
car = SportsCars()
check(car.daimler(200, 0), "hello")
check(car.astonmartin("foo", 1), 101)
check(car.bugatti("bar", 2), 8.8)
check(car.lamborghini(), 101)
check(car.maseratti(289), 289)
MiniCooper(200, 0)
MorrisMinor("baz", 0)
FordAnglia("quux", 200)
AustinAllegro()
from implicittest import *
def check(a, b):
if a != b:
raise RuntimeError(str(a) + " does not equal " + str(b))
#### Class ####
# No implicit conversion
check(1, A(1).get())
check(2, A(1.0).get())
check(3, A(B()).get())
check(4, A("hello").get())
check(4, A(None).get())
check(1, get(1))
check(2, get(1.0))
check(3, get(B()))
# Explicit constructor:
try:
check(4, get("hello"))
raise RuntimeError
except TypeError:
pass
#### Template Class ####
# No implicit conversion
check(1, A_int(1).get())
check(2, A_int(1.0).get())
check(3, A_int(B()).get())
check(4, A_int("hello").get())
check(1, A_int.sget(1))
check(2, A_int.sget(1.0))
check(3, A_int.sget(B()))
# explicit constructor:
try:
check(4, A_int.sget("hello"))
raise RuntimeError
except TypeError:
pass
#### Global variable assignment ####
cvar.foo = Foo(1)
check(cvar.foo.ii, 1)
cvar.foo = 1
check(cvar.foo.ii, 1)
cvar.foo = 1.0
check(cvar.foo.ii, 2)
cvar.foo = Foo("hello")
check(cvar.foo.ii, 3)
# explicit constructor:
try:
cvar.foo = "hello"
raise RuntimeError
except TypeError:
pass
#### Member variable assignment ####
# Note: also needs naturalvar
b = Bar()
check(b.f.ii, 0)
b.f = Foo("hello")
check(b.f.ii, 3)
b.f = 1
check(b.f.ii, 1)
b.f = 1.0
check(b.f.ii, 2)
# explicit constructor:
try:
b.f = "hello"
raise RuntimeError
except TypeError:
pass
#### Class testing None ####
# No implicit conversion
check(1, AA(1).get())
check(2, AA(1.0).get())
check(3, AA(B()).get())
check(3, AA(None).get())
check(4, AA("hello").get())
check(5, AA(BB()).get())
check(1, get_AA_val(1))
check(2, get_AA_val(1.0))
check(3, get_AA_val(B()))
check(3, get_AA_val(None))
check(5, get_AA_val(BB()))
# Explicit constructor:
try:
check(4, get_AA_val("hello"))
raise RuntimeError
except TypeError:
pass
check(1, get_AA_ref(1))
check(2, get_AA_ref(1.0))
check(3, get_AA_ref(B()))
check(3, get_AA_ref(None))
check(5, get_AA_ref(BB()))
# Explicit constructor:
try:
check(4, get_AA_ref("hello"))
raise RuntimeError
except TypeError:
pass
### overloading priority test ###
ccc = CCC(B())
check(ccc.checkvalue, 10)
check(ccc.xx(123), 11)
check(ccc.yy(123, 123), 111)
# This is the import runtime testcase.
import imports_b
import imports_a
import sys
x = imports_b.B()
imports_a.A.hello(x)
a = imports_a.A()
c = imports_b.C()
a1 = c.get_a(c)
a2 = c.get_a_type(c)
if a1.hello() != a2.hello():
raise RuntimeError
from import_nomodule import *
# This test is expected to fail with -builtin option.
# The base class is needed for the builtin class hierarchy
if is_python_builtin():
exit(0)
f = create_Foo()
test1(f, 42)
delete_Foo(f)
b = Bar()
test1(b, 37)
import import_stl_b
import import_stl_a
v_new = import_stl_b.process_vector([1, 2, 3])
if v_new != (1, 2, 3, 4):
raise RuntimeError, v_new
import inctest
error = 0
try:
a = inctest.A()
except:
print "didn't find A"
print "therefore, I didn't include 'testdir/subdir1/hello.i'"
error = 1
pass
try:
b = inctest.B()
except:
print "didn't find B"
print "therefore, I didn't include 'testdir/subdir2/hello.i'"
error = 1
pass
if error == 1:
raise RuntimeError
# Check the import in subdirectory worked
if inctest.importtest1(5) != 15:
print "import test 1 failed"
raise RuntimeError
if inctest.importtest2("black") != "white":
print "import test 2 failed"
raise RuntimeError
import inherit_missing
a = inherit_missing.new_Foo()
b = inherit_missing.Bar()
c = inherit_missing.Spam()
x = inherit_missing.do_blah(a)
if x != "Foo::blah":
print "Whoa! Bad return", x
x = inherit_missing.do_blah(b)
if x != "Bar::blah":
print "Whoa! Bad return", x
x = inherit_missing.do_blah(c)
if x != "Spam::blah":
print "Whoa! Bad return", x
inherit_missing.delete_Foo(a)
import inout
a = inout.AddOne1(1)
if a != 2:
raise RuntimeError
a = inout.AddOne3(1, 1, 1)
if a != [2, 2, 2]:
raise RuntimeError
a = inout.AddOne1p((1, 1))
if a != (2, 2):
raise RuntimeError
a = inout.AddOne2p((1, 1), 1)
if a != [(2, 2), 2]:
raise RuntimeError
a = inout.AddOne3p(1, (1, 1), 1)
if a != [2, (2, 2), 2]:
raise RuntimeError
import inplaceadd
a = inplaceadd.A(7)
a += 5
if a.val != 12:
print a.val
raise RuntimeError
a -= 5
if a.val != 7:
raise RuntimeError
a *= 2
if a.val != 14:
raise RuntimeError
a += a
if a.val != 28:
raise RuntimeError
from input import *
f = Foo()
if f.foo(2) != 4:
raise RuntimeError
if f.foo(None) != None:
raise RuntimeError
if f.foo() != None:
raise RuntimeError
if sfoo("Hello") != "Hello world":
raise RuntimeError
if sfoo(None) != None:
raise RuntimeError
if sfoo() != None:
raise RuntimeError
#!/usr/bin/env python
import keyword_rename_c
keyword_rename_c._in(1)
keyword_rename_c._except(1)
#!/usr/bin/env python
import keyword_rename
keyword_rename._in(1)
keyword_rename._in(_except=1)
keyword_rename._except(1)
keyword_rename._except(_in=1)
from kwargs_feature import *
class MyFoo(Foo):
def __init__(self, a, b=0):
Foo.__init__(self, a, b)
# Simple class
f1 = MyFoo(2)
f = Foo(b=2, a=1)
if f.foo(b=1, a=2) != 3:
raise RuntimeError
if Foo_statfoo(b=2) != 3:
raise RuntimeError
if f.efoo(b=2) != 3:
raise RuntimeError
if Foo_sfoo(b=2) != 3:
raise RuntimeError
# Templated class
b = BarInt(b=2, a=1)
if b.bar(b=1, a=2) != 3:
raise RuntimeError
if BarInt_statbar(b=2) != 3:
raise RuntimeError
if b.ebar(b=2) != 3:
raise RuntimeError
if BarInt_sbar(b=2) != 3:
raise RuntimeError
# Functions
if templatedfunction(b=2) != 3:
raise RuntimeError
if foo_fn(a=1, b=2) != 3:
raise RuntimeError
if foo_fn(b=2) != 3:
raise RuntimeError
# Functions with keywords
if foo_kw(_from=2) != 4:
raise RuntimeError
if foo_nu(_from=2, arg2=3) != 2:
raise RuntimeError
if foo_mm(min=2) != 4:
raise RuntimeError
if foo_mm(max=3) != 4:
raise RuntimeError
# Default args with references
if rfoo(n=123) != 120:
raise RuntimeError
if rfoo(x=10) != -10:
raise RuntimeError
if rfoo(n=11, x=22) != -11:
raise RuntimeError
if rfoo(x=11, n=22) != 11:
raise RuntimeError
# Extended constructors
e = Extending0()
e = Extending1(one=1)
e = Extending1(1)
e = Extending2(1, "two")
e = Extending2(1, two="two")
e = Extending2(two="two", one=1)
e = ExtendingOptArgs1()
e = ExtendingOptArgs1(1)
e = ExtendingOptArgs2(one=1)
e = ExtendingOptArgs2()
e = ExtendingOptArgs2(one=1)
e = ExtendingOptArgs2(two="two")
e = ExtendingOptArgs2(two="two", one=1)
# Invalid kwargs test
h = Hello()
try:
h = Hello(nonexistent=10)
raise RuntimeError("missed exception")
except TypeError as e:
pass
f = Foo(1)
f = Foo(a=1)
try:
f = Foo(nonexistent=10)
raise RuntimeError("missed exception")
except TypeError as e:
pass
try:
f = Foo(a=1, nonexistent=10)
raise RuntimeError("missed exception")
except TypeError as e:
pass
try:
f = Foo(1, nonexistent=10)
raise RuntimeError("missed exception")
except TypeError as e:
pass
import sys
from langobj import *
x = "hello"
rx = sys.getrefcount(x)
v = identity(x)
rv = sys.getrefcount(v)
if v != x:
raise RuntimeError
if rv - rx != 1:
raise RuntimeError
# Ported to C# li_attribute_runme.cs
import li_attribute
aa = li_attribute.A(1, 2, 3)
if aa.a != 1:
raise RuntimeError
aa.a = 3
if aa.a != 3:
print aa.a
raise RuntimeError
if aa.b != 2:
print aa.b
raise RuntimeError
aa.b = 5
if aa.b != 5:
raise RuntimeError
if aa.d != aa.b:
raise RuntimeError
if aa.c != 3:
raise RuntimeError
#aa.c = 5
# if aa.c != 3:
# raise RuntimeError
pi = li_attribute.Param_i(7)
if pi.value != 7:
raise RuntimeError
pi.value = 3
if pi.value != 3:
raise RuntimeError
b = li_attribute.B(aa)
if b.a.c != 3:
raise RuntimeError
# class/struct attribute with get/set methods using return/pass by reference
myFoo = li_attribute.MyFoo()
myFoo.x = 8
myClass = li_attribute.MyClass()
myClass.Foo = myFoo
if myClass.Foo.x != 8:
raise RuntimeError
# class/struct attribute with get/set methods using return/pass by value
myClassVal = li_attribute.MyClassVal()
if myClassVal.ReadWriteFoo.x != -1:
raise RuntimeError
if myClassVal.ReadOnlyFoo.x != -1:
raise RuntimeError
myClassVal.ReadWriteFoo = myFoo
if myClassVal.ReadWriteFoo.x != 8:
raise RuntimeError
if myClassVal.ReadOnlyFoo.x != 8:
raise RuntimeError
# string attribute with get/set methods using return/pass by value
myStringyClass = li_attribute.MyStringyClass("initial string")
if myStringyClass.ReadWriteString != "initial string":
raise RuntimeError
if myStringyClass.ReadOnlyString != "initial string":
raise RuntimeError
myStringyClass.ReadWriteString = "changed string"
if myStringyClass.ReadWriteString != "changed string":
raise RuntimeError
if myStringyClass.ReadOnlyString != "changed string":
raise RuntimeError
# Check a proper AttributeError is raised for non-existent attributes, old versions used to raise unhelpful error:
# AttributeError: type object 'object' has no attribute '__getattr__'
try:
x = myFoo.does_not_exist
raise RuntimeError
except AttributeError, e:
if str(e).find("does_not_exist") == -1:
raise RuntimeError
# Check usage of template attributes
import li_attribute_template
chell = li_attribute_template.Cintint(1, 2, 3)
def rassert(what, master):
if what != master:
print what
raise RuntimeError
# Testing primitive by value attribute
rassert(chell.a, 1)
chell.a = 3
rassert(chell.a, 3)
# Testing primitive by ref attribute
rassert(chell.b, 2)
chell.b = 5
rassert(chell.b, 5)
# Testing string
chell.str = "abc"
rassert(chell.str, "abc")
# Testing class by value
rassert(chell.d.value, 1)
chell.d = li_attribute_template.Foo(2)
rassert(chell.d.value, 2)
# Testing class by reference
rassert(chell.e.value, 2)
chell.e = li_attribute_template.Foo(3)
rassert(chell.e.value, 3)
chell.e.value = 4
rassert(chell.e.value, 4)
# Testing moderately complex template by value
rassert(chell.f.first, 1)
rassert(chell.f.second, 2)
pair = li_attribute_template.pair_intint(3, 4)
chell.f = pair
rassert(chell.f.first, 3)
rassert(chell.f.second, 4)
# Testing moderately complex template by ref
rassert(chell.g.first, 2)
rassert(chell.g.second, 3)
pair = li_attribute_template.pair_intint(4, 5)
chell.g = pair
rassert(chell.g.first, 4)
rassert(chell.g.second, 5)
chell.g.first = 6
chell.g.second = 7
rassert(chell.g.first, 6)
rassert(chell.g.second, 7)
from li_boost_shared_ptr_bits import *
def check(nd):
nd.i = 200
i = nd.i
try:
nd.notexist = 100
passed = 0
except:
passed = 1
if not passed:
raise "Test failed"
nd = NonDynamic()
check(nd)
b = boing(nd)
check(b)
################################
v = VectorIntHolder()
v.push_back(IntHolder(11))
v.push_back(IntHolder(22))
v.push_back(IntHolder(33))
sum = sum(v)
if sum != 66:
raise "sum is wrong"
################################
p = HiddenDestructor.create()
from li_boost_shared_ptr_director import *
class Derived(Base):
def __init__(self, flag):
self.return_none = flag
Base.__init__(self)
def ret_c_shared_ptr(self):
if self.return_none:
return None
else:
return C()
def ret_c_by_value(self):
return C()
def take_c_by_value(self,c):
return c.get_m()
def take_c_by_ref(self,c):
return c.get_m()
def take_c_by_pointer(self,c):
if c:
return c.get_m()
else:
return -2
def take_c_by_pointer_ref(self,c):
if c:
return c.get_m()
else:
return -3
def take_c_shared_ptr_by_value(self,c):
if c:
return c.get_m()
else:
return -4
def take_c_shared_ptr_by_ref(self,c):
if c:
return c.get_m()
else:
return -5
def take_c_shared_ptr_by_pointer(self,c):
if c:
return c.get_m()
else:
return -6
def take_c_shared_ptr_by_pointer_ref(self,c):
if c:
return c.get_m()
else:
return -7
a = Derived(False)
b = Derived(True)
assert call_ret_c_shared_ptr(a) == 1
assert call_ret_c_shared_ptr(b) == -1
assert call_ret_c_by_value(a) == 1
assert call_take_c_by_value(a) == 5
assert call_take_c_by_ref(a) == 6
assert call_take_c_by_pointer(a) == 7
assert call_take_c_by_pointer_ref(a) == 8
assert call_take_c_shared_ptr_by_value(a) == 9
assert call_take_c_shared_ptr_by_ref(a) == 10
assert call_take_c_shared_ptr_by_pointer(a) == 11
assert call_take_c_shared_ptr_by_pointer_ref(a) == 12
assert call_take_c_by_pointer_with_null(a) == -2
assert call_take_c_by_pointer_ref_with_null(a) == -3
assert call_take_c_shared_ptr_by_value_with_null(a) == -4
assert call_take_c_shared_ptr_by_ref_with_null(a) == -5
assert call_take_c_shared_ptr_by_pointer_with_null(a) == -6
assert call_take_c_shared_ptr_by_pointer_ref_with_null(a) == -7
import li_boost_shared_ptr
import gc
debug = False
# simple shared_ptr usage - created in C++
class li_boost_shared_ptr_runme:
def main(self):
if (debug):
print "Started"
li_boost_shared_ptr.cvar.debug_shared = debug
# Change loop count to run for a long time to monitor memory
loopCount = 1 # 5000
for i in range(0, loopCount):
self.runtest()
# Expect 1 instance - the one global variable (GlobalValue)
if (li_boost_shared_ptr.Klass_getTotal_count() != 1):
raise RuntimeError("Klass.total_count=%s" %
li_boost_shared_ptr.Klass.getTotal_count())
wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count()
if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING):
# Expect 1 instance - the one global variable (GlobalSmartValue)
if (wrapper_count != 1):
raise RuntimeError(
"shared_ptr wrapper count=%s" % wrapper_count)
if (debug):
print "Finished"
def runtest(self):
# simple shared_ptr usage - created in C++
k = li_boost_shared_ptr.Klass("me oh my")
val = k.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(1, k)
# simple shared_ptr usage - not created in C++
k = li_boost_shared_ptr.factorycreate()
val = k.getValue()
self.verifyValue("factorycreate", val)
self.verifyCount(1, k)
# pass by shared_ptr
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.smartpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointertest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.smartpointerpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointertest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr reference
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.smartpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerreftest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer reference
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.smartpointerpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointerreftest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# const pass by shared_ptr
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.constsmartpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# const pass by shared_ptr pointer
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.constsmartpointerpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# const pass by shared_ptr reference
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.constsmartpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by value
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.valuetest(k)
val = kret.getValue()
self.verifyValue("me oh my valuetest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by pointer
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.pointertest(k)
val = kret.getValue()
self.verifyValue("me oh my pointertest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by reference
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.reftest(k)
val = kret.getValue()
self.verifyValue("me oh my reftest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by pointer reference
k = li_boost_shared_ptr.Klass("me oh my")
kret = li_boost_shared_ptr.pointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my pointerreftest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# null tests
k = None
if (li_boost_shared_ptr.smartpointertest(k) != None):
raise RuntimeError("return was not null")
if (li_boost_shared_ptr.smartpointerpointertest(k) != None):
raise RuntimeError("return was not null")
if (li_boost_shared_ptr.smartpointerreftest(k) != None):
raise RuntimeError("return was not null")
if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None):
raise RuntimeError("return was not null")
if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer"):
raise RuntimeError("not null smartpointer pointer")
try:
li_boost_shared_ptr.valuetest(k)
raise RuntimeError("Failed to catch null pointer")
except ValueError:
pass
if (li_boost_shared_ptr.pointertest(k) != None):
raise RuntimeError("return was not null")
try:
li_boost_shared_ptr.reftest(k)
raise RuntimeError("Failed to catch null pointer")
except ValueError:
pass
# $owner
k = li_boost_shared_ptr.pointerownertest()
val = k.getValue()
self.verifyValue("pointerownertest", val)
self.verifyCount(1, k)
k = li_boost_shared_ptr.smartpointerpointerownertest()
val = k.getValue()
self.verifyValue("smartpointerpointerownertest", val)
self.verifyCount(1, k)
# //////////////////////////////// Derived class //////////////////////
# derived pass by shared_ptr
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.derivedsmartptrtest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrtest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by shared_ptr pointer
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.derivedsmartptrpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by shared_ptr ref
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.derivedsmartptrreftest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by shared_ptr pointer ref
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by pointer
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.derivedpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedpointertest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# derived pass by ref
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.derivedreftest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedreftest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# //////////////////////////////// Derived and base class mixed ///////
# pass by shared_ptr (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.smartpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointertest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.smartpointerpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointertest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr reference (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.smartpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer reference (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.smartpointerpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointerreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by value (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.valuetest(k)
val = kret.getValue()
self.verifyValue("me oh my valuetest", val) # note slicing
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by pointer (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.pointertest(k)
val = kret.getValue()
self.verifyValue("me oh my pointertest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by ref (mixed)
k = li_boost_shared_ptr.KlassDerived("me oh my")
kret = li_boost_shared_ptr.reftest(k)
val = kret.getValue()
self.verifyValue("me oh my reftest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# //////////////////////////////// Overloading tests //////////////////
# Base class
k = li_boost_shared_ptr.Klass("me oh my")
self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval")
self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref")
self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr")
self.verifyValue(
li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyval(k), "smartbyval")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyref(k), "smartbyref")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref")
# Derived class
k = li_boost_shared_ptr.KlassDerived("me oh my")
self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval")
self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref")
self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr")
self.verifyValue(
li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyval(k), "smartbyval")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyref(k), "smartbyref")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr")
self.verifyValue(
li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref")
# 3rd derived class
k = li_boost_shared_ptr.Klass3rdDerived("me oh my")
val = k.getValue()
self.verifyValue("me oh my-3rdDerived", val)
self.verifyCount(1, k)
val = li_boost_shared_ptr.test3rdupcast(k)
self.verifyValue("me oh my-3rdDerived", val)
self.verifyCount(1, k)
# //////////////////////////////// Member variables ///////////////////
# smart pointer by value
m = li_boost_shared_ptr.MemberVariables()
k = li_boost_shared_ptr.Klass("smart member value")
m.SmartMemberValue = k
val = k.getValue()
self.verifyValue("smart member value", val)
self.verifyCount(2, k)
kmember = m.SmartMemberValue
val = kmember.getValue()
self.verifyValue("smart member value", val)
self.verifyCount(3, kmember)
self.verifyCount(3, k)
del m
self.verifyCount(2, kmember)
self.verifyCount(2, k)
# smart pointer by pointer
m = li_boost_shared_ptr.MemberVariables()
k = li_boost_shared_ptr.Klass("smart member pointer")
m.SmartMemberPointer = k
val = k.getValue()
self.verifyValue("smart member pointer", val)
self.verifyCount(1, k)
kmember = m.SmartMemberPointer
val = kmember.getValue()
self.verifyValue("smart member pointer", val)
self.verifyCount(2, kmember)
self.verifyCount(2, k)
del m
self.verifyCount(2, kmember)
self.verifyCount(2, k)
# smart pointer by reference
m = li_boost_shared_ptr.MemberVariables()
k = li_boost_shared_ptr.Klass("smart member reference")
m.SmartMemberReference = k
val = k.getValue()
self.verifyValue("smart member reference", val)
self.verifyCount(2, k)
kmember = m.SmartMemberReference
val = kmember.getValue()
self.verifyValue("smart member reference", val)
self.verifyCount(3, kmember)
self.verifyCount(3, k)
# The C++ reference refers to SmartMemberValue...
kmemberVal = m.SmartMemberValue
val = kmember.getValue()
self.verifyValue("smart member reference", val)
self.verifyCount(4, kmemberVal)
self.verifyCount(4, kmember)
self.verifyCount(4, k)
del m
self.verifyCount(3, kmemberVal)
self.verifyCount(3, kmember)
self.verifyCount(3, k)
# plain by value
m = li_boost_shared_ptr.MemberVariables()
k = li_boost_shared_ptr.Klass("plain member value")
m.MemberValue = k
val = k.getValue()
self.verifyValue("plain member value", val)
self.verifyCount(1, k)
kmember = m.MemberValue
val = kmember.getValue()
self.verifyValue("plain member value", val)
self.verifyCount(1, kmember)
self.verifyCount(1, k)
del m
self.verifyCount(1, kmember)
self.verifyCount(1, k)
# plain by pointer
m = li_boost_shared_ptr.MemberVariables()
k = li_boost_shared_ptr.Klass("plain member pointer")
m.MemberPointer = k
val = k.getValue()
self.verifyValue("plain member pointer", val)
self.verifyCount(1, k)
kmember = m.MemberPointer
val = kmember.getValue()
self.verifyValue("plain member pointer", val)
self.verifyCount(1, kmember)
self.verifyCount(1, k)
del m
self.verifyCount(1, kmember)
self.verifyCount(1, k)
# plain by reference
m = li_boost_shared_ptr.MemberVariables()
k = li_boost_shared_ptr.Klass("plain member reference")
m.MemberReference = k
val = k.getValue()
self.verifyValue("plain member reference", val)
self.verifyCount(1, k)
kmember = m.MemberReference
val = kmember.getValue()
self.verifyValue("plain member reference", val)
self.verifyCount(1, kmember)
self.verifyCount(1, k)
del m
self.verifyCount(1, kmember)
self.verifyCount(1, k)
# null member variables
m = li_boost_shared_ptr.MemberVariables()
# shared_ptr by value
k = m.SmartMemberValue
if (k != None):
raise RuntimeError("expected null")
m.SmartMemberValue = None
k = m.SmartMemberValue
if (k != None):
raise RuntimeError("expected null")
self.verifyCount(0, k)
# plain by value
try:
m.MemberValue = None
raise RuntimeError("Failed to catch null pointer")
except ValueError:
pass
# ////////////////////////////////// Global variables /////////////////
# smart pointer
kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue
if (kglobal != None):
raise RuntimeError("expected null")
k = li_boost_shared_ptr.Klass("smart global value")
li_boost_shared_ptr.cvar.GlobalSmartValue = k
self.verifyCount(2, k)
kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue
val = kglobal.getValue()
self.verifyValue("smart global value", val)
self.verifyCount(3, kglobal)
self.verifyCount(3, k)
self.verifyValue(
"smart global value", li_boost_shared_ptr.cvar.GlobalSmartValue.getValue())
li_boost_shared_ptr.cvar.GlobalSmartValue = None
# plain value
k = li_boost_shared_ptr.Klass("global value")
li_boost_shared_ptr.cvar.GlobalValue = k
self.verifyCount(1, k)
kglobal = li_boost_shared_ptr.cvar.GlobalValue
val = kglobal.getValue()
self.verifyValue("global value", val)
self.verifyCount(1, kglobal)
self.verifyCount(1, k)
self.verifyValue(
"global value", li_boost_shared_ptr.cvar.GlobalValue.getValue())
try:
li_boost_shared_ptr.cvar.GlobalValue = None
raise RuntimeError("Failed to catch null pointer")
except ValueError:
pass
# plain pointer
kglobal = li_boost_shared_ptr.cvar.GlobalPointer
if (kglobal != None):
raise RuntimeError("expected null")
k = li_boost_shared_ptr.Klass("global pointer")
li_boost_shared_ptr.cvar.GlobalPointer = k
self.verifyCount(1, k)
kglobal = li_boost_shared_ptr.cvar.GlobalPointer
val = kglobal.getValue()
self.verifyValue("global pointer", val)
self.verifyCount(1, kglobal)
self.verifyCount(1, k)
li_boost_shared_ptr.cvar.GlobalPointer = None
# plain reference
k = li_boost_shared_ptr.Klass("global reference")
li_boost_shared_ptr.cvar.GlobalReference = k
self.verifyCount(1, k)
kglobal = li_boost_shared_ptr.cvar.GlobalReference
val = kglobal.getValue()
self.verifyValue("global reference", val)
self.verifyCount(1, kglobal)
self.verifyCount(1, k)
try:
li_boost_shared_ptr.cvar.GlobalReference = None
raise RuntimeError("Failed to catch null pointer")
except ValueError:
pass
# ////////////////////////////////// Templates ////////////////////////
pid = li_boost_shared_ptr.PairIntDouble(10, 20.2)
if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4):
raise RuntimeError("Base values wrong")
if (pid.val1 != 10 or pid.val2 != 20.2):
raise RuntimeError("Derived Values wrong")
def verifyValue(self, expected, got):
if (expected != got):
raise RuntimeError(
"verify value failed. Expected: ", expected, " Got: ", got)
def verifyCount(self, expected, k):
got = li_boost_shared_ptr.use_count(k)
if (expected != got):
raise RuntimeError(
"verify use_count failed. Expected: ", expected, " Got: ", got)
runme = li_boost_shared_ptr_runme()
runme.main()
from li_boost_shared_ptr_template import *
b = BaseINTEGER()
d = DerivedINTEGER()
if b.bar() != 1:
raise RuntimeError
if d.bar() != 2:
raise RuntimeError
if bar_getter(b) != 1:
raise RuntimeError
if bar_getter(d) != 2:
raise RuntimeError
b = BaseDefaultInt()
d = DerivedDefaultInt()
d2 = DerivedDefaultInt2()
if b.bar2() != 3:
raise RuntimeError
if d.bar2() != 4:
raise RuntimeError
if d2.bar2() != 4:
raise RuntimeError
if bar2_getter(b) != 3:
raise RuntimeError
# SWIG fix reverted in Subversion rev 12953
# Testcase has now been modified to mask the problem by providing the default parameter 'int' in:
# %shared_ptr(Space::BaseDefault<short, int>)
# If this is not done then d fails to convert to BaseDefault<short>&
if bar2_getter(d) != 4:
raise RuntimeError
if bar2_getter(d2) != 4:
raise RuntimeError
from li_carrays_cpp import *
d = doubleArray(10)
d[0] = 7
d[5] = d[0] + 3
if d[5] + d[0] != 17:
raise RuntimeError
shorts = shortArray(5)
sum = sum_array(shorts)
if sum != 0:
raise RuntimeError("incorrect zero sum, got: " + str(sum))
for i in range(5):
shorts[i] = i
sum = sum_array(shorts)
if sum != 0+1+2+3+4:
raise RuntimeError("incorrect sum, got: " + str(sum))
from li_carrays import *
d = doubleArray(10)
d[0] = 7
d[5] = d[0] + 3
if d[5] + d[0] != 17:
raise RuntimeError
shorts = shortArray(5)
sum = sum_array(shorts)
if sum != 0:
raise RuntimeError("incorrect zero sum, got: " + str(sum))
for i in range(5):
shorts[i] = i
sum = sum_array(shorts)
if sum != 0+1+2+3+4:
raise RuntimeError("incorrect sum, got: " + str(sum))
from li_cdata_cpp import *
s = "ABC abc"
m = malloc(256)
memmove(m, s)
ss = cdata(m, 7)
if ss != "ABC abc":
raise "failed"
from li_cdata import *
s = "ABC abc"
m = malloc(256)
memmove(m, s)
ss = cdata(m, 7)
if ss != "ABC abc":
raise "failed"
from li_cmalloc import *
p = malloc_int()
free_int(p)
ok = 0
try:
p = calloc_int(-1)
free_int(p)
except:
ok = 1
if ok != 1:
raise RuntimeError
from li_cpointer_cpp import *
p = new_intp()
if intp_value(p) != 0:
raise RuntimeError("not initialized")
intp_assign(p, 3)
if intp_value(p) != 3:
raise RuntimeError
delete_intp(p)
from li_cpointer import *
p = new_intp()
if intp_value(p) != 0:
raise RuntimeError("not initialized")
intp_assign(p, 3)
if intp_value(p) != 3:
raise RuntimeError
delete_intp(p)
from li_cstring import *
if count("ab\0ab\0ab\0", 0) != 3:
raise RuntimeError
if test1() != "Hello World":
raise RuntimeError
if test2() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_":
raise RuntimeError
if test3("hello") != "hello-suffix":
print test3("hello")
raise RuntimeError
if test4("hello") != "hello-suffix":
print test4("hello")
raise RuntimeError
if test5(4) != "xxxx":
raise RuntimeError
if test6(10) != "xxxxx":
raise RuntimeError
if test7() != "Hello world!":
raise RuntimeError
if test8() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_":
raise RuntimeError
from li_cwstring import *
if count(u"ab\0ab\0ab\0", 0) != 3:
raise RuntimeError
if test1() != u"Hello World":
raise RuntimeError
if test2() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_":
raise RuntimeError
if test3("hello") != u"hello-suffix":
raise RuntimeError
if test4("hello") != u"hello-suffix":
raise RuntimeError
if test5(4) != u"xxxx":
raise RuntimeError
if test6(10) != u"xxxxx":
raise RuntimeError
if test7() != u"Hello world!":
raise RuntimeError
if test8() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_":
raise RuntimeError
from li_factory import *
circle = Geometry_create(Geometry.CIRCLE)
r = circle.radius()
if (r != 1.5):
raise RuntimeError
point = Geometry_create(Geometry.POINT)
w = point.width()
if (w != 1.0):
raise RuntimeError
from li_implicit import *
b = B()
ai = A(1)
ad = A(2.0)
ab = A(b)
ai, get(ai)
ad, get(ad)
ab, get(ab)
if get(ai) != get(1):
raise RuntimeError, "bad implicit type"
if get(ad) != get(2.0):
raise RuntimeError, "bad implicit type"
if get(ab) != get(b):
raise RuntimeError, "bad implicit type"
from li_std_auto_ptr import *
k1 = makeKlassAutoPtr("first")
k2 = makeKlassAutoPtr("second")
if Klass_getTotal_count() != 2:
raise "number of objects should be 2"
del k1
if Klass_getTotal_count() != 1:
raise "number of objects should be 1"
if k2.getLabel() != "second":
raise "wrong object label"
del k2
if Klass_getTotal_count() != 0:
raise "no objects should be left"
from li_std_carray import *
v3 = Vector3()
for i in range(0, len(v3)):
v3[i] = i
i = 0
for d in v3:
if d != i:
raise RuntimeError
i = i + 1
m3 = Matrix3()
for i in range(0, len(m3)):
v3 = m3[i]
for j in range(0, len(v3)):
v3[j] = i + j
i = 0
for v3 in m3:
j = 0
for d in v3:
if d != i + j:
raise RuntimeError
j = j + 1
pass
i = i + 1
pass
for i in range(0, len(m3)):
for j in range(0, len(m3)):
if m3[i][j] != i + j:
raise RuntimeError
da = Vector3((1, 2, 3))
ma = Matrix3(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
# Check std::vector and std::list behaves the same as Python iterable
# types (list)
from li_std_containers_int import *
import sys
def failed(a, b, msg):
raise RuntimeError, msg + " " + str(list(a)) + " " + str(list(b))
def compare_sequences(a, b):
if len(a) != len(b):
failed(a, b, "different sizes")
for i in range(len(a)):
if a[i] != b[i]:
failed(a, b, "elements are different")
def compare_containers(pythonlist, swigvector, swiglist):
compare_sequences(pythonlist, swigvector)
compare_sequences(pythonlist, swiglist)
# Check std::vector and std::list assignment behaves same as Python list
# assignment including exceptions
def container_insert_step(i, j, step, newval):
ps = range(6)
iv = vector_int(ps)
il = list_int(ps)
# Python slice
try:
if step == None:
if j == None:
ps[i] = newval
else:
ps[i:j] = newval
else:
if j == None:
ps[i::step] = newval
else:
ps[i:j:step] = newval
ps_error = None
except ValueError, e:
ps_error = e
except IndexError, e:
ps_error = e
# std::vector<int>
try:
if step == None:
if j == None:
iv[i] = newval
else:
iv[i:j] = newval
else:
if j == None:
iv[i::step] = newval
else:
iv[i:j:step] = newval
iv_error = None
except ValueError, e:
iv_error = e
except IndexError, e:
iv_error = e
# std::list<int>
try:
if step == None:
if j == None:
il[i] = newval
else:
il[i:j] = newval
else:
if j == None:
il[i::step] = newval
else:
il[i:j:step] = newval
il_error = None
except ValueError, e:
il_error = e
except IndexError, e:
il_error = e
if not((type(ps_error) == type(iv_error)) and (type(ps_error) == type(il_error))):
raise RuntimeError, "ValueError exception not consistently thrown: " + \
str(ps_error) + " " + str(iv_error) + " " + str(il_error)
compare_containers(ps, iv, il)
# Check std::vector and std::list delete behaves same as Python list
# delete including exceptions
def container_delete_step(i, j, step):
ps = range(6)
iv = vector_int(ps)
il = list_int(ps)
# Python slice
try:
if step == None:
if j == None:
del ps[i]
else:
del ps[i:j]
else:
if j == None:
del ps[i::step]
else:
del ps[i:j:step]
ps_error = None
except ValueError, e:
ps_error = e
except IndexError, e:
ps_error = e
# std::vector<int>
try:
if step == None:
if j == None:
del iv[i]
else:
del iv[i:j]
else:
if j == None:
del iv[i::step]
else:
del iv[i:j:step]
iv_error = None
except ValueError, e:
iv_error = e
except IndexError, e:
iv_error = e
# std::list<int>
try:
if step == None:
if j == None:
del il[i]
else:
del il[i:j]
else:
if j == None:
del il[i::step]
else:
del il[i:j:step]
il_error = None
except ValueError, e:
il_error = e
except IndexError, e:
il_error = e
if not((type(ps_error) == type(iv_error)) and (type(ps_error) == type(il_error))):
raise RuntimeError, "ValueError exception not consistently thrown: " + \
str(ps_error) + " " + str(iv_error) + " " + str(il_error)
compare_containers(ps, iv, il)
ps = [0, 1, 2, 3, 4, 5]
iv = vector_int(ps)
il = list_int(ps)
# slices
compare_containers(ps[0:0], iv[0:0], il[0:0])
compare_containers(ps[1:1], iv[1:1], il[1:1])
compare_containers(ps[1:3], iv[1:3], il[1:3])
compare_containers(ps[2:4], iv[2:4], il[2:4])
compare_containers(ps[0:3], iv[0:3], il[0:3])
compare_containers(ps[3:6], iv[3:6], il[3:6])
compare_containers(ps[3:10], iv[3:10], il[3:10]) # beyond end of range
# before beginning of range (negative indexing)
compare_containers(ps[-1:7], iv[-1:7], il[-1:7])
compare_containers(ps[-2:7], iv[-2:7], il[-2:7])
compare_containers(ps[-5:7], iv[-5:7], il[-5:7])
compare_containers(ps[-6:7], iv[-6:7], il[-6:7])
# before beginning of range (negative indexing, negative index is >
# container size)
compare_containers(ps[-7:7], iv[-7:7], il[-7:7])
compare_containers(ps[-100:7], iv[-100:7], il[-100:7])
compare_containers(ps[3:], iv[3:], il[3:])
compare_containers(ps[:3], iv[:3], il[:3])
compare_containers(ps[:], iv[:], il[:])
compare_containers(ps[-3:], iv[-3:], il[-3:])
compare_containers(ps[-7:], iv[-7:], il[-7:])
compare_containers(ps[:-1], iv[:-1], il[:-1])
compare_containers(ps[:-7], iv[:-7], il[:-7])
# step slicing
compare_containers(ps[1:5:1], iv[1:5:1], il[1:5:1])
compare_containers(ps[1:5:2], iv[1:5:2], il[1:5:2])
compare_containers(ps[1:5:3], iv[1:5:3], il[1:5:3])
compare_containers(ps[1:5:4], iv[1:5:4], il[1:5:4])
compare_containers(ps[1:6:5], iv[1:6:5], il[1:6:5])
compare_containers(ps[1:7:5], iv[1:7:5], il[1:7:5])
compare_containers(ps[-1:7:1], iv[-1:7:1], il[-1:7:1])
compare_containers(ps[-1:7:2], iv[-1:7:2], il[-1:7:2])
compare_containers(ps[-6:7:2], iv[-6:7:2], il[-6:7:2])
compare_containers(ps[-100:7:2], iv[-100:7:2], il[-100:7:2])
compare_containers(ps[::1], iv[::1], il[::1])
compare_containers(ps[::2], iv[::2], il[::2])
compare_containers(ps[::-1], iv[::-1], il[::-1])
compare_containers(ps[6::-1], iv[6::-1], il[6::-1])
compare_containers(ps[:-3:-1], iv[:-3:-1], il[:-3:-1])
compare_containers(ps[:-6:-1], iv[:-6:-1], il[:-6:-1])
compare_containers(ps[:-7:-1], iv[:-7:-1], il[:-7:-1])
compare_containers(ps[:-8:-1], iv[:-8:-1], il[:-8:-1])
compare_containers(ps[:-100:-1], iv[:-100:-1], il[:-100:-1])
compare_containers(ps[4:6:-1], iv[4:6:-1], il[4:6:-1])
compare_containers(ps[4:5:-1], iv[4:5:-1], il[4:5:-1])
compare_containers(ps[4:4:-1], iv[4:4:-1], il[4:4:-1])
compare_containers(ps[4:3:-1], iv[4:3:-1], il[4:3:-1])
compare_containers(ps[4:2:-1], iv[4:2:-1], il[4:2:-1])
compare_containers(ps[100:104:-1], iv[100:104:-1], il[100:104:-1])
compare_containers(ps[104:100:-1], iv[104:100:-1], il[104:100:-1])
compare_containers(ps[-100:-104:-1], iv[-100:-104:-1], il[-100:-104:-1])
compare_containers(ps[-104:-100:-1], iv[-104:-100:-1], il[-104:-100:-1])
compare_containers(ps[::-2], iv[::-2], il[::-2])
compare_containers(ps[::-3], iv[::-3], il[::-3])
compare_containers(ps[::-4], iv[::-4], il[::-4])
compare_containers(ps[::-5], iv[::-5], il[::-5])
# insert sequences (growing, shrinking and staying same size)
for start in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]:
# single element set/replace
container_insert_step(start, None, None, 111)
for end in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]:
container_insert_step(
start, end, None, [111, 222, 333, 444, 555, 666, 777])
container_insert_step(start, end, None, [111, 222, 333, 444, 555, 666])
container_insert_step(start, end, None, [111, 222, 333, 444, 555])
container_insert_step(start, end, None, [111, 222, 333, 444])
container_insert_step(start, end, None, [111, 222, 333])
container_insert_step(start, end, None, [111, 222])
container_insert_step(start, end, None, [111])
container_insert_step(start, end, None, [])
# delete sequences (growing, shrinking and staying same size)
for start in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]:
# single element delete
container_delete_step(start, None, None)
for end in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]:
container_delete_step(start, end, None)
for step in range(-7, 7):
container_delete_step(start, end, step)
ps = range(6)
iv = vector_int(ps)
il = list_int(ps)
del ps[:]
del iv[:]
del il[:]
compare_containers(ps, iv, il)
for end in range(7):
for step in range(-7, 7):
for start in range(7):
container_insert_step(
start, end, step, [111, 222, 333, 444, 555, 666, 777])
container_insert_step(
start, end, step, [111, 222, 333, 444, 555, 666])
container_insert_step(start, end, step, [111, 222, 333, 444, 555])
container_insert_step(start, end, step, [111, 222, 333, 444])
container_insert_step(start, end, step, [111, 222, 333])
container_insert_step(start, end, step, [111, 222])
container_insert_step(start, end, step, [111])
container_insert_step(start, end, step, [])
try:
x = iv[::0]
raise RuntimeError("Zero step not caught")
except ValueError:
pass
from li_std_containers_overload import *
def check(got, expected):
if got != expected:
raise RuntimeError("Failed check. '{}' != '{}'".format(got, expected))
v = VectorX()
check(VectorOverload(v), "vector<X>")
v = VectorY()
check(VectorOverload(v), "vector<Y>")
v = VectorInt()
check(VectorOverload(v), "vector<int>")
v = VectorString()
check(VectorOverload(v), "vector<string>")
v = [X()]
check(VectorOverload(v), "vector<X>")
v = [Y()]
check(VectorOverload(v), "vector<Y>")
v = [1, 2, 3]
check(VectorOverload(v), "vector<int>")
v = ["aaa", "bbb", "ccc"]
check(VectorOverload(v), "vector<string>")
from li_std_except_as_class import *
# This test is expected to fail with -builtin option.
# Throwing builtin classes as exceptions not supported
if is_python_builtin():
try:
test_domain_error()
except RuntimeError:
pass
try:
test_domain_error()
except RuntimeError:
pass
try:
test_domain_error()
except RuntimeError:
pass
else:
# std::domain_error hierarchy
try:
test_domain_error()
except domain_error:
pass
try:
test_domain_error()
except logic_error:
pass
try:
test_domain_error()
except exception:
pass
import li_std_map_member
a = li_std_map_member.mapita()
a[1] = li_std_map_member.TestA()
if (a[1].i != 1):
raise RuntimeError("a[1] != 1")
a[1].i = 2
if (a[1].i != 2):
raise RuntimeError("a[1] != 2")
import li_std_map
a1 = li_std_map.A(3)
a2 = li_std_map.A(7)
p0 = li_std_map.pairii(1, 2)
p1 = li_std_map.pairA(1, a1.this)
m = {}
m[1] = a1
m[2] = a2
pp1 = li_std_map.p_identa(p1)
mm = li_std_map.m_identa(m)
m = li_std_map.mapA()
m[1] = a1
m[2] = a2
pm = {}
for k in m:
pm[k] = m[k]
for k in m:
if pm[k].this != m[k].this:
print pm[k], m[k]
raise RuntimeError
m = {}
m[1] = (1, 2)
m["foo"] = "hello"
pm = li_std_map.pymap()
for k in m:
pm[k] = m[k]
for k in pm:
if (pm[k] != m[k]):
raise RuntimeError
mii = li_std_map.IntIntMap()
mii[1] = 1
mii[1] = 2
if mii[1] != 2:
raise RuntimeError
if mii.keys() != [1]:
raise RuntimeError("keys")
if mii.values() != [2]:
raise RuntimeError("values")
if mii.items() != [(1, 2)]:
raise RuntimeError("items")
if [k for k in mii] != [1]:
raise RuntimeError("iteration")
if [i for i in mii.iterkeys()] != [1]:
raise RuntimeError("iterkeys")
if [i for i in mii.itervalues()] != [2]:
raise RuntimeError("itervalues")
if [i for i in mii.iteritems()] != [(1, 2)]:
raise RuntimeError("iteritems")
slmap = li_std_map.StringLengthNumberMap()
li_std_map.populate(slmap)
keys = " ".join([k for k in slmap.keys()])
if keys != "a aa zzz xxxx aaaaa":
raise RuntimeError("Keys are wrong or in wrong order: " + keys)
values = " ".join([str(v) for v in slmap.values()])
if values != "1 2 3 4 5":
raise RuntimeError("Values are wrong or in wrong order: " + values)
import li_std_pair_extra
p = (1, 2)
p1 = li_std_pair_extra.p_inout(p)
p2 = li_std_pair_extra.p_inoutd(p1)
d1 = li_std_pair_extra.d_inout(2)
i, d2 = li_std_pair_extra.d_inout2(2)
i, p = li_std_pair_extra.p_inout2(p)
p3, p4 = li_std_pair_extra.p_inout3(p1, p1)
psi = li_std_pair_extra.SIPair("hello", 1)
pci = li_std_pair_extra.CIPair(1, 1)
#psi.first = "hi"
psi = li_std_pair_extra.SIPair("hi", 1)
if psi != ("hi", 1):
raise RuntimeError
psii = li_std_pair_extra.SIIPair(psi, 1)
a = li_std_pair_extra.A()
b = li_std_pair_extra.B()
pab = li_std_pair_extra.ABPair(a, b)
pab.first = a
pab.first.val = 2
if pab.first.val != 2:
raise RuntimeError
pci = li_std_pair_extra.CIntPair(1, 0)
a = li_std_pair_extra.A(5)
p1 = li_std_pair_extra.pairP1(1, a.this)
p2 = li_std_pair_extra.pairP2(a, 1)
p3 = li_std_pair_extra.pairP3(a, a)
if a.val != li_std_pair_extra.p_identa(p1.this)[1].val:
raise RuntimeError
p = li_std_pair_extra.IntPair(1, 10)
p.first = 1
p = li_std_pair_extra.paircA1(1, a)
p.first
p.second
p = li_std_pair_extra.paircA2(1, a)
pp = li_std_pair_extra.pairiiA(1, p)
from li_std_pair_using import *
one_tuple = ("one", "numero uno")
one = StringStringPair(one_tuple)
two_tuple = ("two", 2)
two = StringIntPair(two_tuple)
if bounce(one) != one_tuple:
raise RuntimeError
from li_std_set import *
s = set_string()
s.append("a")
s.append("b")
s.append("c")
sum = ""
for i in s:
sum = sum + i
if sum != "abc":
raise RuntimeError
i = s.__iter__()
if i.next() != "a":
raise RuntimeError
if i.next() != "b":
raise RuntimeError
if i.next() != "c":
raise RuntimeError
b = s.begin()
e = s.end()
sum = ""
while (b != e):
sum = sum + b.next()
if sum != "abc":
raise RuntimeError
b = s.rbegin()
e = s.rend()
sum = ""
while (b != e):
sum = sum + b.next()
if sum != "cba":
raise RuntimeError
si = set_int()
si.append(1)
si.append(2)
si.append(3)
i = si.__iter__()
if i.next() != 1:
raise RuntimeError
if i.next() != 2:
raise RuntimeError
if i.next() != 3:
raise RuntimeError
if si[0] != 1:
raise RuntimeError
i = s.begin()
i.next()
s.erase(i)
b = s.begin()
e = s.end()
sum = ""
while (b != e):
sum = sum + b.next()
if sum != "ac":
raise RuntimeError
b = s.begin()
e = s.end()
if e - b != 2:
raise RuntimeError
m = b + 1
if m.value() != "c":
raise RuntimeError
s = pyset()
s.insert((1, 2))
s.insert(1)
s.insert("hello")
sum = ()
for i in s:
sum = sum + (i,)
if (len(sum) != 3 or (not 1 in sum) or (not "hello" in sum) or (not (1, 2) in sum)):
raise RuntimeError
from li_std_stream import *
a = A()
o = ostringstream()
o << a << " " << 2345 << " " << 1.435
if o.str() != "A class 2345 1.435":
print "\"%s\"" % (o.str(),)
raise RuntimeError
import li_std_string_extra
x = "hello"
if li_std_string_extra.test_ccvalue(x) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_cvalue(x) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_value(x) != x:
print x, li_std_string_extra.test_value(x)
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_const_reference(x) != x:
raise RuntimeError, "bad string mapping"
s = li_std_string_extra.string("he")
#s += "ll"
# s.append("o")
s = s + "llo"
if s != x:
print s, x
raise RuntimeError, "bad string mapping"
if s[1:4] != x[1:4]:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_value(s) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_const_reference(s) != x:
raise RuntimeError, "bad string mapping"
a = li_std_string_extra.A(s)
if li_std_string_extra.test_value(a) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_const_reference(a) != x:
raise RuntimeError, "bad string mapping"
b = li_std_string_extra.string(" world")
s = a + b
if a + b != "hello world":
print a + b
raise RuntimeError, "bad string mapping"
if a + " world" != "hello world":
raise RuntimeError, "bad string mapping"
# This is expected to fail with -builtin option
# Reverse operators not supported in builtin types
if not li_std_string_extra.is_python_builtin():
if "hello" + b != "hello world":
raise RuntimeError, "bad string mapping"
c = "hello" + b
if c.find_last_of("l") != 9:
raise RuntimeError, "bad string mapping"
s = "hello world"
b = li_std_string_extra.B("hi")
b.name = li_std_string_extra.string("hello")
if b.name != "hello":
raise RuntimeError, "bad string mapping"
b.a = li_std_string_extra.A("hello")
if b.a != "hello":
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_value_basic1(x) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_value_basic2(x) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_value_basic3(x) != x:
raise RuntimeError, "bad string mapping"
if li_std_string_extra.test_value_basic_overload(x) != x:
raise RuntimeError, "bad overload string"
if li_std_string_extra.test_value_basic_overload(123) != "int":
raise RuntimeError, "bad overload int"
try:
li_std_string_extra.test_value_basic_overload([x])
raise RuntimeError, "should throw TypeError"
except TypeError as e:
if str(e).find("Possible C/C++ prototypes are:") == -1:
raise RuntimeError("Incorrect error message text:\n{}".format(e))
pass
try:
li_std_string_extra.test_value_basic_overload([123])
raise RuntimeError, "should throw TypeError"
except TypeError as e:
if str(e).find("Possible C/C++ prototypes are:") == -1:
raise RuntimeError("Incorrect error message text:\n{}".format(e))
pass
# Global variables
s = "initial string"
if li_std_string_extra.cvar.GlobalString2 != "global string 2":
raise RuntimeError, "GlobalString2 test 1"
li_std_string_extra.cvar.GlobalString2 = s
if li_std_string_extra.cvar.GlobalString2 != s:
raise RuntimeError, "GlobalString2 test 2"
if li_std_string_extra.cvar.ConstGlobalString != "const global string":
raise RuntimeError, "ConstGlobalString test"
# Member variables
myStructure = li_std_string_extra.Structure()
if myStructure.MemberString2 != "member string 2":
raise RuntimeError, "MemberString2 test 1"
myStructure.MemberString2 = s
if myStructure.MemberString2 != s:
raise RuntimeError, "MemberString2 test 2"
if myStructure.ConstMemberString != "const member string":
raise RuntimeError, "ConstMemberString test"
if li_std_string_extra.cvar.Structure_StaticMemberString2 != "static member string 2":
raise RuntimeError, "StaticMemberString2 test 1"
li_std_string_extra.cvar.Structure_StaticMemberString2 = s
if li_std_string_extra.cvar.Structure_StaticMemberString2 != s:
raise RuntimeError, "StaticMemberString2 test 2"
if li_std_string_extra.cvar.Structure_ConstStaticMemberString != "const static member string":
raise RuntimeError, "ConstStaticMemberString test"
if li_std_string_extra.test_reference_input("hello") != "hello":
raise RuntimeError
s = li_std_string_extra.test_reference_inout("hello")
if s != "hellohello":
raise RuntimeError
if li_std_string_extra.stdstring_empty() != "":
raise RuntimeError
if li_std_string_extra.c_empty() != "":
raise RuntimeError
if li_std_string_extra.c_null() != None:
raise RuntimeError
from li_std_vector_back_reference import *
def first_element():
v = VectorWheel((Wheel(11), Wheel(22)))
# v will be deleted after exit from this method
return v[0]
size = first_element().size
if size != 11:
raise RuntimeError("Back reference not working {}".format(size))
import li_std_vector_enum
def check(a, b):
if (a != b):
raise RuntimeError("Not equal: ", a, b)
ev = li_std_vector_enum.EnumVector()
check(ev.nums[0], 10)
check(ev.nums[1], 20)
check(ev.nums[2], 30)
it = ev.nums.iterator()
v = it.value()
check(v, 10)
it.next()
v = it.value()
check(v, 20)
expected = 10
for val in ev.nums:
check(val, expected)
expected += 10
from li_std_vector_extra import *
iv = IntVector(4)
for i in range(0, 4):
iv[i] = i
x = average(iv)
y = average([1, 2, 3, 4])
a = half([10, 10.5, 11, 11.5])
dv = DoubleVector(10)
for i in range(0, 10):
dv[i] = i / 2.0
halve_in_place(dv)
bv = BoolVector(4)
bv[0] = bool(1)
bv[1] = bool(0)
bv[2] = bool(4)
bv[3] = bool(0)
if bv[0] != bv[2]:
raise RuntimeError, "bad std::vector<bool> mapping"
b = B(5)
va = VecA([b, None, b, b])
if va[0].f(1) != 6:
raise RuntimeError, "bad std::vector<A*> mapping"
if vecAptr(va) != 6:
raise RuntimeError, "bad std::vector<A*> mapping"
b.val = 7
if va[3].f(1) != 8:
raise RuntimeError, "bad std::vector<A*> mapping"
ip = PtrInt()
ap = new_ArrInt(10)
ArrInt_setitem(ip, 0, 123)
ArrInt_setitem(ap, 2, 123)
vi = IntPtrVector((ip, ap, None))
if ArrInt_getitem(vi[0], 0) != ArrInt_getitem(vi[1], 2):
raise RuntimeError, "bad std::vector<int*> mapping"
delete_ArrInt(ap)
a = halfs([10, 8, 4, 3])
v = IntVector()
v[0:2] = [1, 2]
if v[0] != 1 or v[1] != 2:
raise RuntimeError, "bad setslice"
if v[0:-1][0] != 1:
raise RuntimeError, "bad getslice"
if v[0:-2].size() != 0:
raise RuntimeError, "bad getslice"
v[0:1] = [2]
if v[0] != 2:
raise RuntimeError, "bad setslice"
v[1:] = [3]
if v[1] != 3:
raise RuntimeError, "bad setslice"
v[2:] = [3]
if v[2] != 3:
raise RuntimeError, "bad setslice"
if v[0:][0] != v[0]:
raise RuntimeError, "bad getslice"
del v[:]
if v.size() != 0:
raise RuntimeError, "bad getslice"
del v[:]
if v.size() != 0:
raise RuntimeError, "bad getslice"
v = vecStr(["hello ", "world"])
if v[0] != "hello world":
raise RuntimeError, "bad std::string+std::vector"
pv = pyvector([1, "hello", (1, 2)])
if pv[1] != "hello":
raise RuntimeError
iv = IntVector(5)
for i in range(0, 5):
iv[i] = i
iv[1:3] = []
if iv[1] != 3:
raise RuntimeError
# Overloading checks
if overloaded1(iv) != "vector<int>":
raise RuntimeError
if overloaded1(dv) != "vector<double>":
raise RuntimeError
if overloaded2(iv) != "vector<int>":
raise RuntimeError
if overloaded2(dv) != "vector<double>":
raise RuntimeError
if overloaded3(iv) != "vector<int> *":
raise RuntimeError
if overloaded3(None) != "vector<int> *":
raise RuntimeError
if overloaded3(100) != "int":
raise RuntimeError
# vector pointer checks
ip = makeIntPtr(11)
dp = makeDoublePtr(33.3)
error = 0
try:
# check vector<int *> does not accept double * element
vi = IntPtrVector((ip, dp))
error = 1
except:
pass
if error:
raise RuntimeError
vi = IntPtrVector((ip, makeIntPtr(22)))
if extractInt(vi[0]) != 11:
raise RuntimeError
if extractInt(vi[1]) != 22:
raise RuntimeError
# vector const pointer checks
csp = makeConstShortPtr(111)
error = 0
try:
# check vector<const unsigned short *> does not accept double * element
vcs = ConstShortPtrVector((csp, dp))
error = 1
except:
pass
if error:
raise RuntimeError
vcs = ConstShortPtrVector((csp, makeConstShortPtr(222)))
if extractConstShort(vcs[0]) != 111:
raise RuntimeError
if extractConstShort(vcs[1]) != 222:
raise RuntimeError
for p in vcs[0:1]:
if extractConstShort2(p) != 111:
raise RuntimeError
for p in vcs[1:2]:
if extractConstShort2(p) != 222:
raise RuntimeError
from li_std_vector_ptr import *
def check(val1, val2):
if val1 != val2:
raise RuntimeError("Values are not the same %s %s" % (val1, val2))
ip1 = makeIntPtr(11)
ip2 = makeIntPtr2(22)
vi = IntPtrVector((ip1, ip2))
check(getValueFromVector(vi, 0), 11)
check(getValueFromVector(vi, 1), 22)
check(getIntValue(vi[0]), 11)
check(getIntValue(vi[1]), 22)
check(getIntValue2(vi[0]), 11)
check(getIntValue2(vi[1]), 22)
ipp = makeIntPtrPtr(vi[0])
check(getIntValue3(ipp), 11) # Note: getIntValue3 takes int**
vA = APtrVector([makeA(33), makeA(34)])
check(getVectorValueA(vA, 0), 33)
vB = BPtrVector([makeB(133), makeB(134)])
check(getVectorValueB(vB, 0), 133)
vC = CPtrVector([makeC(1133), makeC(1134)])
check(getVectorValueC(vC, 0), 1133)
vA = [makeA(233), makeA(234)]
check(getVectorValueA(vA, 0), 233)
vB = [makeB(333), makeB(334)]
check(getVectorValueB(vB, 0), 333)
vC = [makeC(3333), makeC(3334)]
check(getVectorValueC(vC, 0), 3333)
# mixed A and B should not be accepted
vAB = [makeA(999), makeB(999)]
try:
check(getVectorValueA(vAB, 0), 999)
raise RuntimeError("missed exception")
except TypeError:
pass
b111 = makeB(111)
bNones = BPtrVector([None, b111, None])
bCount = 0
noneCount = 0
for b in bNones:
if b == None:
noneCount = noneCount + 1
else:
if b.val != 111:
raise RuntimeError("b.val is wrong")
bCount = bCount + 1
if bCount != 1:
raise RuntimeError("bCount wrong")
if noneCount != 2:
raise RuntimeError("noneCount wrong")
from li_std_vector import *
if typedef_test(101) != 101:
raise RuntimeError
try:
sv = StructVector([None, None])
raise RuntimeError("Using None should result in a TypeError")
except TypeError:
pass
from li_std_wstream import *
a = A()
o = wostringstream()
o << a << u" " << 2345 << u" " << 1.435 << wends
if o.str() != "A class 2345 1.435\0":
print "\"%s\"" % (o.str(),)
raise RuntimeError
import li_std_wstring_inherit
import sys
x = u"hello"
s = li_std_wstring_inherit.wstring(u"he")
s = s + u"llo"
if s != x:
print s, x
raise RuntimeError("bad string mapping")
if s[1:4] != x[1:4]:
raise RuntimeError("bad string mapping")
a = li_std_wstring_inherit.A(s)
b = li_std_wstring_inherit.wstring(" world")
if a + b != "hello world":
raise RuntimeError("bad string mapping")
if a + " world" != "hello world":
raise RuntimeError("bad string mapping")
# This is expected to fail if -builtin is used
# Reverse operators not supported in builtin types
if not li_std_wstring_inherit.is_python_builtin():
if "hello" + b != "hello world":
raise RuntimeError("bad string mapping")
c = "hello" + b
if c.find_last_of("l") != 9:
raise RuntimeError("bad string mapping")
b = li_std_wstring_inherit.B("hi")
b.name = li_std_wstring_inherit.wstring(u"hello")
if b.name != "hello":
raise RuntimeError("bad string mapping")
b.a = li_std_wstring_inherit.A("hello")
if b.a != u"hello":
raise RuntimeError("bad string mapping")
import li_std_wstring
import sys
def check_equal(a, b):
if a != b:
raise RuntimeError("failed {} {}".format(a, b))
h = u"h"
check_equal(li_std_wstring.test_wcvalue(h), h)
x = u"abc"
check_equal(li_std_wstring.test_ccvalue(x), x)
check_equal(li_std_wstring.test_cvalue(x), x)
check_equal(li_std_wstring.test_wchar_overload(x), x)
check_equal(li_std_wstring.test_wchar_overload(), None)
li_std_wstring.test_pointer(None)
li_std_wstring.test_const_pointer(None)
try:
li_std_wstring.test_value(None)
raise RuntimeError("NULL check failed")
except TypeError as e:
pass
try:
li_std_wstring.test_reference(None)
raise RuntimeError("NULL check failed")
except ValueError as e:
if "invalid null reference" not in str(e):
raise RuntimeError("Missing text {}".format(e))
try:
li_std_wstring.test_const_reference(None)
raise RuntimeError("NULL check failed")
except ValueError as e:
if "invalid null reference" not in str(e):
raise RuntimeError("Missing text {}".format(e))
x = "hello"
check_equal(li_std_wstring.test_const_reference(x), x)
s = "abc"
if not li_std_wstring.test_equal_abc(s):
raise RuntimeError("Not equal {}".format(s))
try:
li_std_wstring.test_throw
except RuntimeError as e:
check_equal(e.message, "throwing test_throw")
x = "abc\0def"
check_equal(li_std_wstring.test_value(x), x)
check_equal(li_std_wstring.test_ccvalue(x), "abc")
check_equal(li_std_wstring.test_wchar_overload(x), "abc")
################### Python specific
# Byte strings only converted in Python 2
if sys.version_info[0:2] < (3, 0):
x = b"hello there"
if li_std_wstring.test_value(x) != x:
raise RuntimeError("bad string mapping")
# Invalid utf-8 in a byte string fails in all versions
x = b"h\xe9llo"
try:
li_std_wstring.test_value(x)
raise RuntimeError("TypeError not thrown")
except TypeError:
pass
# Check surrogateescape
if sys.version_info[0:2] > (3, 1):
x = u"h\udce9llo" # surrogate escaped representation of C char*: "h\xe9llo"
if li_std_wstring.non_utf8_c_str() != x:
raise RuntimeError("surrogateescape not working")
if li_std_wstring.size_wstring(x) != 5 and len(x) != 5:
raise RuntimeError("Unexpected length")
import memberin_extend_c
t = memberin_extend_c.Person()
t.name = "Fred Bloggs"
if t.name != "FRED BLOGGS":
raise RuntimeError("name wrong")
# Example using pointers to member functions
from member_pointer_const import *
def check(what, expected, actual):
if expected != actual:
raise RuntimeError(
"Failed: ", what, " Expected: ", expected, " Actual: ", actual)
# Get the pointers
area_pt = areapt()
perim_pt = perimeterpt()
# Create some objects
s = Square(10)
# Do some calculations
check("Square area ", 100.0, do_op(s, area_pt))
check("Square perim", 40.0, do_op(s, perim_pt))
memberPtr = cvar.areavar
memberPtr = cvar.perimetervar
# Try the variables
check("Square area ", 100.0, do_op(s, cvar.areavar))
check("Square perim", 40.0, do_op(s, cvar.perimetervar))
# Modify one of the variables
cvar.areavar = perim_pt
check("Square perimeter", 40.0, do_op(s, cvar.areavar))
# Try the constants
memberPtr = AREAPT
memberPtr = PERIMPT
memberPtr = NULLPT
check("Square area ", 100.0, do_op(s, AREAPT))
check("Square perim", 40.0, do_op(s, PERIMPT))
# Typedefs
check("Square perim", 40.0, do_op_td(s, perim_pt));
check("Add by value", 3, call1(ADD_BY_VALUE, 1, 2))
#check("Add by pointer", 7, call2(ADD_BY_POINTER, 3, 4))
#check("Add by reference", 11, call3(ADD_BY_REFERENCE, 5, 6))
# Example using pointers to member functions
from member_pointer import *
def check(what, expected, actual):
if expected != actual:
raise RuntimeError(
"Failed: ", what, " Expected: ", expected, " Actual: ", actual)
# Get the pointers
area_pt = areapt()
perim_pt = perimeterpt()
# Create some objects
s = Square(10)
# Do some calculations
check("Square area ", 100.0, do_op(s, area_pt))
check("Square perim", 40.0, do_op(s, perim_pt))
memberPtr = cvar.areavar
memberPtr = cvar.perimetervar
# Try the variables
check("Square area ", 100.0, do_op(s, cvar.areavar))
check("Square perim", 40.0, do_op(s, cvar.perimetervar))
# Modify one of the variables
cvar.areavar = perim_pt
check("Square perimeter", 40.0, do_op(s, cvar.areavar))
# Try the constants
memberPtr = AREAPT
memberPtr = PERIMPT
memberPtr = NULLPT
check("Square area ", 100.0, do_op(s, AREAPT))
check("Square perim", 40.0, do_op(s, PERIMPT))
# Typedefs
check("Square perim", 40.0, do_op_td(s, perim_pt));
check("Add by value", 3, call1(ADD_BY_VALUE, 1, 2))
check("Add by pointer", 7, call2(ADD_BY_POINTER, 3, 4))
check("Add by reference", 11, call3(ADD_BY_REFERENCE, 5, 6))
import minherit
a = minherit.Foo()
b = minherit.Bar()
c = minherit.FooBar()
d = minherit.Spam()
if a.xget() != 1:
raise RuntimeError, "Bad attribute value"
if b.yget() != 2:
raise RuntimeError, "Bad attribute value"
if c.xget() != 1 or c.yget() != 2 or c.zget() != 3:
raise RuntimeError, "Bad attribute value"
if d.xget() != 1 or d.yget() != 2 or d.zget() != 3 or d.wget() != 4:
raise RuntimeError, "Bad attribute value"
if minherit.xget(a) != 1:
raise RuntimeError, "Bad attribute value %d" % (minherit.xget(a))
if minherit.yget(b) != 2:
raise RuntimeError, "Bad attribute value %d" % (minherit.yget(b))
if minherit.xget(c) != 1 or minherit.yget(c) != 2 or minherit.zget(c) != 3:
raise RuntimeError, "Bad attribute value %d %d %d" % (
minherit.xget(c), minherit.yget(c), minherit.zget(c))
if minherit.xget(d) != 1 or minherit.yget(d) != 2 or minherit.zget(d) != 3 or minherit.wget(d) != 4:
raise RuntimeError, "Bad attribute value %d %d %d %d" % (
minherit.xget(d), minherit.yget(d), minherit.zget(d), minherit.wget(d))
# Cleanse all of the pointers and see what happens
aa = minherit.toFooPtr(a)
bb = minherit.toBarPtr(b)
cc = minherit.toFooBarPtr(c)
dd = minherit.toSpamPtr(d)
if aa.xget() != 1:
raise RuntimeError, "Bad attribute value"
if bb.yget() != 2:
raise RuntimeError, "Bad attribute value"
if cc.xget() != 1 or cc.yget() != 2 or cc.zget() != 3:
raise RuntimeError, "Bad attribute value"
if dd.xget() != 1 or dd.yget() != 2 or dd.zget() != 3 or dd.wget() != 4:
raise RuntimeError, "Bad attribute value"
if minherit.xget(aa) != 1:
raise RuntimeError, "Bad attribute value %d" % (minherit.xget(aa))
if minherit.yget(bb) != 2:
raise RuntimeError, "Bad attribute value %d" % (minherit.yget(bb))
if minherit.xget(cc) != 1 or minherit.yget(cc) != 2 or minherit.zget(cc) != 3:
raise RuntimeError, "Bad attribute value %d %d %d" % (
minherit.xget(cc), minherit.yget(cc), minherit.zget(cc))
if minherit.xget(dd) != 1 or minherit.yget(dd) != 2 or minherit.zget(dd) != 3 or minherit.wget(dd) != 4:
raise RuntimeError, "Bad attribute value %d %d %d %d" % (
minherit.xget(dd), minherit.yget(dd), minherit.zget(dd), minherit.wget(dd))
import mod_a
import mod_b
c = mod_b.C()
d = mod_b.D()
d.DoSomething(c)
import multi_import_a
import multi_import_b
x = multi_import_b.XXX()
if x.testx() != 0:
raise RuntimeError
y = multi_import_b.YYY()
if y.testx() != 0:
raise RuntimeError
if y.testy() != 1:
raise RuntimeError
z = multi_import_a.ZZZ()
if z.testx() != 0:
raise RuntimeError
if z.testz() != 2:
raise RuntimeError
from namespace_class import *
try:
p = Private1()
error = 1
except:
error = 0
if (error):
raise RuntimeError, "Private1 is private"
try:
p = Private2()
error = 1
except:
error = 0
if (error):
raise RuntimeError, "Private2 is private"
EulerT3D.toFrame(1, 1, 1)
b = BooT_i()
b = BooT_H()
f = FooT_i()
f.quack(1)
f = FooT_d()
f.moo(1)
f = FooT_H()
f.foo(Hi)
f_type = str(type(f))
if f_type.find("'namespace_class.FooT_H'") == -1:
raise RuntimeError("Incorrect type: " + f_type)
from namespace_typemap import *
if stest1("hello") != "hello":
raise RuntimeError
if stest2("hello") != "hello":
raise RuntimeError
if stest3("hello") != "hello":
raise RuntimeError
if stest4("hello") != "hello":
raise RuntimeError
if stest5("hello") != "hello":
raise RuntimeError
if stest6("hello") != "hello":
raise RuntimeError
if stest7("hello") != "hello":
raise RuntimeError
if stest8("hello") != "hello":
raise RuntimeError
if stest9("hello") != "hello":
raise RuntimeError
if stest10("hello") != "hello":
raise RuntimeError
if stest11("hello") != "hello":
raise RuntimeError
if stest12("hello") != "hello":
raise RuntimeError
c = complex(2, 3)
r = c.real
if ctest1(c) != r:
raise RuntimeError
if ctest2(c) != r:
raise RuntimeError
if ctest3(c) != r:
raise RuntimeError
if ctest4(c) != r:
raise RuntimeError
if ctest5(c) != r:
raise RuntimeError
if ctest6(c) != r:
raise RuntimeError
if ctest7(c) != r:
raise RuntimeError
if ctest8(c) != r:
raise RuntimeError
if ctest9(c) != r:
raise RuntimeError
if ctest10(c) != r:
raise RuntimeError
if ctest11(c) != r:
raise RuntimeError
if ctest12(c) != r:
raise RuntimeError
try:
ttest1(-14)
raise RuntimeError
except ValueError:
pass
import namespace_virtual_method
x = namespace_virtual_method.Spam()
from naturalvar import *
f = Foo()
b = Bar()
b.f = f
cvar.s = "hello"
b.s = "hello"
if b.s != cvar.s:
raise RuntimeError
from nested_in_template import *
cd = ConcreteDerived(88)
if cd.m_value != 88:
raise RuntimeError("ConcreteDerived not created correctly")
from nested import *
def check(a, b):
if a != b:
raise RuntimeError("Problem: {} != {}".format(a, b))
xx = x_t()
yy = y_t()
aa = a_t()
bb = b_t()
cc = c_t()
dd = d_t()
set_union_values(100, xx, yy, aa, bb, cc, dd)
check(xx.duplicate_p.x, 100)
check(yy.duplicate_p.y, 101)
check(aa.duplicate_p.a, 102)
check(bb.duplicate_p.b, 103)
check(cc.duplicate_p.c, 104)
check(dd.duplicate_p.d, 105)
from nested_template_base import *
ois = InnerS(123)
oic = InnerC()
# Check base method is available
if (oic.outer(ois).val != 123):
raise RuntimeError("Wrong value calling outer")
# Check non-derived class using base class
if (oic.innerc().outer(ois).val != 123):
raise RuntimeError("Wrong value calling innerc")
from nested_workaround import *
inner = Inner(5)
outer = Outer()
newInner = outer.doubleInnerValue(inner)
if newInner.getValue() != 10:
raise RuntimeError
outer = Outer()
inner = outer.createInner(3)
newInner = outer.doubleInnerValue(inner)
if outer.getInnerValue(newInner) != 6:
raise RuntimeError
from operator_overload import *
# first check all the operators are implemented correctly from pure C++ code
Op_sanity_check()
pop = Op(6)/Op(3)
# test routine:
a=Op()
b=Op(5)
c=Op(b) # copy construct
d=Op(2)
dd=d # assignment operator
# test equality
if not a!=b:
raise RuntimeError("a!=b")
if not b==c:
raise RuntimeError("b==c")
if not a!=d:
raise RuntimeError("a!=d")
if not d==dd:
raise RuntimeError("d==dd")
# test <
if not a<b:
raise RuntimeError("a<b")
if not a<=b:
raise RuntimeError("a<=b")
if not b<=c:
raise RuntimeError("b<=c")
if not b>=c:
raise RuntimeError("b>=c")
if not b>d:
raise RuntimeError("b>d")
if not b>=d:
raise RuntimeError("b>=d")
# test +=
e=Op(3)
e+=d
if not e==b:
raise RuntimeError("e==b (%s==%s)" % (e.i, b.i))
e-=c
if not e==a:
raise RuntimeError("e==a")
e=Op(1)
e*=b
if not e==c:
raise RuntimeError("e==c")
e/=d
if not e==d:
raise RuntimeError("e==d")
e%=c;
if not e==d:
raise RuntimeError("e==d")
# test +
f=Op(1)
g=Op(1)
if not f+g==Op(2):
raise RuntimeError("f+g==Op(2)")
if not f-g==Op(0):
raise RuntimeError("f-g==Op(0)")
if not f*g==Op(1):
raise RuntimeError("f*g==Op(1)")
if not f/g==Op(1):
raise RuntimeError("f/g==Op(1)")
if not f%g==Op(0):
raise RuntimeError("f%g==Op(0)")
# test unary operators
if not -a==a:
raise RuntimeError("-a==a")
if not -b==Op(-5):
raise RuntimeError("-b==Op(-5)")
# test functors
if not b()==5:
raise RuntimeError("functor")
if not b(1)==6:
raise RuntimeError("functor")
if not b(1, 2)==8:
raise RuntimeError("functor")
#!/usr/bin/env python
import operbool
if operbool.Test():
raise RuntimeError("operbool failed")
import overload_bool
# Overloading bool, int, string
if overload_bool.overloaded(True) != "bool":
raise RuntimeError("wrong!")
if overload_bool.overloaded(False) != "bool":
raise RuntimeError("wrong!")
if overload_bool.overloaded(0) != "int":
raise RuntimeError("wrong!")
if overload_bool.overloaded(1) != "int":
raise RuntimeError("wrong!")
if overload_bool.overloaded(2) != "int":
raise RuntimeError("wrong!")
if overload_bool.overloaded("1234") != "string":
raise RuntimeError("wrong!")
# Test bool masquerading as int
if overload_bool.intfunction(True) != "int":
raise RuntimeError("wrong!")
if overload_bool.intfunction(False) != "int":
raise RuntimeError("wrong!")
# Test int masquerading as bool
# Not possible
#############################################
# Overloading bool, int, string
if overload_bool.overloaded_ref(True) != "bool":
raise RuntimeError("wrong!")
if overload_bool.overloaded_ref(False) != "bool":
raise RuntimeError("wrong!")
if overload_bool.overloaded_ref(0) != "int":
raise RuntimeError("wrong!")
if overload_bool.overloaded_ref(1) != "int":
raise RuntimeError("wrong!")
if overload_bool.overloaded_ref(2) != "int":
raise RuntimeError("wrong!")
if overload_bool.overloaded_ref("1234") != "string":
raise RuntimeError("wrong!")
# Test bool masquerading as int
if overload_bool.intfunction_ref(True) != "int":
raise RuntimeError("wrong!")
if overload_bool.intfunction_ref(False) != "int":
raise RuntimeError("wrong!")
# Test int masquerading as bool
# Not possible
from overload_complicated import *
pInt = None
# Check the correct constructors are available
p = Pop(pInt)
p = Pop(pInt, False)
# Check overloaded in const only and pointers/references which target
# languages cannot disambiguate
if p.hip(False) != 701:
raise RuntimeError, "Test 1 failed"
if p.hip(pInt) != 702:
raise RuntimeError, "Test 2 failed"
# Reverse the order for the above
if p.hop(pInt) != 805:
raise RuntimeError, "Test 3 failed"
if p.hop(False) != 801:
raise RuntimeError, "Test 4 failed"
# Few more variations and order shuffled
if p.pop(False) != 901:
raise RuntimeError, "Test 5 failed"
if p.pop(pInt) != 904:
raise RuntimeError, "Test 6 failed"
if p.pop() != 905:
raise RuntimeError, "Test 7 failed"
# Overload on const only
if p.bop(pInt) != 1001:
raise RuntimeError, "Test 8 failed"
if p.bip(pInt) != 2002:
raise RuntimeError, "Test 9 failed"
# Globals
if muzak(False) != 3001:
raise RuntimeError, "Test 10 failed"
if muzak(pInt) != 3002:
raise RuntimeError, "Test 11 failed"
from overload_copy import *
f = Foo()
g = Foo(f)
import overload_extend2
f = overload_extend2.Foo()
if f.test(3) != 1:
raise RuntimeError
if f.test("hello") != 2:
raise RuntimeError
if f.test(3.5, 2.5) != 3:
raise RuntimeError
if f.test("hello", 20) != 1020:
raise RuntimeError
if f.test("hello", 20, 100) != 120:
raise RuntimeError
# C default args
if f.test(f) != 30:
raise RuntimeError
if f.test(f, 100) != 120:
raise RuntimeError
if f.test(f, 100, 200) != 300:
raise RuntimeError
import overload_extend_c
f = overload_extend_c.Foo()
if f.test() != 0:
raise RuntimeError
if f.test(3) != 1:
raise RuntimeError
if f.test("hello") != 2:
raise RuntimeError
if f.test(3, 2) != 5:
raise RuntimeError
if f.test(3.0) != 1003:
raise RuntimeError
import overload_extend
f = overload_extend.Foo()
if f.test() != 0:
raise RuntimeError
if f.test(3) != 1:
raise RuntimeError
if f.test("hello") != 2:
raise RuntimeError
if f.test(3, 2) != 5:
raise RuntimeError
if f.test(3.0) != 1003:
raise RuntimeError
from overload_null import *
def check(a, b):
if a != b:
raise RuntimeError(str(a) + " does not equal " + str(b))
o = Overload()
x = X()
check(1, o.byval1(x))
check(2, o.byval1(None))
check(3, o.byval2(None))
check(4, o.byval2(x))
check(5, o.byref1(x))
check(6, o.byref1(None))
check(7, o.byref2(None))
check(8, o.byref2(x))
check(9, o.byconstref1(x))
check(10, o.byconstref1(None))
check(11, o.byconstref2(None))
check(12, o.byconstref2(x))
# const pointer references
check(13, o.byval1cpr(x))
check(14, o.byval1cpr(None))
check(15, o.byval2cpr(None))
check(16, o.byval2cpr(x))
# forward class declaration
check(17, o.byval1forwardptr(x))
check(18, o.byval1forwardptr(None))
check(19, o.byval2forwardptr(None))
check(20, o.byval2forwardptr(x))
check(21, o.byval1forwardref(x))
check(22, o.byval2forwardref(x))
from overload_numeric import *
import math
nums = Nums()
limits = Limits()
def check(got, expected):
if got != expected:
raise RuntimeError("got: " + got + " expected: " + expected)
check(nums.over(0), "signed char")
check(nums.over(0.0), "float")
check(nums.over(limits.schar_min()), "signed char")
check(nums.over(limits.schar_max()), "signed char")
check(nums.over(limits.schar_min() - 1), "short")
check(nums.over(limits.schar_max() + 1), "short")
check(nums.over(limits.shrt_min()), "short")
check(nums.over(limits.shrt_max()), "short")
check(nums.over(limits.shrt_min() - 1), "int")
check(nums.over(limits.shrt_max() + 1), "int")
check(nums.over(limits.int_min()), "int")
check(nums.over(limits.int_max()), "int")
check(nums.over(limits.flt_min()), "float")
check(nums.over(limits.flt_max()), "float")
check(nums.over(limits.flt_max() * 10), "double")
check(nums.over(-limits.flt_max() * 10), "double")
check(nums.over(limits.dbl_max()), "double")
check(nums.over(-limits.dbl_max()), "double")
check(nums.over(float("inf")), "float")
check(nums.over(float("-inf")), "float")
check(nums.over(float("nan")), "float")
# Just check if the following are accepted without exceptions being thrown
nums.doublebounce(float("inf"))
nums.doublebounce(float("-inf"))
nums.doublebounce(float("nan"))
import overload_rename
f = overload_rename.Foo(1)
f = overload_rename.Foo(1, 1)
f = overload_rename.Foo_int(1, 1)
f = overload_rename.Foo_int(1, 1, 1)
from overload_simple import *
if foo(3) != "foo:int":
raise RuntimeError, "foo(int)"
if foo(3.0) != "foo:double":
raise RuntimeError, "foo(double)"
if foo("hello") != "foo:char *":
raise RuntimeError, "foo(char *)"
f = Foo()
b = Bar()
if foo(f) != "foo:Foo *":
raise RuntimeError, "foo(Foo *)"
if foo(b) != "foo:Bar *":
raise RuntimeError, "foo(Bar *)"
v = malloc_void(32)
if foo(v) != "foo:void *":
raise RuntimeError, "foo(void *)"
s = Spam()
if s.foo(3) != "foo:int":
raise RuntimeError, "Spam::foo(int)"
if s.foo(3.0) != "foo:double":
raise RuntimeError, "Spam::foo(double)"
if s.foo("hello") != "foo:char *":
raise RuntimeError, "Spam::foo(char *)"
if s.foo(f) != "foo:Foo *":
raise RuntimeError, "Spam::foo(Foo *)"
if s.foo(b) != "foo:Bar *":
raise RuntimeError, "Spam::foo(Bar *)"
if s.foo(v) != "foo:void *":
raise RuntimeError, "Spam::foo(void *)"
if Spam_bar(3) != "bar:int":
raise RuntimeError, "Spam::bar(int)"
if Spam_bar(3.0) != "bar:double":
raise RuntimeError, "Spam::bar(double)"
if Spam_bar("hello") != "bar:char *":
raise RuntimeError, "Spam::bar(char *)"
if Spam_bar(f) != "bar:Foo *":
raise RuntimeError, "Spam::bar(Foo *)"
if Spam_bar(b) != "bar:Bar *":
raise RuntimeError, "Spam::bar(Bar *)"
if Spam_bar(v) != "bar:void *":
raise RuntimeError, "Spam::bar(void *)"
# Test constructors
s = Spam()
if s.type != "none":
raise RuntimeError, "Spam()"
s = Spam(3)
if s.type != "int":
raise RuntimeError, "Spam(int)"
s = Spam(3.4)
if s.type != "double":
raise RuntimeError, "Spam(double)"
s = Spam("hello")
if s.type != "char *":
raise RuntimeError, "Spam(char *)"
s = Spam(f)
if s.type != "Foo *":
raise RuntimeError, "Spam(Foo *)"
s = Spam(b)
if s.type != "Bar *":
raise RuntimeError, "Spam(Bar *)"
s = Spam(v)
if s.type != "void *":
raise RuntimeError, "Spam(void *)"
free_void(v)
a = ClassA()
b = a.method1(1)
from overload_subtype import *
f = Foo()
b = Bar()
if spam(f) != 1:
raise RuntimeError, "foo"
if spam(b) != 2:
raise RuntimeError, "bar"
from overload_template_fast import *
f = foo()
a = maximum(3, 4)
b = maximum(3.4, 5.2)
# mix 1
if (mix1("hi") != 101):
raise RuntimeError, ("mix1(const char*)")
if (mix1(1.0, 1.0) != 102):
raise RuntimeError, ("mix1(double, const double &)")
if (mix1(1.0) != 103):
raise RuntimeError, ("mix1(double)")
# mix 2
if (mix2("hi") != 101):
raise RuntimeError, ("mix2(const char*)")
if (mix2(1.0, 1.0) != 102):
raise RuntimeError, ("mix2(double, const double &)")
if (mix2(1.0) != 103):
raise RuntimeError, ("mix2(double)")
# mix 3
if (mix3("hi") != 101):
raise RuntimeError, ("mix3(const char*)")
if (mix3(1.0, 1.0) != 102):
raise RuntimeError, ("mix3(double, const double &)")
if (mix3(1.0) != 103):
raise RuntimeError, ("mix3(double)")
# Combination 1
if (overtparams1(100) != 10):
raise RuntimeError, ("overtparams1(int)")
if (overtparams1(100.0, 100) != 20):
raise RuntimeError, ("overtparams1(double, int)")
# Combination 2
if (overtparams2(100.0, 100) != 40):
raise RuntimeError, ("overtparams2(double, int)")
# Combination 3
if (overloaded() != 60):
raise RuntimeError, ("overloaded()")
if (overloaded(100.0, 100) != 70):
raise RuntimeError, ("overloaded(double, int)")
# Combination 4
if (overloadedagain("hello") != 80):
raise RuntimeError, ("overloadedagain(const char *)")
if (overloadedagain() != 90):
raise RuntimeError, ("overloadedagain(double)")
# specializations
if (specialization(10) != 202):
raise RuntimeError, ("specialization(int)")
if (specialization(10.0) != 203):
raise RuntimeError, ("specialization(double)")
if (specialization(10, 10) != 204):
raise RuntimeError, ("specialization(int, int)")
if (specialization(10.0, 10.0) != 205):
raise RuntimeError, ("specialization(double, double)")
if (specialization("hi", "hi") != 201):
raise RuntimeError, ("specialization(const char *, const char *)")
# simple specialization
xyz()
xyz_int()
xyz_double()
# a bit of everything
if (overload("hi") != 0):
raise RuntimeError, ("overload()")
if (overload(1) != 10):
raise RuntimeError, ("overload(int t)")
if (overload(1, 1) != 20):
raise RuntimeError, ("overload(int t, const int &)")
if (overload(1, "hello") != 30):
raise RuntimeError, ("overload(int t, const char *)")
k = Klass()
if (overload(k) != 10):
raise RuntimeError, ("overload(Klass t)")
if (overload(k, k) != 20):
raise RuntimeError, ("overload(Klass t, const Klass &)")
if (overload(k, "hello") != 30):
raise RuntimeError, ("overload(Klass t, const char *)")
if (overload(10.0, "hi") != 40):
raise RuntimeError, ("overload(double t, const char *)")
if (overload() != 50):
raise RuntimeError, ("overload(const char *)")
# everything put in a namespace
if (nsoverload("hi") != 1000):
raise RuntimeError, ("nsoverload()")
if (nsoverload(1) != 1010):
raise RuntimeError, ("nsoverload(int t)")
if (nsoverload(1, 1) != 1020):
raise RuntimeError, ("nsoverload(int t, const int &)")
if (nsoverload(1, "hello") != 1030):
raise RuntimeError, ("nsoverload(int t, const char *)")
if (nsoverload(k) != 1010):
raise RuntimeError, ("nsoverload(Klass t)")
if (nsoverload(k, k) != 1020):
raise RuntimeError, ("nsoverload(Klass t, const Klass &)")
if (nsoverload(k, "hello") != 1030):
raise RuntimeError, ("nsoverload(Klass t, const char *)")
if (nsoverload(10.0, "hi") != 1040):
raise RuntimeError, ("nsoverload(double t, const char *)")
if (nsoverload() != 1050):
raise RuntimeError, ("nsoverload(const char *)")
A.foo(1)
b = B()
b.foo(1)
from overload_template import *
f = foo()
a = maximum(3, 4)
b = maximum(3.4, 5.2)
# mix 1
if (mix1("hi") != 101):
raise RuntimeError, ("mix1(const char*)")
if (mix1(1.0, 1.0) != 102):
raise RuntimeError, ("mix1(double, const double &)")
if (mix1(1.0) != 103):
raise RuntimeError, ("mix1(double)")
# mix 2
if (mix2("hi") != 101):
raise RuntimeError, ("mix2(const char*)")
if (mix2(1.0, 1.0) != 102):
raise RuntimeError, ("mix2(double, const double &)")
if (mix2(1.0) != 103):
raise RuntimeError, ("mix2(double)")
# mix 3
if (mix3("hi") != 101):
raise RuntimeError, ("mix3(const char*)")
if (mix3(1.0, 1.0) != 102):
raise RuntimeError, ("mix3(double, const double &)")
if (mix3(1.0) != 103):
raise RuntimeError, ("mix3(double)")
# Combination 1
if (overtparams1(100) != 10):
raise RuntimeError, ("overtparams1(int)")
if (overtparams1(100.0, 100) != 20):
raise RuntimeError, ("overtparams1(double, int)")
# Combination 2
if (overtparams2(100.0, 100) != 40):
raise RuntimeError, ("overtparams2(double, int)")
# Combination 3
if (overloaded() != 60):
raise RuntimeError, ("overloaded()")
if (overloaded(100.0, 100) != 70):
raise RuntimeError, ("overloaded(double, int)")
# Combination 4
if (overloadedagain("hello") != 80):
raise RuntimeError, ("overloadedagain(const char *)")
if (overloadedagain() != 90):
raise RuntimeError, ("overloadedagain(double)")
# specializations
if (specialization(10) != 202):
raise RuntimeError, ("specialization(int)")
if (specialization(10.0) != 203):
raise RuntimeError, ("specialization(double)")
if (specialization(10, 10) != 204):
raise RuntimeError, ("specialization(int, int)")
if (specialization(10.0, 10.0) != 205):
raise RuntimeError, ("specialization(double, double)")
if (specialization("hi", "hi") != 201):
raise RuntimeError, ("specialization(const char *, const char *)")
# simple specialization
xyz()
xyz_int()
xyz_double()
# a bit of everything
if (overload("hi") != 0):
raise RuntimeError, ("overload()")
if (overload(1) != 10):
raise RuntimeError, ("overload(int t)")
if (overload(1, 1) != 20):
raise RuntimeError, ("overload(int t, const int &)")
if (overload(1, "hello") != 30):
raise RuntimeError, ("overload(int t, const char *)")
k = Klass()
if (overload(k) != 10):
raise RuntimeError, ("overload(Klass t)")
if (overload(k, k) != 20):
raise RuntimeError, ("overload(Klass t, const Klass &)")
if (overload(k, "hello") != 30):
raise RuntimeError, ("overload(Klass t, const char *)")
if (overload(10.0, "hi") != 40):
raise RuntimeError, ("overload(double t, const char *)")
if (overload() != 50):
raise RuntimeError, ("overload(const char *)")
# everything put in a namespace
if (nsoverload("hi") != 1000):
raise RuntimeError, ("nsoverload()")
if (nsoverload(1) != 1010):
raise RuntimeError, ("nsoverload(int t)")
if (nsoverload(1, 1) != 1020):
raise RuntimeError, ("nsoverload(int t, const int &)")
if (nsoverload(1, "hello") != 1030):
raise RuntimeError, ("nsoverload(int t, const char *)")
if (nsoverload(k) != 1010):
raise RuntimeError, ("nsoverload(Klass t)")
if (nsoverload(k, k) != 1020):
raise RuntimeError, ("nsoverload(Klass t, const Klass &)")
if (nsoverload(k, "hello") != 1030):
raise RuntimeError, ("nsoverload(Klass t, const char *)")
if (nsoverload(10.0, "hi") != 1040):
raise RuntimeError, ("nsoverload(double t, const char *)")
if (nsoverload() != 1050):
raise RuntimeError, ("nsoverload(const char *)")
A_foo(1)
b = B()
b.foo(1)
import pointer_reference
s = pointer_reference.get()
if s.value != 10:
raise RuntimeError, "get test failed"
ss = pointer_reference.Struct(20)
pointer_reference.set(ss)
if pointer_reference.cvar.Struct_instance.value != 20:
raise RuntimeError, "set test failed"
if pointer_reference.overloading(1) != 111:
raise RuntimeError, "overload test 1 failed"
if pointer_reference.overloading(ss) != 222:
raise RuntimeError, "overload test 2 failed"
import preproc_defined
if preproc_defined.call_checking() != 1:
raise RuntimeError
d = preproc_defined.Defined()
d.defined = 10
preproc_defined.thing(10)
preproc_defined.stuff(10)
preproc_defined.bumpf(10)
import preproc_gcc_output
preproc_gcc_output.header1_function_a(99)
preproc_gcc_output.header1_function_b(99)
preproc_gcc_output.header2_function(99)
import preproc_include
if preproc_include.multiply10(10) != 100:
raise RuntimeError
if preproc_include.multiply20(10) != 200:
raise RuntimeError
if preproc_include.multiply30(10) != 300:
raise RuntimeError
if preproc_include.multiply40(10) != 400:
raise RuntimeError
if preproc_include.multiply50(10) != 500:
raise RuntimeError
if preproc_include.multiply60(10) != 600:
raise RuntimeError
if preproc_include.multiply70(10) != 700:
raise RuntimeError
import preproc
if preproc.endif != 1:
raise RuntimeError
if preproc.define != 1:
raise RuntimeError
if preproc.defined != 1:
raise RuntimeError
if 2 * preproc.one != preproc.two:
raise RuntimeError
if preproc.methodX(99) != 199:
raise RuntimeError
t1 = preproc.tcxMessageTest()
t2 = preproc.tcxMessageBug()
from primitive_ref import *
if ref_int(3) != 3:
raise RuntimeError
if ref_uint(3) != 3:
raise RuntimeError
if ref_short(3) != 3:
raise RuntimeError
if ref_ushort(3) != 3:
raise RuntimeError
if ref_long(3) != 3:
raise RuntimeError
if ref_ulong(3) != 3:
raise RuntimeError
if ref_schar(3) != 3:
raise RuntimeError
if ref_uchar(3) != 3:
raise RuntimeError
if ref_float(3.5) != 3.5:
raise RuntimeError
if ref_double(3.5) != 3.5:
raise RuntimeError
if ref_bool(True) != True:
raise RuntimeError
if ref_char("x") != "x":
raise RuntimeError
if ref_over(0) != 0:
raise RuntimeError
import sys
from primitive_types import *
var_init()
# assigning globals calls
cvar.var_bool = sct_bool
cvar.var_schar = sct_schar
cvar.var_uchar = sct_uchar
cvar.var_int = sct_int
cvar.var_uint = sct_uint
cvar.var_short = sct_short
cvar.var_ushort = sct_ushort
cvar.var_long = sct_long
cvar.var_ulong = sct_ulong
cvar.var_llong = sct_llong
cvar.var_ullong = sct_ullong
cvar.var_char = sct_char
cvar.var_pchar = sct_pchar
cvar.var_pcharc = sct_pcharc
cvar.var_pint = sct_pint
cvar.var_sizet = sct_sizet
cvar.var_hello = sct_hello
cvar.var_myint = sct_myint
cvar.var_namet = def_namet
cvar.var_parami = sct_parami
cvar.var_paramd = sct_paramd
cvar.var_paramc = sct_paramc
v_check()
def pyerror(name, val, cte):
print "bad val/cte", name, val, cte
raise RuntimeError
pass
if cvar.var_bool != cct_bool:
pyerror("bool", cvar.var_bool, cct_bool)
if cvar.var_schar != cct_schar:
pyerror("schar", cvar.var_schar, cct_schar)
if cvar.var_uchar != cct_uchar:
pyerror("uchar", cvar.var_uchar, cct_uchar)
if cvar.var_int != cct_int:
pyerror("int", cvar.var_int, cct_int)
if cvar.var_uint != cct_uint:
pyerror("uint", cvar.var_uint, cct_uint)
if cvar.var_short != cct_short:
pyerror("short", cvar.var_short, cct_short)
if cvar.var_ushort != cct_ushort:
pyerror("ushort", cvar.var_ushort, cct_ushort)
if cvar.var_long != cct_long:
pyerror("long", cvar.var_long, cct_long)
if cvar.var_ulong != cct_ulong:
pyerror("ulong", cvar.var_ulong, cct_ulong)
if cvar.var_llong != cct_llong:
pyerror("llong", cvar.var_llong, cct_llong)
if cvar.var_ullong != cct_ullong:
pyerror("ullong", cvar.var_ullong, cct_ullong)
if cvar.var_char != cct_char:
pyerror("char", cvar.var_char, cct_char)
if cvar.var_pchar != cct_pchar:
pyerror("pchar", cvar.var_pchar, cct_pchar)
if cvar.var_pcharc != cct_pcharc:
pyerror("pchar", cvar.var_pcharc, cct_pcharc)
if cvar.var_pint != cct_pint:
pyerror("pint", cvar.var_pint, cct_pint)
if cvar.var_sizet != cct_sizet:
pyerror("sizet", cvar.var_sizet, cct_sizet)
if cvar.var_hello != cct_hello:
pyerror("hello", cvar.var_hello, cct_hello)
if cvar.var_myint != cct_myint:
pyerror("myint", cvar.var_myint, cct_myint)
if cvar.var_namet != def_namet:
pyerror("name", cvar.var_namet, def_namet)
class PyTest (TestDirector):
def __init__(self):
TestDirector.__init__(self)
pass
def ident(self, x):
return x
def vval_bool(self, x): return self.ident(x)
def vval_schar(self, x): return self.ident(x)
def vval_uchar(self, x): return self.ident(x)
def vval_int(self, x): return self.ident(x)
def vval_uint(self, x): return self.ident(x)
def vval_short(self, x): return self.ident(x)
def vval_ushort(self, x): return self.ident(x)
def vval_long(self, x): return self.ident(x)
def vval_ulong(self, x): return self.ident(x)
def vval_llong(self, x): return self.ident(x)
def vval_ullong(self, x): return self.ident(x)
def vval_float(self, x): return self.ident(x)
def vval_double(self, x): return self.ident(x)
def vval_char(self, x): return self.ident(x)
def vval_pchar(self, x): return self.ident(x)
def vval_pcharc(self, x): return self.ident(x)
def vval_pint(self, x): return self.ident(x)
def vval_sizet(self, x): return self.ident(x)
def vval_hello(self, x): return self.ident(x)
def vval_myint(self, x): return self.ident(x)
def vref_bool(self, x): return self.ident(x)
def vref_schar(self, x): return self.ident(x)
def vref_uchar(self, x): return self.ident(x)
def vref_int(self, x): return self.ident(x)
def vref_uint(self, x): return self.ident(x)
def vref_short(self, x): return self.ident(x)
def vref_ushort(self, x): return self.ident(x)
def vref_long(self, x): return self.ident(x)
def vref_ulong(self, x): return self.ident(x)
def vref_llong(self, x): return self.ident(x)
def vref_ullong(self, x): return self.ident(x)
def vref_float(self, x): return self.ident(x)
def vref_double(self, x): return self.ident(x)
def vref_char(self, x): return self.ident(x)
def vref_pchar(self, x): return self.ident(x)
def vref_pcharc(self, x): return self.ident(x)
def vref_pint(self, x): return self.ident(x)
def vref_sizet(self, x): return self.ident(x)
def vref_hello(self, x): return self.ident(x)
def vref_myint(self, x): return self.ident(x)
pass
t = Test()
p = PyTest()
# internal call check
if t.c_check() != p.c_check():
raise RuntimeError, "bad director"
p.var_bool = p.stc_bool
p.var_schar = p.stc_schar
p.var_uchar = p.stc_uchar
p.var_int = p.stc_int
p.var_uint = p.stc_uint
p.var_short = p.stc_short
p.var_ushort = p.stc_ushort
p.var_long = p.stc_long
p.var_ulong = p.stc_ulong
p.var_llong = p.stc_llong
p.var_ullong = p.stc_ullong
p.var_char = p.stc_char
p.var_pchar = sct_pchar
p.var_pcharc = sct_pcharc
p.var_pint = sct_pint
p.var_sizet = sct_sizet
p.var_hello = sct_hello
p.var_myint = sct_myint
p.var_namet = def_namet
p.var_parami = sct_parami
p.var_paramd = sct_paramd
p.var_paramc = sct_paramc
p.v_check()
t.var_bool = t.stc_bool
t.var_schar = t.stc_schar
t.var_uchar = t.stc_uchar
t.var_int = t.stc_int
t.var_uint = t.stc_uint
t.var_short = t.stc_short
t.var_ushort = t.stc_ushort
t.var_long = t.stc_long
t.var_ulong = t.stc_ulong
t.var_llong = t.stc_llong
t.var_ullong = t.stc_ullong
t.var_char = t.stc_char
t.var_pchar = sct_pchar
t.var_pcharc = sct_pcharc
t.var_pint = sct_pint
t.var_sizet = sct_sizet
t.var_hello = sct_hello
t.var_myint = sct_myint
t.var_namet = def_namet
t.var_parami = sct_parami
t.var_paramd = sct_paramd
t.var_paramc = sct_paramc
t.v_check()
# this value contains a '0' char!
if def_namet != "hola":
print "bad namet", def_namet
raise RuntimeError
t.var_namet = def_namet
if t.var_namet != def_namet:
print "bad namet", t.var_namet, def_namet
raise RuntimeError
t.var_namet = "hola"
if t.var_namet != "hola":
print "bad namet", t.var_namet
raise RuntimeError
t.var_namet = "hol"
if t.var_namet != "hol":
# if t.var_namet != "hol\0\0":
print "bad namet", t.var_namet
raise RuntimeError
cvar.var_char = "\0"
if cvar.var_char != "\0":
raise RuntimeError, "bad char '0' case"
cvar.var_char = 0
if cvar.var_char != "\0":
raise RuntimeError, "bad char '0' case"
cvar.var_namet = "\0"
# if cvar.var_namet != "\0\0\0\0\0":
if cvar.var_namet != "":
print "hola", "", cvar.var_namet
raise RuntimeError, "bad char '\0' case"
cvar.var_namet = ""
# if cvar.var_namet != "\0\0\0\0\0":
if cvar.var_namet != "":
raise RuntimeError, "bad char empty case"
cvar.var_pchar = None
if cvar.var_pchar != None:
raise RuntimeError, "bad None case"
cvar.var_pchar = ""
if cvar.var_pchar != "":
print "%c" % (cvar.var_pchar[0],)
raise RuntimeError, "bad char empty case"
cvar.var_pcharc = None
if cvar.var_pcharc != None:
raise RuntimeError, "bad None case"
cvar.var_pcharc = ""
if cvar.var_pcharc != "":
raise RuntimeError, "bad char empty case"
#
# creating a raw char*
#
pc = new_pchar(5)
pchar_setitem(pc, 0, "h")
pchar_setitem(pc, 1, "o")
pchar_setitem(pc, 2, "l")
pchar_setitem(pc, 3, "a")
pchar_setitem(pc, 4, 0)
cvar.var_pchar = pc
if cvar.var_pchar != "hola":
print cvar.var_pchar
raise RuntimeError, "bad pointer case"
cvar.var_namet = pc
# if cvar.var_namet != "hola\0":
if cvar.var_namet != "hola":
raise RuntimeError, "bad pointer case"
delete_pchar(pc)
#
# Now when things should fail
#
try:
error = 0
a = t.var_uchar
t.var_uchar = 10000
error = 1
except OverflowError:
if a != t.var_uchar:
error = 1
pass
if error:
raise RuntimeError, "bad uchar typemap"
try:
error = 0
a = t.var_char
t.var_char = "23"
error = 1
except TypeError:
if a != t.var_char:
error = 1
pass
if error:
raise RuntimeError, "bad char typemap"
try:
error = 0
a = t.var_ushort
t.var_ushort = -1
error = 1
except OverflowError:
if a != t.var_ushort:
error = 1
pass
if error:
raise RuntimeError, "bad ushort typemap"
try:
error = 0
a = t.var_uint
t.var_uint = -1
error = 1
except OverflowError:
if a != t.var_uint:
error = 1
pass
if error:
raise RuntimeError, "bad uint typemap"
try:
error = 0
a = t.var_sizet
t.var_sizet = -1
error = 1
except OverflowError:
if a != t.var_sizet:
error = 1
pass
if error:
raise RuntimeError, "bad sizet typemap"
try:
error = 0
a = t.var_ulong
t.var_ulong = -1
error = 1
except OverflowError:
if a != t.var_ulong:
error = 1
pass
if error:
raise RuntimeError, "bad ulong typemap"
#
#
try:
error = 0
a = t.var_namet
t.var_namet = "123456"
error = 1
except TypeError:
if a != t.var_namet:
error = 1
pass
if error:
raise RuntimeError, "bad namet typemap"
#
#
#
t2 = p.vtest(t)
if t.var_namet != t2.var_namet:
raise RuntimeError, "bad SWIGTYPE* typemap"
if cvar.fixsize != "ho\0la\0\0\0":
raise RuntimeError, "bad FIXSIZE typemap"
cvar.fixsize = "ho"
if cvar.fixsize != "ho\0\0\0\0\0\0":
raise RuntimeError, "bad FIXSIZE typemap"
f = Foo(3)
f1 = fptr_val(f)
f2 = fptr_ref(f)
if f1._a != f2._a:
raise RuntimeError, "bad const ptr& typemap"
v = char_foo(1, 3)
if v != 3:
raise RuntimeError, "bad int typemap"
s = char_foo(1, "hello")
if s != "hello":
raise RuntimeError, "bad char* typemap"
v = SetPos(1, 3)
if v != 4:
raise RuntimeError, "bad int typemap"
#
# Check the bounds for converting various types
#
# ctypes not available until 2.5
if sys.version_info[0:2] <= (2, 4):
sys.exit(0)
import ctypes
# Get the minimum and maximum values that fit in signed char, short, int, long, and long long
overchar = 2 ** 7
while ctypes.c_byte(overchar).value > 0:
overchar *= 2
minchar = -overchar
maxchar = overchar - 1
maxuchar = 2 * maxchar + 1
overshort = overchar
while ctypes.c_short(overshort).value > 0:
overshort *= 2
minshort = -overshort
maxshort = overshort - 1
maxushort = 2 * maxshort + 1
overint = overshort
while ctypes.c_int(overint).value > 0:
overint *= 2
minint = -overint
maxint = overint - 1
maxuint = 2 * maxint + 1
overlong = overint
while ctypes.c_long(overlong).value > 0:
overlong *= 2
minlong = -overlong
maxlong = overlong - 1
maxulong = 2 * maxlong + 1
overllong = overlong
while ctypes.c_longlong(overllong).value > 0:
overllong *= 2
minllong = -overllong
maxllong = overllong - 1
maxullong = 2 * maxllong + 1
# Make sure Python 2's sys.maxint is the same as the maxlong we calculated
if sys.version_info[0] <= 2 and maxlong != sys.maxint:
raise RuntimeError, "sys.maxint is not the maximum value of a signed long"
def checkType(t, e, val, delta):
"""t = Test object, e = type name (e.g. ulong), val = max or min allowed value, delta = +1 for max, -1 for min"""
error = 0
# Set the extreme valid value for var_*
setattr(t, "var_" + e, val)
# Make sure it was set properly and works properly in the val_* and ref_* methods
if getattr(t, "var_" + e) != val or getattr(t, "val_" + e)(val) != val or getattr(t, "ref_" + e)(val) != val:
error = 1
# Make sure setting a more extreme value fails without changing the value
try:
a = getattr(t, "var_" + e)
setattr(t, "var_" + e, val + delta)
error = 1
except OverflowError:
if a != getattr(t, "var_" + e):
error = 1
# Make sure the val_* and ref_* methods fail with a more extreme value
try:
getattr(t, "val_" + e)(val + delta)
error = 1
except OverflowError:
pass
try:
getattr(t, "ref_" + e)(val + delta)
error = 1
except OverflowError:
pass
if error:
raise RuntimeError, "bad " + e + " typemap"
def checkFull(t, e, maxval, minval):
"""Check the maximum and minimum bounds for the type given by e"""
checkType(t, e, maxval, 1)
checkType(t, e, minval, -1)
checkFull(t, "llong", maxllong, minllong)
checkFull(t, "long", maxlong, minlong)
checkFull(t, "int", maxint, minint)
checkFull(t, "short", maxshort, minshort)
checkFull(t, "schar", maxchar, minchar)
checkFull(t, "ullong", maxullong, 0)
checkFull(t, "ulong", maxulong, 0)
checkFull(t, "uint", maxuint, 0)
checkFull(t, "ushort", maxushort, 0)
checkFull(t, "uchar", maxuchar, 0)
def checkOverload(t, name, val, delta, prevval, limit):
"""
Check that overloading works
t = Test object
name = type name (e.g. ulong)
val = max or min allowed value
delta = +1 for max, -1 for min
prevval = corresponding value for one smaller type
limit = most extreme value for any type
"""
# If val == prevval, then the smaller typemap will win
if val != prevval:
# Make sure the most extreme value of this type gives the name of this type
if t.ovr_str(val) != name:
raise RuntimeError, "bad " + name + " typemap"
# Make sure a more extreme value doesn't give the name of this type
try:
if t.ovr_str(val + delta) == name:
raise RuntimeError, "bad " + name + " typemap"
if val == limit:
# Should raise TypeError here since this is the largest integral type
raise RuntimeError, "bad " + name + " typemap"
except TypeError:
if val != limit:
raise RuntimeError, "bad " + name + " typemap"
# Check that overloading works: uchar > schar > ushort > short > uint > int > ulong > long > ullong > llong
checkOverload(t, "uchar", maxuchar, +1, 0, maxullong)
checkOverload(t, "ushort", maxushort, +1, maxuchar, maxullong)
checkOverload(t, "uint", maxuint, +1, maxushort, maxullong)
checkOverload(t, "ulong", maxulong, +1, maxuint, maxullong)
checkOverload(t, "ullong", maxullong, +1, maxulong, maxullong)
checkOverload(t, "schar", minchar, -1, 0, minllong)
checkOverload(t, "short", minshort, -1, minchar, minllong)
checkOverload(t, "int", minint, -1, minshort, minllong)
checkOverload(t, "long", minlong, -1, minint, minllong)
checkOverload(t, "llong", minllong, -1, minlong, minllong)
# Make sure that large ints can be converted to doubles properly
if val_double(sys.maxint + 1) != float(sys.maxint + 1):
raise RuntimeError, "bad double typemap"
if val_double(-sys.maxint - 2) != float(-sys.maxint - 2):
raise RuntimeError, "bad double typemap"
# Check the minimum and maximum values that fit in ptrdiff_t and size_t
def checkType(name, maxfunc, maxval, minfunc, minval, echofunc):
if maxfunc() != maxval:
raise RuntimeError, "bad " + name + " typemap"
if minfunc() != minval:
raise RuntimeError, "bad " + name + " typemap"
if echofunc(maxval) != maxval:
raise RuntimeError, "bad " + name + " typemap"
if echofunc(minval) != minval:
raise RuntimeError, "bad " + name + " typemap"
error = 0
try:
echofunc(maxval + 1)
error = 1
except OverflowError:
pass
if error == 1:
raise RuntimeError, "bad " + name + " typemap"
try:
echofunc(minval - 1)
error = 1
except OverflowError:
pass
if error == 1:
raise RuntimeError, "bad " + name + " typemap"
# sys.maxsize is the largest value supported by Py_ssize_t, which should be the same as ptrdiff_t
if sys.version_info[0:2] >= (2, 6):
checkType("ptrdiff_t", get_ptrdiff_max, sys.maxsize, get_ptrdiff_min, -(sys.maxsize + 1), ptrdiff_echo)
checkType("size_t", get_size_max, (2 * sys.maxsize) + 1, get_size_min, 0, size_echo)
import _profiletest
#import profiletest
pa = _profiletest.new_A()
pb = _profiletest.new_B()
fn = _profiletest.B_fn
destroy = _profiletest.delete_A
i = 50000
a = pa
while i:
a = fn(pb, a) # 1
destroy(a)
a = fn(pb, a) # 2
destroy(a)
a = fn(pb, a) # 3
destroy(a)
a = fn(pb, a) # 4
destroy(a)
a = fn(pb, a) # 5
destroy(a)
a = fn(pb, a) # 6
destroy(a)
a = fn(pb, a) # 7
destroy(a)
a = fn(pb, a) # 8
destroy(a)
a = fn(pb, a) # 9
destroy(a)
a = fn(pb, a) # 10
destroy(a)
a = fn(pb, a) # 1
destroy(a)
a = fn(pb, a) # 2
destroy(a)
a = fn(pb, a) # 3
destroy(a)
a = fn(pb, a) # 4
destroy(a)
a = fn(pb, a) # 5
destroy(a)
a = fn(pb, a) # 6
destroy(a)
a = fn(pb, a) # 7
destroy(a)
a = fn(pb, a) # 8
destroy(a)
a = fn(pb, a) # 9
destroy(a)
a = fn(pb, a) # 20
destroy(a)
i -= 1
_profiletest.delete_A(pa)
_profiletest.delete_B(pb)
import _profiletest
import profiletest
a = profiletest.A()
print a
print a.this
b = profiletest.B()
fn = b.fn
i = 50000
while i:
a = fn(a) # 1
a = fn(a) # 2
a = fn(a) # 3
a = fn(a) # 4
a = fn(a) # 5
a = fn(a) # 6
a = fn(a) # 7
a = fn(a) # 8
a = fn(a) # 9
a = fn(a) # 10
a = fn(a) # 1
a = fn(a) # 2
a = fn(a) # 3
a = fn(a) # 4
a = fn(a) # 5
a = fn(a) # 6
a = fn(a) # 7
a = fn(a) # 8
a = fn(a) # 9
a = fn(a) # 20
i -= 1
import sys
# collections.abc requires Python 3.3+
if sys.version_info[0:2] < (3, 3):
exit(0)
from python_abstractbase import *
import collections.abc
# This is expected to fail with -builtin option
# Builtin types can't inherit from pure-python abstract bases
if is_python_builtin():
exit(0)
# Python abc is only turned on when -py3 option is passed to SWIG
if not is_swig_py3:
exit(0)
def check_issubclass(derived, base):
if not issubclass(derived, base):
raise RuntimeError("{} is not a subclass of {}".format(derived, base))
check_issubclass(Mapii, collections.abc.MutableMapping)
check_issubclass(Multimapii, collections.abc.MutableMapping)
check_issubclass(IntSet, collections.abc.MutableSet)
check_issubclass(IntMultiset, collections.abc.MutableSet)
check_issubclass(IntVector, collections.abc.MutableSequence)
check_issubclass(IntList, collections.abc.MutableSequence)
mapii = Mapii()
multimapii = Multimapii()
intset = IntSet()
intmultiset = IntMultiset()
intvector = IntVector()
intlist = IntList()
from python_append import *
# test not relevant for -builtin
if is_python_builtin():
exit(0)
t = Test()
t.funk()
t.static_func()
if grabpath() != os.path.dirname(mypath):
raise RuntimeError("grabpath failed")
if grabstaticpath() != os.path.basename(mypath):
raise RuntimeError("grabstaticpath failed")
clearstaticpath()
if grabstaticpath() != None:
raise RuntimeError("Resetting staticfuncpath failed")
Test.static_func()
if grabstaticpath() != os.path.basename(mypath):
raise RuntimeError("grabstaticpath failed")
# slots test
fs = ForSlots()
if fs.ValidVariable != 99:
raise RuntimeError("ValidVariable failed")
fs.ValidVariable = 11
if fs.ValidVariable != 11:
raise RuntimeError("ValidVariable failed")
try:
fs.Invalid = 22
raise RuntimeError("It should not be possible to set a random variable name")
except AttributeError:
pass
from python_builtin import *
if is_python_builtin():
# Test 0 for default tp_hash
vs = ValueStruct(1234)
h = hash(vs)
d = dict()
d[h] = "hi"
if h not in d:
raise RuntimeError("h should be in d")
h2 = hash(ValueStruct.inout(vs))
if h != h2:
raise RuntimeError("default tp_hash not working")
# Test 1a for tp_hash
if hash(SimpleValue(222)) != 222:
raise RuntimeError("tp_hash not working")
# Test 1b for tp_hash
if hash(SimpleValue2(333)) != 333:
raise RuntimeError("tp_hash not working")
# Test 2 for tp_hash
try:
# Was incorrectly raising: SystemError: error return without exception set
h = hash(BadHashFunctionReturnType())
raise RuntimeError("Missing TypeError")
except TypeError:
pass
# Test 3 for tp_hash
passed = False
try:
h = hash(ExceptionHashFunction())
except RuntimeError, e:
passed = str(e).find("oops") != -1
pass
if not passed:
raise RuntimeError("did not catch exception in hash()")
# Test 4 for tp_dealloc (which is handled differently to other slots in the SWIG source)
d = Dealloc1()
if cvar.Dealloc1CalledCount != 0:
raise RuntimeError("count should be 0")
del d
if cvar.Dealloc1CalledCount != 1:
raise RuntimeError("count should be 1")
d = Dealloc2()
if cvar.Dealloc2CalledCount != 0:
raise RuntimeError("count should be 0")
del d
if cvar.Dealloc2CalledCount != 1:
raise RuntimeError("count should be 1")
d = Dealloc3()
if cvar.Dealloc3CalledCount != 0:
raise RuntimeError("count should be 0")
del d
if cvar.Dealloc3CalledCount != 1:
raise RuntimeError("count should be 1")
# Test 5 for python:compare feature
m10 = MyClass(10)
m20 = MyClass(20)
m15 = MyClass(15)
if not m10 < m15:
raise RuntimeError("m10 < m15")
if not m10 < m20:
raise RuntimeError("m10 < m20")
if not m15 < m20:
raise RuntimeError("m15 < m20")
if m10 > m15:
raise RuntimeError("m10 > m15")
if m10 > m20:
raise RuntimeError("m10 > m20")
if m15 > m20:
raise RuntimeError("m15 > m20")
if MyClass.less_than_counts != 6:
raise RuntimeError("python:compare feature not working")
# Test 6
sa = SimpleArray(5)
elements = [x for x in sa]
if elements != [0, 10, 20, 30, 40]:
raise RuntimeError("Iteration not working")
if len(sa) != 5:
raise RuntimeError("len not working")
for i in range(5):
if sa[i] != i*10:
raise RuntimeError("indexing not working")
subslice = sa[1:3]
elements = [x for x in subslice]
if elements != [10, 20]:
raise RuntimeError("slice not working")
# Test 7 mapping to Python's pow
x = ANumber(2)
y = ANumber(4)
z = x ** y
if z.Value() != 16:
raise RuntimeError("x ** y wrong")
z = pow(x, y)
if z.Value() != 16:
raise RuntimeError("pow(x, y) wrong")
z = ANumber(9)
z = pow(x, y, z)
if z.Value() != 7:
raise RuntimeError("pow(x, y, z) wrong")
import python_destructor_exception
from StringIO import StringIO
import sys
def error_function():
python_destructor_exception.ClassWithThrowingDestructor().GetBlah()
def runtest():
attributeErrorOccurred = False
try:
error_function()
except AttributeError, e:
attributeErrorOccurred = True
return attributeErrorOccurred
def test1():
stderr_saved = sys.stderr
buffer = StringIO()
attributeErrorOccurred = False
try:
# Suppress stderr while making this call to suppress the output shown by PyErr_WriteUnraisable
sys.stderr = buffer
attributeErrorOccurred = runtest()
finally:
sys.stderr.flush()
sys.stderr = stderr_saved
if not attributeErrorOccurred:
raise RuntimeError("attributeErrorOccurred failed")
if not buffer.getvalue().count("I am the ClassWithThrowingDestructor dtor doing bad things") >= 1:
raise RuntimeError("ClassWithThrowingDestructor dtor doing bad things failed")
class VectorHolder(object):
def __init__(self, v):
self.v = v
def gen(self):
for e in self.v:
yield e
# See issue #559, #560, #573 - In Python 3.5, test2() call to the generator 'gen' was
# resulting in the following (not for -builtin where there is no call to SWIG_Python_CallFunctor
# as SwigPyObject_dealloc is not used):
#
# StopIteration
#
# During handling of the above exception, another exception occurred:
# ...
# SystemError: <built-in function delete_VectorInt> returned a result with an error set
def addup():
sum = 0
for i in VectorHolder(python_destructor_exception.VectorInt([1, 2, 3])).gen():
sum = sum + i
return sum
def test2():
sum = addup()
if sum != 6:
raise RuntimeError("Sum is incorrect")
# These two tests are different are two different ways to recreate essentially the same problem
# reported by Python 3.5 that an exception was already set when destroying a wrapped object
test1()
test2()
from python_docstring import *
import inspect
def check(got, expected):
expected_list = expected.split("\n")
got_list = got.split("\n")
if expected_list != got_list:
raise RuntimeError("\n" + "Expected: " + str(expected_list) + "\n" + "Got : " + str(got_list))
# When getting docstrings, use inspect.getdoc(x) instead of x.__doc__ otherwise the different options
# such as -O and -builtin may produce different initial indentation.
check(inspect.getdoc(DocStrings.docstring1),
" line 1\n"
"line 2\n"
"\n"
"\n"
"\n"
"line 3"
)
check(inspect.getdoc(DocStrings.docstring2),
"line 1\n"
" line 2\n"
"\n"
"\n"
"\n"
" line 3"
)
check(inspect.getdoc(DocStrings.docstring3),
"line 1\n"
" line 2\n"
"\n"
"\n"
"\n"
" line 3"
)
check(inspect.getdoc(DocStrings.docstring4),
"line 1\n"
" line 2\n"
"\n"
"\n"
"\n"
" line 3"
)
check(inspect.getdoc(DocStrings.docstring5),
"line 1\n"
" line 2\n"
"\n"
"\n"
"\n"
" line 3"
)
check(inspect.getdoc(DocStrings.docstring6),
"line 1\n"
" line 2\n"
"\n"
"\n"
"\n"
" line 3"
)
check(inspect.getdoc(DocStrings.docstring7),
"line 1\n"
"line 2\n"
"line 3"
)
check(inspect.getdoc(DocStrings.docstringA),
"first line\n"
"second line"
)
check(inspect.getdoc(DocStrings.docstringB),
"first line\n"
"second line"
)
check(inspect.getdoc(DocStrings.docstringC),
"first line\n"
"second line"
)
# One line doc special case, use __doc__
check(DocStrings.docstringX.__doc__,
" one line docs"
)
check(inspect.getdoc(DocStrings.docstringX),
"one line docs"
)
check(inspect.getdoc(DocStrings.docstringY),
"one line docs"
)
import python_extranative
vs = python_extranative.make_vector_string()
if not isinstance(vs, python_extranative.VectorString):
# will be of type tuple if extranative not working
raise RuntimeError("Not of type VectorString")
for s1, s2 in zip(vs, ["one", "two"]):
if s1 != s2:
raise RuntimeError("Mismatch: " + s1 + " " + s2)
import python_moduleimport
if python_moduleimport.simple_function(99) != 99:
raise RuntimeError("simple_function")
if python_moduleimport.extra_import_variable != "custom import of _python_moduleimport":
raise RuntimeError("custom import")
import python_nondynamic
def is_python_modern():
"""Return True if SWIG is generating Python code using -modern. Works only if %python_nondynamic has been used."""
return hasattr(python_nondynamic, "_swig_setattr_nondynamic_class_variable")
def debug_print(s):
show_debug = False
if show_debug:
print(s)
aa = python_nondynamic.A()
aa.a = 1
aa.b = 2
# Check values are really set
if python_nondynamic.retrieve_A_a(aa) != 1: raise RuntimeError("a not set correctly")
if python_nondynamic.retrieve_A_b(aa) != 2: raise RuntimeError("b not set correctly")
try:
aa.c = 2
raise RuntimeError("A is not static")
except AttributeError as e:
debug_print(e)
pass
class PurePythonClass(object):
def __init__(self):
self.variables = dict()
def __set__(self, name, value):
self.variables[name] = value
pass
class B(python_nondynamic.A):
c = 4
cc = PurePythonClass()
cc.nnn = "new attrib"
def __init__(self):
python_nondynamic.A.__init__(self)
pass
pass
bb = B()
bb.a = 4
bb.b = 5
# Check values are really set
if python_nondynamic.retrieve_A_a(bb) != 4: raise RuntimeError("a not set correctly")
if python_nondynamic.retrieve_A_b(bb) != 5: raise RuntimeError("b not set correctly")
try:
bb.c = 3
print("bb.c = {}".format(bb.c))
print("B.c = {}".format(B.c))
raise RuntimeError("B.c class variable messes up nondynamic-ness of B")
except AttributeError as e:
debug_print(e)
pass
try:
bb.d = 2
raise RuntimeError("B is not static")
except AttributeError as e:
debug_print(e)
pass
cc = python_nondynamic.C()
cc.d = 3
# An inconsistency between builtin and (non-builtin/modern).
# Class variables cannot be set on builtin types, like other Python builtins, eg list.classvar=111 fails
if python_nondynamic.is_python_builtin():
try:
python_nondynamic.C.classvar = 111
raise RuntimeError("C should not allow static variables to be added when using builtin")
except AttributeError as e:
debug_print(e)
pass
else:
python_nondynamic.C.classvar = 111
if is_python_modern() and not python_nondynamic.is_python_builtin():
# Not working with builtin or non-modern :(
try:
B.a = 10
raise RuntimeError("B should not allow adding a class variable by setting it as an instance variable")
except AttributeError as e:
debug_print(e)
pass
try:
python_nondynamic.A.a = 10
raise RuntimeError("A should not allow adding a class variable by setting it as an instance variable")
except AttributeError as e:
debug_print(e)
pass
if not python_nondynamic.is_python_builtin():
try:
bb.cc = 3
print("bb.cc = {}".format(bb.cc))
print("B.cc = {}".format(B.cc))
raise RuntimeError("B.cc class variable messes up nondynamic-ness of B")
except AttributeError as e:
debug_print(e)
pass
from python_overload_simple_cast import *
class Ai:
def __init__(self, x):
self.x = x
def __int__(self):
return self.x
class Ad:
def __init__(self, x):
self.x = x
def __float__(self):
return self.x
ai = Ai(4)
ad = Ad(5.0)
add = Ad(5.5)
try:
fint(add)
good = 0
except:
good = 1
if not good:
raise RuntimeError, "fint(int)"
if fint(ad) != "fint:int":
raise RuntimeError, "fint(int)"
if fdouble(ad) != "fdouble:double":
raise RuntimeError, "fdouble(double)"
if fint(ai) != "fint:int":
raise RuntimeError, "fint(int)"
if fint(5.0) != "fint:int":
raise RuntimeError, "fint(int)"
if fint(3) != "fint:int":
raise RuntimeError, "fint(int)"
if fint(3.0) != "fint:int":
raise RuntimeError, "fint(int)"
if fdouble(ad) != "fdouble:double":
raise RuntimeError, "fdouble(double)"
if fdouble(3) != "fdouble:double":
raise RuntimeError, "fdouble(double)"
if fdouble(3.0) != "fdouble:double":
raise RuntimeError, "fdouble(double)"
if fid(3, 3.0) != "fid:intdouble":
raise RuntimeError, "fid:intdouble"
if fid(3.0, 3) != "fid:doubleint":
raise RuntimeError, "fid:doubleint"
if fid(ad, ai) != "fid:doubleint":
raise RuntimeError, "fid:doubleint"
if fid(ai, ad) != "fid:intdouble":
raise RuntimeError, "fid:intdouble"
if foo(3) != "foo:int":
raise RuntimeError, "foo(int)"
if foo(3.0) != "foo:double":
raise RuntimeError, "foo(double)"
if foo("hello") != "foo:char *":
raise RuntimeError, "foo(char *)"
f = Foo()
b = Bar()
if foo(f) != "foo:Foo *":
raise RuntimeError, "foo(Foo *)"
if foo(b) != "foo:Bar *":
raise RuntimeError, "foo(Bar *)"
v = malloc_void(32)
if foo(v) != "foo:void *":
raise RuntimeError, "foo(void *)"
s = Spam()
if s.foo(3) != "foo:int":
raise RuntimeError, "Spam::foo(int)"
if s.foo(3.0) != "foo:double":
raise RuntimeError, "Spam::foo(double)"
if s.foo("hello") != "foo:char *":
raise RuntimeError, "Spam::foo(char *)"
if s.foo(f) != "foo:Foo *":
raise RuntimeError, "Spam::foo(Foo *)"
if s.foo(b) != "foo:Bar *":
raise RuntimeError, "Spam::foo(Bar *)"
if s.foo(v) != "foo:void *":
raise RuntimeError, "Spam::foo(void *)"
if Spam_bar(3) != "bar:int":
raise RuntimeError, "Spam::bar(int)"
if Spam_bar(3.0) != "bar:double":
raise RuntimeError, "Spam::bar(double)"
if Spam_bar("hello") != "bar:char *":
raise RuntimeError, "Spam::bar(char *)"
if Spam_bar(f) != "bar:Foo *":
raise RuntimeError, "Spam::bar(Foo *)"
if Spam_bar(b) != "bar:Bar *":
raise RuntimeError, "Spam::bar(Bar *)"
if Spam_bar(v) != "bar:void *":
raise RuntimeError, "Spam::bar(void *)"
# Test constructors
s = Spam()
if s.type != "none":
raise RuntimeError, "Spam()"
s = Spam(3)
if s.type != "int":
raise RuntimeError, "Spam(int)"
s = Spam(3.4)
if s.type != "double":
raise RuntimeError, "Spam(double)"
s = Spam("hello")
if s.type != "char *":
raise RuntimeError, "Spam(char *)"
s = Spam(f)
if s.type != "Foo *":
raise RuntimeError, "Spam(Foo *)"
s = Spam(b)
if s.type != "Bar *":
raise RuntimeError, "Spam(Bar *)"
s = Spam(v)
if s.type != "void *":
raise RuntimeError, "Spam(void *)"
# unsigned long long
ullmax = 9223372036854775807 # 0xffffffffffffffff
ullmaxd = 9007199254740992.0
ullmin = 0
ullmind = 0.0
if ull(ullmin) != ullmin:
raise RuntimeError, "ull(ullmin)"
if ull(ullmax) != ullmax:
raise RuntimeError, "ull(ullmax)"
if ull(ullmind) != ullmind:
raise RuntimeError, "ull(ullmind)"
if ull(ullmaxd) != ullmaxd:
raise RuntimeError, "ull(ullmaxd)"
# long long
llmax = 9223372036854775807 # 0x7fffffffffffffff
llmin = -9223372036854775808
# these are near the largest floats we can still convert into long long
llmaxd = 9007199254740992.0
llmind = -9007199254740992.0
if ll(llmin) != llmin:
raise RuntimeError, "ll(llmin)"
if ll(llmax) != llmax:
raise RuntimeError, "ll(llmax)"
if ll(llmind) != llmind:
raise RuntimeError, "ll(llmind)"
if ll(llmaxd) != llmaxd:
raise RuntimeError, "ll(llmaxd)"
free_void(v)
import python_pickle
import pickle
import sys
def check(p):
msg = p.msg
if msg != "hi there":
raise RuntimeError("Bad, got: " + msg)
python_pickle.cvar.debug = False
p = python_pickle.PickleMe("hi there")
check(p)
r = p.__reduce__()
if python_pickle.cvar.debug:
print "__reduce__ returned:", r
pickle_string = pickle.dumps(p)
newp = pickle.loads(pickle_string)
check(newp)
# Not yet working... some crash and others are not producing a sensible "can't be pickled" error
#nfp = python_pickle.NotForPickling("no no")
#print nfp.__reduce__()
#pickle_string = pickle.dumps(nfp)
#print pickle_string
#newp = pickle.loads(pickle_string)
#print newp.msg
# run:
# python python_pybuffer_runme.py benchmark
# for the benchmark, other wise the test case will be run
import python_pybuffer
import sys
def check(flag):
if not flag:
raise RuntimeError("Test failed")
if len(sys.argv) >= 2 and sys.argv[1] == "benchmark":
# run the benchmark
import time
k = 1000000 # number of times to execute the functions
t = time.time()
a = bytearray(b"hello world")
for i in range(k):
python_pybuffer.title1(a)
print "Time used by bytearray:", time.time() - t
t = time.time()
b = "hello world"
for i in range(k):
python_pybuffer.title2(b)
print "Time used by string:", time.time() - t
else:
# run the test case
buf1 = bytearray(10)
buf2 = bytearray(50)
python_pybuffer.func1(buf1)
check(buf1 == b"a" * 10)
python_pybuffer.func2(buf2)
check(buf2.startswith(b"Hello world!\x00"))
count = python_pybuffer.func3(buf2)
check(count == 10) # number of alpha and number in 'Hello world!'
length = python_pybuffer.func4(buf2)
check(length == 12)
buf3 = bytearray(b"hello")
python_pybuffer.title1(buf3)
check(buf3 == b"Hello")
import python_pythoncode
# No need to actually do anything, this is a regression test for a bug which
# caused an invalid python_pythoncode.py to be generated, so if we can import
# it the bug is still fixed.
# A later test enhancement checking __new__ requires some code...
f = python_pythoncode.get_foo()
f = python_pythoncode.Foo()
import python_richcompare
import sys
def check_unorderable_types(exception):
# if str(exception).find("unorderable types") == -1:
# raise RuntimeError("A TypeError 'unorderable types' exception was expected"), None, sys.exc_info()[2]
pass # Exception message seems to vary from one version of Python to another
base1 = python_richcompare.BaseClass(1)
base2 = python_richcompare.BaseClass(2)
base3 = python_richcompare.BaseClass(3)
a1 = python_richcompare.SubClassA(1)
a2 = python_richcompare.SubClassA(2)
a3 = python_richcompare.SubClassA(3)
b1 = python_richcompare.SubClassB(1)
b2 = python_richcompare.SubClassB(2)
b3 = python_richcompare.SubClassB(3)
# Check == and != within a single type
#-------------------------------------------------------------------------
if not (base1 == base1):
raise RuntimeError("Object not == to itself")
if not (base1 == python_richcompare.BaseClass(1)):
raise RuntimeError("Object not == to an equivalent object")
if (base1 == base2):
raise RuntimeError(
"Comparing non-equivalent objects of the same type, == returned True")
if (base1 != base1):
raise RuntimeError("Object is != itself")
if (base1 != python_richcompare.BaseClass(1)):
raise RuntimeError("Object is != an equivalent object")
if not (base1 != base2):
raise RuntimeError(
"Comparing non-equivalent objects of the same type, != returned False")
# Check redefined operator== in SubClassA
#-------------------------------------------------------------------------
if (a2 == base2):
raise RuntimeError("Redefined operator== in SubClassA failed")
if (a2 == b2):
raise RuntimeError("Redefined operator== in SubClassA failed")
if not (a1 == a2):
raise RuntimeError("Redefined operator== in SubClassA failed")
# Check up-casting of subclasses
#-------------------------------------------------------------------------
if (base2 != a2):
raise RuntimeError(
"Comparing equivalent base and subclass instances, != returned True")
if (a2 == base2):
raise RuntimeError(
"Comparing non-equivalent base and subclass instances, == returned True")
if (a1 == b1):
raise RuntimeError(
"Comparing equivalent instances of different subclasses, == returned True")
if (b1 == a1):
raise RuntimeError(
"Comparing equivalent instances of different subclasses, == returned True")
# Check comparison to other objects
#-------------------------------------------------------------------------------
if (base1 == 42) :
raise RuntimeError("Comparing class to incompatible type, == returned True")
if not (base1 != 42) :
raise RuntimeError("Comparing class to incompatible type, != returned False")
if (a1 == 42) :
raise RuntimeError("Comparing class (with overloaded operator ==) to incompatible type, == returned True")
if not (a1 != 42) :
raise RuntimeError("Comparing class (with overloaded operator ==) to incompatible type, != returned False")
# Check inequalities
#-------------------------------------------------------------------------
if (a2 > b2):
raise RuntimeError("operator> failed")
if (a2 < b2):
raise RuntimeError("operator< failed")
if not (a2 >= b2):
raise RuntimeError("operator>= failed")
if not (a2 <= b2):
raise RuntimeError("operator<= failed")
# Check inequalities to other objects
#-------------------------------------------------------------------------------
if sys.version_info[0:2] < (3, 0):
if (base1 < 42):
raise RuntimeError("Comparing class to incompatible type, < returned True")
if (base1 <= 42):
raise RuntimeError("Comparing class to incompatible type, <= returned True")
if not (base1 > 42):
raise RuntimeError("Comparing class to incompatible type, > returned False")
if not (base1 >= 42):
raise RuntimeError("Comparing class to incompatible type, >= returned False")
else:
# Python 3 throws: TypeError: unorderable types
try:
res = base1 < 42
raise RuntimeError("Failed to throw")
except TypeError,e:
check_unorderable_types(e)
try:
res = base1 <= 42
raise RuntimeError("Failed to throw")
except TypeError,e:
check_unorderable_types(e)
try:
res = base1 > 42
raise RuntimeError("Failed to throw")
except TypeError,e:
check_unorderable_types(e)
try:
res = base1 >= 42
raise RuntimeError("Failed to throw")
except TypeError,e:
check_unorderable_types(e)
# Check inequalities used for ordering
#-------------------------------------------------------------------------
x = sorted([a2, a3, a1])
if not (x[0] is a1):
raise RuntimeError("Ordering failed")
if not (x[1] is a2):
raise RuntimeError("Ordering failed")
if not (x[2] is a3):
raise RuntimeError("Ordering failed")
x = sorted([base2, a3, b1])
if not (x[0] is b1):
raise RuntimeError("Ordering failed")
if not (x[1] is base2):
raise RuntimeError("Ordering failed")
if not (x[2] is a3):
raise RuntimeError("Ordering failed")
import python_strict_unicode
test_bytes = b"hello \x01world\x99"
BYTES = b"BYTES"
test_unicode = u"h\udce9llo w\u00f6rld"
# Test that byte string inputs and outputs work as expected
bdbl = python_strict_unicode.double_str(test_bytes)
if bdbl != test_bytes + test_bytes:
raise RuntimeError("Failed to double string")
if type(bdbl) != type(BYTES):
raise RuntimeError("Wrong type output for string")
bout = python_strict_unicode.same_str(test_bytes)
if bout != test_bytes:
raise RuntimeError("Failed to copy char*")
if type(bout) != type(BYTES):
raise RuntimeError("Wrong type output for char*")
# Test that unicode string inputs and outputs work as expected
udbl = python_strict_unicode.double_wstr(test_unicode)
if udbl != test_unicode + test_unicode:
raise RuntimeError("Failed to double wide string")
if type(udbl) != type(u""):
raise RuntimeError("Wrong type output for wide string")
uout = python_strict_unicode.same_wstr(test_unicode)
if uout != test_unicode:
raise RuntimeError("Failed to copy wchar_t*")
if type(uout) != type(u""):
raise RuntimeError("Wrong type output for wchar_t*")
# Test that overloading is handled properly
bovr = python_strict_unicode.overload(test_bytes)
if bovr != BYTES:
raise RuntimeError("Failed to return bytes from overload")
if type(bovr) != type(BYTES):
raise RuntimeError("Wrong type output from overload")
uovr = python_strict_unicode.overload(test_unicode)
if uovr != u"UNICODE":
raise RuntimeError("Failed to return unicode from overload")
if type(uovr) != type(u""):
raise RuntimeERror("Wrong type output from overload")
# Test that bytes aren't accepted as wide strings and unicode isn't accepted as narrow strings
try:
python_strict_unicode.double_str(test_unicode)
error = 1
except TypeError:
error = 0
if error:
raise RuntimeError("Unicode accepted for string")
try:
python_strict_unicode.same_str(test_unicode)
error = 1
except TypeError:
error = 0
if error:
raise RuntimeError("Unicode accepted for char*")
try:
python_strict_unicode.double_wstr(test_bytes)
error = 1
except TypeError:
error = 0
if error:
raise RuntimeError("Bytes accepted for wstring")
try:
python_strict_unicode.same_wstr(test_bytes)
error = 1
except TypeError:
error = 0
if error:
raise RuntimeError("Bytes accepted for wchar_t*")
from python_threads import *
action = ActionGroup()
count = 1
for child in action.GetActionList():
if child.val != count:
raise RuntimeError(
"Expected: " + str(count) + " got: " + str(child.val))
count = count + 1
# Was seg faulting at the end here
import python_varargs_typemap
if (python_varargs_typemap.testfunc(1, 2.0, "three") != "three"):
raise RuntimeError("testfunc failed!")
if (python_varargs_typemap.testfunc(1, 2.0, "three", "four", "five") != "threefourfive"):
raise RuntimeError("testfunc failed! {}")
from refcount import *
#
# very innocent example
#
a = A3()
b1 = B(a)
b2 = B_create(a)
if a.ref_count() != 3:
raise RuntimeError("Count = %d" % a.ref_count())
rca = b2.get_rca()
b3 = B_create(rca)
if a.ref_count() != 5:
raise RuntimeError("Count = %d" % a.ref_count())
v = vector_A(2)
v[0] = a
v[1] = a
x = v[0]
del v
if a.ref_count() != 6:
raise RuntimeError("Count = %d" % a.ref_count())
# Check %newobject
b4 = b2.cloner()
if b4.ref_count() != 1:
raise RuntimeError
b5 = global_create(a)
if b5.ref_count() != 1:
raise RuntimeError
b6 = Factory_create(a)
if b6.ref_count() != 1:
raise RuntimeError
b7 = Factory().create2(a)
if b7.ref_count() != 1:
raise RuntimeError
if a.ref_count() != 10:
raise RuntimeError("Count = %d" % a.ref_count())
del b4
del b5
del b6
del b7
if a.ref_count() != 6:
raise RuntimeError("Count = %d" % a.ref_count())
from reference_global_vars import *
# const class reference variable
if getconstTC().num != 33:
raise RuntimeError
# primitive reference variables
cvar.var_bool = createref_bool(False)
if value_bool(cvar.var_bool) != False:
raise RuntimeError
cvar.var_bool = createref_bool(True)
if value_bool(cvar.var_bool) != True:
raise RuntimeError
cvar.var_char = createref_char("w")
if value_char(cvar.var_char) != "w":
raise RuntimeError
cvar.var_unsigned_char = createref_unsigned_char(10)
if value_unsigned_char(cvar.var_unsigned_char) != 10:
raise RuntimeError
cvar.var_signed_char = createref_signed_char(10)
if value_signed_char(cvar.var_signed_char) != 10:
raise RuntimeError
cvar.var_short = createref_short(10)
if value_short(cvar.var_short) != 10:
raise RuntimeError
cvar.var_unsigned_short = createref_unsigned_short(10)
if value_unsigned_short(cvar.var_unsigned_short) != 10:
raise RuntimeError
cvar.var_int = createref_int(10)
if value_int(cvar.var_int) != 10:
raise RuntimeError
cvar.var_unsigned_int = createref_unsigned_int(10)
if value_unsigned_int(cvar.var_unsigned_int) != 10:
raise RuntimeError
cvar.var_long = createref_long(10)
if value_long(cvar.var_long) != 10:
raise RuntimeError
cvar.var_unsigned_long = createref_unsigned_long(10)
if value_unsigned_long(cvar.var_unsigned_long) != 10:
raise RuntimeError
cvar.var_long_long = createref_long_long(0x6FFFFFFFFFFFFFF8)
if value_long_long(cvar.var_long_long) != 0x6FFFFFFFFFFFFFF8:
raise RuntimeError
#ull = abs(0xFFFFFFF2FFFFFFF0)
ull = 55834574864
cvar.var_unsigned_long_long = createref_unsigned_long_long(ull)
if value_unsigned_long_long(cvar.var_unsigned_long_long) != ull:
raise RuntimeError
cvar.var_float = createref_float(10.5)
if value_float(cvar.var_float) != 10.5:
raise RuntimeError
cvar.var_double = createref_double(10.5)
if value_double(cvar.var_double) != 10.5:
raise RuntimeError
# class reference variable
cvar.var_TestClass = createref_TestClass(TestClass(20))
if value_TestClass(cvar.var_TestClass).num != 20:
raise RuntimeError
from rename_pcre_encoder import *
s = SomeWidget()
s.put_borderWidth(3)
if s.get_borderWidth() != 3:
raise RuntimeError("Border should be 3, not %d" % (s.get_borderWidth(),))
s.put_size(4, 5)
a = AnotherWidget()
a.DoSomething()
evt = wxEVTSomeEvent()
t = xUnchangedName()
if StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42:
raise RuntimeError("Unexpected result of renamed function call")
from rename_predicates import *
r = RenamePredicates(123)
r.MF_member_function()
r.MF_static_member_function()
r.MF_extend_function_before()
r.MF_extend_function_after()
GF_global_function()
if r.MV_member_variable != 123:
raise RuntimeError("variable wrong")
r.MV_member_variable = 1234
if r.MV_member_variable != 1234:
raise RuntimeError("variable wrong")
if cvar.RenamePredicates_MV_static_member_variable != 456:
raise RuntimeError("variable wrong")
cvar.RenamePredicates_MV_static_member_variable = 4567
if cvar.RenamePredicates_MV_static_member_variable != 4567:
raise RuntimeError("variable wrong")
if cvar.GV_global_variable != 789:
raise RuntimeError("variable wrong")
cvar.GV_global_variable = 7890
if cvar.GV_global_variable != 7890:
raise RuntimeError("variable wrong")
UC_UPPERCASE()
LC_lowercase()
TI_Title()
FU_FirstUpperCase()
FL_firstLowerCase()
CA_CamelCase()
LC_lowerCamelCase()
UC_under_case_it()
ex = ExtendCheck()
ex.MF_real_member1()
ex.MF_real_member2()
ex.EX_EXTENDMETHOD1()
ex.EX_EXTENDMETHOD2()
ex.EX_EXTENDMETHOD3()
from rename_rstrip_encoder import *
s = SomeThing()
a = AnotherThing()
a.DoClsX()
from rename_scope import *
a = Natural_UP()
b = Natural_BP()
if a.rtest() != 1:
raise RuntimeError
if b.rtest() != 1:
raise RuntimeError
f = equals
from rename_strip_encoder import *
s = SomeWidget()
a = AnotherWidget()
a.DoSomething()
import return_const_value
import sys
p = return_const_value.Foo_ptr_getPtr()
if (p.getVal() != 17):
print "Runtime test1 failed. p.getVal()=", p.getVal()
sys.exit(1)
p = return_const_value.Foo_ptr_getConstPtr()
if (p.getVal() != 17):
print "Runtime test2 failed. p.getVal()=", p.getVal()
sys.exit(1)
import ret_by_value
a = ret_by_value.get_test()
if a.myInt != 100:
raise RuntimeError
if a.myShort != 200:
raise RuntimeError
from smart_pointer_const_overload import *
CONST_ACCESS = 1
MUTABLE_ACCESS = 2
def test(b, f):
if f.x != 0:
raise RuntimeError
# Test member variable get
if b.x != 0:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test member variable set
b.x = 1
if f.x != 1:
raise RuntimeError
if f.access != MUTABLE_ACCESS:
raise RuntimeError
# Test const method
if b.getx() != 1:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test mutable method
b.setx(2)
if f.x != 2:
raise RuntimeError
if f.access != MUTABLE_ACCESS:
raise RuntimeError
# Test extended const method
if b.getx2() != 2:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test extended mutable method
b.setx2(3)
if f.x != 3:
raise RuntimeError
if f.access != MUTABLE_ACCESS:
raise RuntimeError
# Test static method
b.statMethod()
if f.access != CONST_ACCESS:
raise RuntimeError
# Test const member
f.access = MUTABLE_ACCESS
if b.y != 0:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test get through mutable pointer to const member
f.access = MUTABLE_ACCESS
if get_int(b.yp) != 0:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test get through const pointer to mutable member
f.x = 4
f.access = MUTABLE_ACCESS
if get_int(b.xp) != 4:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test set through const pointer to mutable member
f.access = MUTABLE_ACCESS
set_int(b.xp, 5)
if f.x != 5:
raise RuntimeError
if f.access != CONST_ACCESS:
raise RuntimeError
# Test set pointer to const member
b.yp = new_int(6)
if f.y != 0:
raise RuntimeError
if get_int(f.yp) != 6:
raise RuntimeError
if f.access != MUTABLE_ACCESS:
raise RuntimeError
delete_int(f.yp)
f = Foo()
b = Bar(f)
f2 = Foo()
b2 = Bar2(f2)
test(b, f)
test(b2, f2)
from smart_pointer_extend import *
f = Foo()
b = Bar(f)
if b.extension() != f.extension():
raise RuntimeError
b = CBase()
d = CDerived()
p = CPtr()
if b.bar() != p.bar():
raise RuntimeError
if d.foo() != p.foo():
raise RuntimeError
if b.hello() != p.hello():
raise RuntimeError
d = DFoo()
dp = DPtrFoo(d)
if d.SExt(1) != dp.SExt(1):
raise RuntimeError
if d.Ext(1) != dp.Ext(1):
raise RuntimeError
from smart_pointer_member import *
f = Foo()
f.y = 1
if f.y != 1:
raise RuntimeError
b = Bar(f)
b.y = 2
if f.y != 2:
print f.y
print b.y
raise RuntimeError
if b.x != f.x:
raise RuntimeError
if b.z != f.z:
raise RuntimeError
if Foo.z == Bar.z:
raise RuntimeError
from smart_pointer_multi import *
f = Foo()
b = Bar(f)
s = Spam(b)
g = Grok(b)
s.x = 3
if s.getx() != 3:
raise RuntimeError
g.x = 4
if g.getx() != 4:
raise RuntimeError
from smart_pointer_multi_typedef import *
f = Foo()
b = Bar(f)
s = Spam(b)
g = Grok(b)
s.x = 3
if s.getx() != 3:
raise RuntimeError
g.x = 4
if g.getx() != 4:
raise RuntimeError
from smart_pointer_not import *
f = Foo()
b = Bar(f)
s = Spam(f)
g = Grok(f)
try:
x = b.x
print "Error! b.x"
except:
pass
try:
x = s.x
print "Error! s.x"
except:
pass
try:
x = g.x
print "Error! g.x"
except:
pass
try:
x = b.getx()
print "Error! b.getx()"
except:
pass
try:
x = s.getx()
print "Error! s.getx()"
except:
pass
try:
x = g.getx()
print "Error! g.getx()"
except:
pass
from smart_pointer_overload import *
f = Foo()
b = Bar(f)
if f.test(3) != 1:
raise RuntimeError
if f.test(3.5) != 2:
raise RuntimeError
if f.test("hello") != 3:
raise RuntimeError
if b.test(3) != 1:
raise RuntimeError
if b.test(3.5) != 2:
raise RuntimeError
if b.test("hello") != 3:
raise RuntimeError
from smart_pointer_rename import *
f = Foo()
b = Bar(f)
if b.test() != 3:
raise RuntimeError
if b.ftest1(1) != 1:
raise RuntimeError
if b.ftest2(2, 3) != 2:
raise RuntimeError
from smart_pointer_simple import *
f = Foo()
b = Bar(f)
b.x = 3
if b.getx() != 3:
raise RuntimeError
fp = b.__deref__()
fp.x = 4
if fp.getx() != 4:
raise RuntimeError
from smart_pointer_templatevariables import *
d = DiffImContainerPtr_D(create(1234, 5678))
if (d.id != 1234):
raise RuntimeError
# if (d.xyz != 5678):
# raise RuntimeError
d.id = 4321
#d.xyz = 8765
if (d.id != 4321):
raise RuntimeError
# if (d.xyz != 8765):
# raise RuntimeError
from smart_pointer_typedef import *
f = Foo()
b = Bar(f)
b.x = 3
if b.getx() != 3:
raise RuntimeError
fp = b.__deref__()
fp.x = 4
if fp.getx() != 4:
raise RuntimeError
import sneaky1
x = sneaky1.add(3, 4)
y = sneaky1.subtract(3, 4)
z = sneaky1.mul(3, 4)
w = sneaky1.divide(3, 4)
import special_variable_macros
name = special_variable_macros.Name()
if special_variable_macros.testFred(name) != "none":
raise "test failed"
if special_variable_macros.testJack(name) != "$specialname":
raise "test failed"
if special_variable_macros.testJill(name) != "jilly":
raise "test failed"
if special_variable_macros.testMary(name) != "SWIGTYPE_p_NameWrap":
raise "test failed"
if special_variable_macros.testJames(name) != "SWIGTYPE_Name":
raise "test failed"
if special_variable_macros.testJim(name) != "multiname num":
raise "test failed"
if special_variable_macros.testJohn(special_variable_macros.PairIntBool(10, False)) != 123:
raise "test failed"
from static_const_member_2 import *
c = Test_int()
try:
a = c.forward_field
a = c.current_profile
a = c.RightIndex
a = Test_int.backward_field
a = Test_int.LeftIndex
a = Test_int.cavity_flags
except:
raise RuntimeError
if Foo.BAZ.val != 2 * Foo.BAR.val:
raise RuntimeError
import sys
import std_containers
cube = (((1, 2), (3, 4)), ((5, 6), (7, 8)))
icube = std_containers.cident(cube)
for i in range(0, len(cube)):
if cube[i] != icube[i]:
raise RuntimeError, "bad cident"
p = (1, 2)
if p != std_containers.pident(p):
raise RuntimeError, "bad pident"
v = (1, 2, 3, 4, 5, 6)
iv = std_containers.vident(v)
for i in range(0, len(v)):
if v[i] != iv[i]:
raise RuntimeError, "bad vident"
iv = std_containers.videntu(v)
for i in range(0, len(v)):
if v[i] != iv[i]:
raise RuntimeError, "bad videntu"
vu = std_containers.vector_ui(v)
if vu[2] != std_containers.videntu(vu)[2]:
raise RuntimeError, "bad videntu"
if v[0:3][1] != vu[0:3][1]:
print v[0:3][1], vu[0:3][1]
raise RuntimeError, "bad getslice"
m = ((1, 2, 3), (2, 3), (3, 4))
im = std_containers.midenti(m)
for i in range(0, len(m)):
for j in range(0, len(m[i])):
if m[i][j] != im[i][j]:
raise RuntimeError, "bad getslice"
m = ((True, False, True), (True, True), (True, True))
im = std_containers.midentb(m)
for i in range(0, len(m)):
for j in range(0, len(m[i])):
if m[i][j] != im[i][j]:
raise RuntimeError, "bad getslice"
mi = std_containers.imatrix(m)
mc = std_containers.cmatrix(m)
if mi[0][1] != mc[0][1]:
raise RuntimeError, "bad matrix"
map = {}
map["hello"] = 1
map["hi"] = 2
map["3"] = 2
imap = std_containers.mapident(map)
for k in map:
if map[k] != imap[k]:
raise RuntimeError, "bad map"
# Test __contains__ (required for 'x in y' to work)
if not imap.__contains__("hello"):
raise RuntimeError("hello imap.__contains__")
if "hello" not in imap:
raise RuntimeError("hello not in imap")
if imap.__contains__("oops"):
raise RuntimeError("oops imap.__contains__")
if "oops" in imap:
raise RuntimeError("oops in imap")
mapc = {}
c1 = std_containers.C()
c2 = std_containers.C()
mapc[1] = c1.this
mapc[2] = c2
std_containers.mapidentc(mapc)
vi = std_containers.vector_i((2, 2, 3, 4))
v = (1, 2)
v1 = std_containers.v_inout(vi)
vi[1], v1[1]
v1, v2 = ((1, 2), (3, 4))
v1, v2 = std_containers.v_inout2(v1, v2)
a1 = std_containers.A(1)
a2 = std_containers.A(2)
p1 = (1, a1)
p2 = (2, a2)
v = (p1, p2)
v2 = std_containers.pia_vident(v)
v2[0][1].a
v2[1][1].a
v3 = std_containers.vector_piA(v2)
v3[0][1].a
v3[1][1].a
s = std_containers.set_i()
s.append(1)
s.append(2)
s.append(3)
j = 1
for i in s:
if i != j:
raise RuntimeError
j = j + 1
# Test __contains__ (required for 'x in y' to work)
if not s.__contains__(3):
raise RuntimeError("3 s.__contains__")
if 3 not in s:
raise RuntimeError("3 not in s")
if s.__contains__(-1):
raise RuntimeError("-1 s.__contains__")
if -1 in s:
raise RuntimeError("-1 in s")
from struct_initialization import *
if cvar.instanceC1.x != 10:
raise RuntimeError
if cvar.instanceD1.x != 10:
raise RuntimeError
if cvar.instanceD2.x != 20:
raise RuntimeError
if cvar.instanceD3.x != 30:
raise RuntimeError
if cvar.instanceE1.x != 1:
raise RuntimeError
if cvar.instanceF1.x != 1:
raise RuntimeError
import struct_rename
b = struct_rename.Bar()
import struct_value
b = struct_value.Bar()
b.a.x = 3
if b.a.x != 3:
raise RuntimeError
b.b.x = 3
if b.b.x != 3:
raise RuntimeError
# Test dynamically added attributes - Github pull request #320
b.added = 123
if b.added != 123:
raise RuntimeError("Wrong attribute value")
if not b.__dict__.has_key("added"):
raise RuntimeError("Missing added attribute in __dict__")
class PyBar(struct_value.Bar):
def __init__(self):
self.extra = "hi"
struct_value.Bar.__init__(self)
pybar = PyBar()
if not pybar.__dict__.has_key("extra"):
raise RuntimeError("Missing extra attribute in __dict__")
if pybar.extra != "hi":
raise RuntimeError("Incorrect attribute value for extra")
from swigobject import *
a = A()
a1 = a_ptr(a)
a2 = a_ptr(a)
if a1.this != a2.this:
raise RuntimeError
lthis = long(a.this)
# match pointer value, but deal with leading zeros on 8/16 bit systems and
# different C++ compilers interpretation of %p
xstr1 = "%016X" % (lthis,)
xstr1 = str.lstrip(xstr1, "0")
xstr2 = pointer_str(a)
xstr2 = str.replace(xstr2, "0x", "")
xstr2 = str.replace(xstr2, "0X", "")
xstr2 = str.lstrip(xstr2, "0")
xstr2 = str.upper(xstr2)
if xstr1 != xstr2:
print xstr1, xstr2
raise RuntimeError
s = str(a.this)
r = repr(a.this)
v1 = v_ptr(a)
v2 = v_ptr(a)
if long(v1) != long(v2):
raise RuntimeError
from template_classes import *
# This test is just testing incorrect number of arguments/parameters checking
point = PointInt()
rectangle = RectangleInt()
rectangle.setPoint(point)
rectangle.getPoint()
RectangleInt.static_noargs()
RectangleInt.static_onearg(1)
fail = True
try:
rectangle.setPoint()
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
rectangle.getPoint(0)
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
RectangleInt.static_noargs(0)
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
fail = True
try:
RectangleInt.static_onearg()
except TypeError, e:
fail = False
if fail:
raise RuntimeError("argument count check failed")
from template_class_reuse_name import *
Bool1().tt()
Bool1False().ff()
Bool2().tt()
Bool2False().ff()
Bool3().tt()
Bool3False().ff()
Bool4().tt()
Bool4False().ff()
BoolForward1().tt()
BoolForward1False().ff()
BoolForward2().tt()
BoolForward2False().ff()
BoolForward3().tt()
BoolForward3False().ff()
BoolForward4().tt()
BoolForward4False().ff()
IntBool1().tt()
IntBool1False().ff()
IntBool2().tt()
IntBool2False().ff()
IntBool3().tt()
IntBool3False().ff()
IntBool4().tt()
IntBool4False().ff()
Duplicate2_0().n()
Duplicate3().n()
import template_construct
from template_default_arg_overloaded_extend import *
def check(flag):
if not flag:
raise RuntimeError("failed")
rs = ResultSet()
check(rs.go_get_method(0, SearchPoint()) == -1)
check(rs.go_get_method(0, SearchPoint(), 100) == 100)
check(rs.go_get_template(0, SearchPoint()) == -2)
check(rs.go_get_template(0, SearchPoint(), 100) == 100)
check(rs.over() == "over(int)")
check(rs.over(10) == "over(int)")
check(rs.over(SearchPoint()) == "over(giai2::SearchPoint, int)")
check(rs.over(SearchPoint(), 10) == "over(giai2::SearchPoint, int)")
check(rs.over(True, SearchPoint()) == "over(bool, gaia2::SearchPoint, int)")
check(rs.over(True, SearchPoint(), 10) == "over(bool, gaia2::SearchPoint, int)")
from template_default_arg_overloaded import *
def check(expected, got):
if expected != got:
raise RuntimeError("Expected: " + str(expected) + " got: " + str(got))
pl = PropertyList()
check(1, pl.setInt("int", 10))
check(1, pl.setInt("int", 10, False))
check(2, pl.set("int", pl))
check(2, pl.set("int", pl, False))
check(3, pl.setInt("int", 10, "int"))
check(3, pl.setInt("int", 10, "int", False))
pl = PropertyListGlobal()
check(1, pl.setIntGlobal("int", 10))
check(1, pl.setIntGlobal("int", 10, False))
check(2, pl.set("int", pl))
check(2, pl.set("int", pl, False))
check(3, pl.setIntGlobal("int", 10, "int"))
check(3, pl.setIntGlobal("int", 10, "int", False))
check(1, GoopIntGlobal(10))
check(1, GoopIntGlobal(10, True))
check(2, goopGlobal(3))
check(2, goopGlobal())
check(3, GoopIntGlobal("int", False))
check(3, GoopIntGlobal("int"))
check(1, GoopInt(10))
check(1, GoopInt(10, True))
check(2, goop(3))
check(2, goop())
check(3, GoopInt("int", False))
check(3, GoopInt("int"))
import template_default_arg
helloInt = template_default_arg.Hello_int()
helloInt.foo(template_default_arg.Hello_int.hi)
x = template_default_arg.X_int()
if (x.meth(20.0, 200) != 200):
raise RuntimeError, ("X_int test 1 failed")
if (x.meth(20) != 20):
raise RuntimeError, ("X_int test 2 failed")
if (x.meth() != 0):
raise RuntimeError, ("X_int test 3 failed")
y = template_default_arg.Y_unsigned()
if (y.meth(20.0, 200) != 200):
raise RuntimeError, ("Y_unsigned test 1 failed")
if (y.meth(20) != 20):
raise RuntimeError, ("Y_unsigned test 2 failed")
if (y.meth() != 0):
raise RuntimeError, ("Y_unsigned test 3 failed")
x = template_default_arg.X_longlong()
x = template_default_arg.X_longlong(20.0)
x = template_default_arg.X_longlong(20.0, 200L)
x = template_default_arg.X_int()
x = template_default_arg.X_int(20.0)
x = template_default_arg.X_int(20.0, 200)
x = template_default_arg.X_hello_unsigned()
x = template_default_arg.X_hello_unsigned(20.0)
x = template_default_arg.X_hello_unsigned(
20.0, template_default_arg.Hello_int())
y = template_default_arg.Y_hello_unsigned()
y.meth(20.0, template_default_arg.Hello_int())
y.meth(template_default_arg.Hello_int())
y.meth()
fz = template_default_arg.Foo_Z_8()
x = template_default_arg.X_Foo_Z_8()
fzc = x.meth(fz)
# Templated functions
# plain function: int ott(Foo<int>)
if (template_default_arg.ott(template_default_arg.Foo_int()) != 30):
raise RuntimeError, ("ott test 1 failed")
# %template(ott) ott<int, int>
if (template_default_arg.ott() != 10):
raise RuntimeError, ("ott test 2 failed")
if (template_default_arg.ott(1) != 10):
raise RuntimeError, ("ott test 3 failed")
if (template_default_arg.ott(1, 1) != 10):
raise RuntimeError, ("ott test 4 failed")
if (template_default_arg.ott("hi") != 20):
raise RuntimeError, ("ott test 5 failed")
if (template_default_arg.ott("hi", 1) != 20):
raise RuntimeError, ("ott test 6 failed")
if (template_default_arg.ott("hi", 1, 1) != 20):
raise RuntimeError, ("ott test 7 failed")
# %template(ott) ott<const char *>
if (template_default_arg.ottstring(template_default_arg.Hello_int(), "hi") != 40):
raise RuntimeError, ("ott test 8 failed")
if (template_default_arg.ottstring(template_default_arg.Hello_int()) != 40):
raise RuntimeError, ("ott test 9 failed")
# %template(ott) ott<int>
if (template_default_arg.ottint(template_default_arg.Hello_int(), 1) != 50):
raise RuntimeError, ("ott test 10 failed")
if (template_default_arg.ottint(template_default_arg.Hello_int()) != 50):
raise RuntimeError, ("ott test 11 failed")
# %template(ott) ott<double>
if (template_default_arg.ott(template_default_arg.Hello_int(), 1.0) != 60):
raise RuntimeError, ("ott test 12 failed")
if (template_default_arg.ott(template_default_arg.Hello_int()) != 60):
raise RuntimeError, ("ott test 13 failed")
import template_default_cache
ap = template_default_cache.get_mp_a();
bp = template_default_cache.get_mp_b();
if not isinstance(ap, template_default_cache.AModelPtr):
raise RuntimeError("get_mp_a fail")
if not isinstance(bp, template_default_cache.BModelPtr):
raise RuntimeError("get_mp_b fail")
import template_extend1
a = template_extend1.lBaz()
b = template_extend1.dBaz()
if a.foo() != "lBaz::foo":
raise RuntimeError
if b.foo() != "dBaz::foo":
raise RuntimeError
import template_extend2
a = template_extend2.lBaz()
b = template_extend2.dBaz()
if a.foo() != "lBaz::foo":
raise RuntimeError
if b.foo() != "dBaz::foo":
raise RuntimeError
from template_inherit import *
a = FooInt()
b = FooDouble()
c = BarInt()
d = BarDouble()
e = FooUInt()
f = BarUInt()
if a.blah() != "Foo":
raise ValueError
if b.blah() != "Foo":
raise ValueError
if e.blah() != "Foo":
raise ValueError
if c.blah() != "Bar":
raise ValueError
if d.blah() != "Bar":
raise ValueError
if f.blah() != "Bar":
raise ValueError
if c.foomethod() != "foomethod":
raise ValueError
if d.foomethod() != "foomethod":
raise ValueError
if f.foomethod() != "foomethod":
raise ValueError
if invoke_blah_int(a) != "Foo":
raise ValueError
if invoke_blah_int(c) != "Bar":
raise ValueError
if invoke_blah_double(b) != "Foo":
raise ValueError
if invoke_blah_double(d) != "Bar":
raise ValueError
if invoke_blah_uint(e) != "Foo":
raise ValueError
if invoke_blah_uint(f) != "Bar":
raise ValueError
from template_matrix import *
passVector([1, 2, 3])
passMatrix([[1, 2], [1, 2, 3]])
passCube([[[1, 2], [1, 2, 3]], [[1, 2], [1, 2, 3]]])
from template_ns4 import *
d = make_Class_DD()
if d.test() != "test":
raise RuntimeError
from template_ns import *
p1 = pairii(2, 3)
p2 = pairii(p1)
if p2.first != 2:
raise RuntimeError
if p2.second != 3:
raise RuntimeError
p3 = pairdd(3.5, 2.5)
p4 = pairdd(p3)
if p4.first != 3.5:
raise RuntimeError
if p4.second != 2.5:
raise RuntimeError
import template_opaque
v = template_opaque.OpaqueVectorType(10)
template_opaque.FillVector(v)
import template_ref_type
xr = template_ref_type.XC()
y = template_ref_type.Y()
y.find(xr)
import template_rename
i = template_rename.iFoo()
d = template_rename.dFoo()
a = i.blah_test(4)
b = i.spam_test(5)
c = i.groki_test(6)
x = d.blah_test(7)
y = d.spam(8)
z = d.grok_test(9)
from template_static import *
Foo_bar_double(1)
from template_tbase_template import *
a = make_Class_dd()
if a.test() != "test":
raise RuntimeError
from template_typedef_cplx2 import *
#
# double case
#
try:
d = make_Identity_double()
a = d.this
except:
print d, "is not an instance"
raise RuntimeError
s = "%s" % d
if str.find(s, "ArithUnaryFunction") == -1:
print d, "is not an ArithUnaryFunction"
raise RuntimeError
try:
e = make_Multiplies_double_double_double_double(d, d)
a = e.this
except:
print e, "is not an instance"
raise RuntimeError
s = "%s" % e
if str.find(s, "ArithUnaryFunction") == -1:
print e, "is not an ArithUnaryFunction"
raise RuntimeError
#
# complex case
#
try:
c = make_Identity_complex()
a = c.this
except:
print c, "is not an instance"
raise RuntimeError
s = "%s" % c
if str.find(s, "ArithUnaryFunction") == -1:
print c, "is not an ArithUnaryFunction"
raise RuntimeError
try:
f = make_Multiplies_complex_complex_complex_complex(c, c)
a = f.this
except:
print f, "is not an instance"
raise RuntimeError
s = "%s" % f
if str.find(s, "ArithUnaryFunction") == -1:
print f, "is not an ArithUnaryFunction"
raise RuntimeError
#
# Mix case
#
try:
g = make_Multiplies_double_double_complex_complex(d, c)
a = g.this
except:
print g, "is not an instance"
raise RuntimeError
s = "%s" % g
if str.find(s, "ArithUnaryFunction") == -1:
print g, "is not an ArithUnaryFunction"
raise RuntimeError
try:
h = make_Multiplies_complex_complex_double_double(c, d)
a = h.this
except:
print h, "is not an instance"
raise RuntimeError
s = "%s" % h
if str.find(s, "ArithUnaryFunction") == -1:
print h, "is not an ArithUnaryFunction"
raise RuntimeError
try:
a = g.get_value()
except:
print g, "has not get_value() method"
raise RuntimeError
import string
from template_typedef_cplx3 import *
#
# this is OK
#
s = Sin()
s.get_base_value()
s.get_value()
s.get_arith_value()
my_func_r(s)
make_Multiplies_double_double_double_double(s, s)
z = CSin()
z.get_base_value()
z.get_value()
z.get_arith_value()
my_func_c(z)
make_Multiplies_complex_complex_complex_complex(z, z)
#
# Here we fail
#
d = make_Identity_double()
my_func_r(d)
c = make_Identity_complex()
my_func_c(c)
import string
from template_typedef_cplx4 import *
#
# this is OK
#
s = Sin()
s.get_base_value()
s.get_value()
s.get_arith_value()
my_func_r(s)
make_Multiplies_double_double_double_double(s, s)
z = CSin()
z.get_base_value()
z.get_value()
z.get_arith_value()
my_func_c(z)
make_Multiplies_complex_complex_complex_complex(z, z)
#
# Here we fail
#
d = make_Identity_double()
my_func_r(d)
c = make_Identity_complex()
my_func_c(c)
from template_typedef_cplx import *
#
# double case
#
try:
d = make_Identity_double()
a = d.this
except:
print d, "is not an instance"
raise RuntimeError
s = "%s" % d
if str.find(s, "ArithUnaryFunction") == -1:
print d, "is not an ArithUnaryFunction"
raise RuntimeError
try:
e = make_Multiplies_double_double_double_double(d, d)
a = e.this
except:
print e, "is not an instance"
raise RuntimeError
s = "%s" % e
if str.find(s, "ArithUnaryFunction") == -1:
print e, "is not an ArithUnaryFunction"
raise RuntimeError
#
# complex case
#
try:
c = make_Identity_complex()
a = c.this
except:
print c, "is not an instance"
raise RuntimeError
s = "%s" % c
if str.find(s, "ArithUnaryFunction") == -1:
print c, "is not an ArithUnaryFunction"
raise RuntimeError
try:
f = make_Multiplies_complex_complex_complex_complex(c, c)
a = f.this
except:
print f, "is not an instance"
raise RuntimeError
s = "%s" % f
if str.find(s, "ArithUnaryFunction") == -1:
print f, "is not an ArithUnaryFunction"
raise RuntimeError
#
# Mix case
#
try:
g = make_Multiplies_double_double_complex_complex(d, c)
a = g.this
except:
print g, "is not an instance"
raise RuntimeError
s = "%s" % g
if str.find(s, "ArithUnaryFunction") == -1:
print g, "is not an ArithUnaryFunction"
raise RuntimeError
try:
h = make_Multiplies_complex_complex_double_double(c, d)
a = h.this
except:
print h, "is not an instance"
raise RuntimeError
s = "%s" % h
if str.find(s, "ArithUnaryFunction") == -1:
print h, "is not an ArithUnaryFunction"
raise RuntimeError
from template_typedef_cplx2 import *
from template_typedef_import import *
#
# this is OK
#
s = Sin()
s.get_base_value()
s.get_value()
s.get_arith_value()
my_func_r(s)
make_Multiplies_double_double_double_double(s, s)
z = CSin()
z.get_base_value()
z.get_value()
z.get_arith_value()
my_func_c(z)
make_Multiplies_complex_complex_complex_complex(z, z)
#
# Here we fail
#
d = make_Identity_double()
my_func_r(d)
c = make_Identity_complex()
my_func_c(c)
from template_typedef import *
d = make_Identity_float()
c = make_Identity_reald()
try:
a = d.this
a = c.this
except:
raise RuntimeError
try:
e = make_Multiplies_float_float_float_float(d, d)
a = e.this
except:
print e, "is not an instance"
raise RuntimeError
try:
f = make_Multiplies_reald_reald_reald_reald(c, c)
a = f.this
except:
print f, "is not an instance"
raise RuntimeError
try:
g = make_Multiplies_float_float_reald_reald(d, c)
a = g.this
except:
print g, "is not an instance"
raise RuntimeError
# the old large format
if not SWIG_TypeQuery("vfncs::ArithUnaryFunction<vfncs::arith_traits<float,double>::argument_type,vfncs::arith_traits<float,double >::result_type > *"):
raise RuntimeError
# the reduced format
if not SWIG_TypeQuery("vfncs::ArithUnaryFunction<double,double> *"):
raise RuntimeError
# this is a bad name
if SWIG_TypeQuery("vfncs::ArithUnaryFunction<double,doublex> *"):
raise RuntimeError
from template_typemaps_typedef2 import *
m1 = MultimapIntA()
dummy_pair = m1.make_dummy_pair()
val = m1.typemap_test(dummy_pair).val
if val != 1234:
raise RuntimeError, "typemaps not working"
m2 = MultimapAInt()
# TODO: typemaps and specializations not quite working as expected. T needs expanding, but at least the right typemap is being picked up.
#dummy_pair = m2.make_dummy_pair()
#val = m2.typemap_test(dummy_pair)
# print val
# if val != 4321:
# raise RuntimeError, "typemaps not working"
if typedef_test1(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test1 not working"
if typedef_test2(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test2 not working"
if typedef_test3(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test3 not working"
if typedef_test4(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test4 not working"
if typedef_test5(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test5 not working"
if typedef_test6(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test6 not working"
from template_typemaps_typedef import *
m1 = MultimapIntA()
dummy_pair = m1.make_dummy_pair()
val = m1.typemap_test(dummy_pair).val
if val != 1234:
raise RuntimeError, "typemaps not working"
m2 = MultimapAInt()
# TODO: typemaps and specializations not quite working as expected. T needs expanding, but at least the right typemap is being picked up.
#dummy_pair = m2.make_dummy_pair()
#val = m2.typemap_test(dummy_pair)
# print val
# if val != 4321:
# raise RuntimeError, "typemaps not working"
if typedef_test1(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test1 not working"
if typedef_test2(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test2 not working"
if typedef_test3(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test3 not working"
if typedef_test4(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test4 not working"
if typedef_test5(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test5 not working"
if typedef_test6(dummy_pair).val != 1234:
raise RuntimeError, "typedef_test6 not working"
from template_type_namespace import *
if type(foo()[0]) != type(""):
raise RuntimeError
import template_using_directive_typedef
vo = template_using_directive_typedef.Vector_Obj();
h = template_using_directive_typedef.Holder();
h.holder_use1(vo, vo, vo);
h.holder_use2(vo, vo, vo);
h.holder_use3(vo, vo, vo);
template_using_directive_typedef.tns_holder_use(vo, vo);
template_using_directive_typedef.tns_use(vo, vo, vo);
template_using_directive_typedef.global_holder_use(vo);
template_using_directive_typedef.global_use(vo, vo, vo);
template_using_directive_typedef.ns1_holder_use(vo);
template_using_directive_typedef.ns2_holder_use(vo, vo, vo, vo);
import threads_exception
t = threads_exception.Test()
try:
t.unknown()
except RuntimeError, e:
pass
try:
t.simple()
except RuntimeError, e:
if e.args[0] != 37:
raise RuntimeError
try:
t.message()
except RuntimeError, e:
if e.args[0] != "I died.":
raise RuntimeError
# This is expected fail with -builtin option
# Throwing builtin classes as exceptions not supported
if not threads_exception.is_python_builtin():
try:
t.hosed()
except threads_exception.Exc, e:
code = e.code
if code != 42:
raise RuntimeError, "bad... code: %d" % code
msg = e.msg
if msg != "Hosed":
raise RuntimeError, "bad... msg: '%s' len: %d" % (msg, len(msg))
for i in range(1, 4):
try:
t.multi(i)
except RuntimeError, e:
pass
except threads_exception.Exc, e:
pass
from typedef_classforward_same_name import *
foo = Foo()
foo.x = 5
if extractFoo(foo) != 5:
raise RuntimeError("unexpected value")
boo = Boo()
boo.x = 5
if extractBoo(boo) != 5:
raise RuntimeError("unexpected value")
import typedef_class
a = typedef_class.RealA()
a.a = 3
b = typedef_class.B()
b.testA(a)
import typedef_funcptr
a = 100
b = 10
if typedef_funcptr.do_op(a,b,typedef_funcptr.addf) != 110:
raise RuntimeError("addf failed")
if typedef_funcptr.do_op(a,b,typedef_funcptr.subf) != 90:
raise RuntimeError("subf failed")
if typedef_funcptr.do_op_typedef_int(a,b,typedef_funcptr.addf) != 110:
raise RuntimeError("addf failed")
if typedef_funcptr.do_op_typedef_int(a,b,typedef_funcptr.subf) != 90:
raise RuntimeError("subf failed")
if typedef_funcptr.do_op_typedef_Integer(a,b,typedef_funcptr.addf) != 110:
raise RuntimeError("addf failed")
if typedef_funcptr.do_op_typedef_Integer(a,b,typedef_funcptr.subf) != 90:
raise RuntimeError("subf failed")
import typedef_inherit
a = typedef_inherit.Foo()
b = typedef_inherit.Bar()
x = typedef_inherit.do_blah(a)
if x != "Foo::blah":
print "Whoa! Bad return", x
x = typedef_inherit.do_blah(b)
if x != "Bar::blah":
print "Whoa! Bad return", x
c = typedef_inherit.Spam()
d = typedef_inherit.Grok()
x = typedef_inherit.do_blah2(c)
if x != "Spam::blah":
print "Whoa! Bad return", x
x = typedef_inherit.do_blah2(d)
if x != "Grok::blah":
print "Whoa! Bad return", x
import typedef_scope
b = typedef_scope.Bar()
x = b.test1(42, "hello")
if x != 42:
print "Failed!!"
x = b.test2(42, "hello")
if x != "hello":
print "Failed!!"
import typedef_typedef
b = typedef_typedef.B()
if b.getValue(123) != 1234:
raise Exception("Failed")
from typemap_arrays import *
if sumA(None) != 60:
raise RuntimeError, "Sum is wrong"
import typemap_delete
r = typemap_delete.Rect(123)
if r.val != 123:
raise RuntimeError
import typemap_documentation
f = typemap_documentation.Foo()
f.x = 55
b = typemap_documentation.Bar()
b.y = 44
if 55 != typemap_documentation.GrabVal(f):
raise RuntimeError("bad value")
try:
typemap_documentation.GrabVal(b)
raise RuntimeError("unexpected exception")
except TypeError:
pass
if 55 != typemap_documentation.GrabValFooBar(f):
raise RuntimeError("bad f value")
if 44 != typemap_documentation.GrabValFooBar(b):
raise RuntimeError("bad b value")
from typemap_namespace import *
if test1("hello") != "hello":
raise RuntimeError
if test2("hello") != "hello":
raise RuntimeError
import typemap_ns_using
if typemap_ns_using.spam(37) != 37:
raise RuntimeError
from typemap_out_optimal import *
cvar.XX_debug = False
x = XX_create()
import typemap_qualifier_strip
val = typemap_qualifier_strip.create_int(111)
if typemap_qualifier_strip.testA1(val) != 1234:
raise RuntimeError
if typemap_qualifier_strip.testA2(val) != 1234:
raise RuntimeError
if typemap_qualifier_strip.testA3(val) != 1234:
raise RuntimeError
if typemap_qualifier_strip.testA4(val) != 1234:
raise RuntimeError
if typemap_qualifier_strip.testB1(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testB2(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testB3(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testB4(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testC1(val) != 5678:
raise RuntimeError
if typemap_qualifier_strip.testC2(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testC3(val) != 5678:
raise RuntimeError
if typemap_qualifier_strip.testC4(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testD1(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testD2(val) != 3456:
raise RuntimeError
if typemap_qualifier_strip.testD3(val) != 111:
raise RuntimeError
if typemap_qualifier_strip.testD4(val) != 111:
raise RuntimeError
from typemap_template_typedef import *
def check(got, expected):
if got != expected:
raise RuntimeError("got: " + str(got) + " expected: " + str(expected))
x = XXXInt()
check(x.aa1(0), 0)
check(x.aa2(0), 55)
check(x.aa3(0), 0)
check(aa1(0), 0)
check(aa2(0), 0)
check(x.bb1(0), 0)
check(x.bb2(0), 66)
check(x.bb3(0), 0)
check(bb1(0), 0)
check(bb2(0), 0)
check(x.cc1(0), 0)
check(x.cc2(0), 77)
check(x.cc3(0), 77)
check(cc1(0), 0)
check(cc2(0), 0)
check(x.dd1(0), 0)
check(x.dd2(0), 88)
check(x.dd3(0), 0)
check(dd1(0), 0)
check(dd2(0), 0)
import typename
import types
f = typename.Foo()
b = typename.Bar()
x = typename.twoFoo(f)
if not isinstance(x, types.FloatType):
raise RuntimeError, "Wrong return type (FloatType) !"
y = typename.twoBar(b)
if not isinstance(y, types.IntType):
raise RuntimeError, "Wrong return type (IntType)!"
from types_directive import *
d1 = Time1(2001, 2, 3, 60)
# check that a Time1 instance is accepted where Date is expected
newDate = add(d1, 7)
if newDate.day != 10:
raise RuntimeError
d2 = Time2(1999, 8, 7, 60)
# check that a Time2 instance is accepted where Date is expected
newDate = add(d2, 7)
if newDate.day != 14:
raise RuntimeError
import sys
import unicode_strings
# The 'u' string prefix isn't valid in Python 3.0 - 3.2 and is redundant
# in 3.3+. Since this file is run through 2to3 before testing, though,
# mark this as a unicode string in 2.x so it'll become a str in 3.x.
test_string = u"h\udce9llo w\u00f6rld"
if sys.version_info[0:2] >= (3, 1):
if unicode_strings.non_utf8_c_str() != test_string:
raise ValueError("Test comparison mismatch")
if unicode_strings.non_utf8_std_string() != test_string:
raise ValueError("Test comparison mismatch")
def check(s1, s2):
if s1 != s2:
raise RuntimeError("{} != {}".format(s1, s2))
# Testing SWIG_PYTHON_2_UNICODE flag which allows unicode strings to be passed to C
if sys.version_info[0:2] < (3, 0):
check(unicode_strings.charstring("hello1"), "hello1")
check(unicode_strings.charstring(str(u"hello2")), "hello2")
check(unicode_strings.charstring(u"hello3"), "hello3")
check(unicode_strings.charstring(unicode("hello4")), "hello4")
unicode_strings.charstring(u"hell\xb05")
unicode_strings.charstring(u"hell\u00f66")
low_surrogate_string = u"\udcff"
try:
unicode_strings.instring(low_surrogate_string)
# Will succeed with Python 2
except TypeError, e:
# Python 3 will fail the PyUnicode_AsUTF8String conversion resulting in a TypeError.
# The real error is actually:
# UnicodeEncodeError: 'utf-8' codec can't encode character '\udcff' in position 0: surrogates not allowed
pass
# This is the union runtime testcase. It ensures that values within a
# union embedded within a struct can be set and read correctly.
import unions
import sys
import string
# Create new instances of SmallStruct and BigStruct for later use
small = unions.SmallStruct()
small.jill = 200
big = unions.BigStruct()
big.smallstruct = small
big.jack = 300
# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
# Ensure values in EmbeddedUnionTest are set correctly for each.
eut = unions.EmbeddedUnionTest()
# First check the SmallStruct in EmbeddedUnionTest
eut.number = 1
eut.uni.small = small
Jill1 = eut.uni.small.jill
if (Jill1 != 200):
print "Runtime test1 failed. eut.uni.small.jill=", Jill1
sys.exit(1)
Num1 = eut.number
if (Num1 != 1):
print "Runtime test2 failed. eut.number=", Num1
sys.exit(1)
# Secondly check the BigStruct in EmbeddedUnionTest
eut.number = 2
eut.uni.big = big
Jack1 = eut.uni.big.jack
if (Jack1 != 300):
print "Runtime test3 failed. eut.uni.big.jack=", Jack1
sys.exit(1)
Jill2 = eut.uni.big.smallstruct.jill
if (Jill2 != 200):
print "Runtime test4 failed. eut.uni.big.smallstruct.jill=", Jill2
sys.exit(1)
Num2 = eut.number
if (Num2 != 2):
print "Runtime test5 failed. eut.number=", Num2
sys.exit(1)
import using1
if using1.spam(37) != 37:
raise RuntimeError
import using2
if using2.spam(37) != 37:
raise RuntimeError
from using_composition import *
f = FooBar()
if f.blah(3) != 3:
raise RuntimeError, "FooBar::blah(int)"
if f.blah(3.5) != 3.5:
raise RuntimeError, "FooBar::blah(double)"
if f.blah("hello") != "hello":
raise RuntimeError, "FooBar::blah(char *)"
f = FooBar2()
if f.blah(3) != 3:
raise RuntimeError, "FooBar2::blah(int)"
if f.blah(3.5) != 3.5:
raise RuntimeError, "FooBar2::blah(double)"
if f.blah("hello") != "hello":
raise RuntimeError, "FooBar2::blah(char *)"
f = FooBar3()
if f.blah(3) != 3:
raise RuntimeError, "FooBar3::blah(int)"
if f.blah(3.5) != 3.5:
raise RuntimeError, "FooBar3::blah(double)"
if f.blah("hello") != "hello":
raise RuntimeError, "FooBar3::blah(char *)"
from using_extend import *
f = FooBar()
if f.blah(3) != 3:
raise RuntimeError, "blah(int)"
if f.blah(3.5) != 3.5:
raise RuntimeError, "blah(double)"
if f.blah("hello") != "hello":
raise RuntimeError, "blah(char *)"
if f.blah(3, 4) != 7:
raise RuntimeError, "blah(int,int)"
if f.blah(3.5, 7.5) != (3.5 + 7.5):
raise RuntimeError, "blah(double,double)"
if f.duh(3) != 3:
raise RuntimeError, "duh(int)"
from using_inherit import *
b = Bar()
if b.test(3) != 3:
raise RuntimeError, "Bar::test(int)"
if b.test(3.5) != 3.5:
raise RuntimeError, "Bar::test(double)"
b = Bar2()
if b.test(3) != 6:
raise RuntimeError, "Bar2::test(int)"
if b.test(3.5) != 7.0:
raise RuntimeError, "Bar2::test(double)"
b = Bar3()
if b.test(3) != 6:
raise RuntimeError, "Bar3::test(int)"
if b.test(3.5) != 7.0:
raise RuntimeError, "Bar3::test(double)"
b = Bar4()
if b.test(3) != 6:
raise RuntimeError, "Bar4::test(int)"
if b.test(3.5) != 7.0:
raise RuntimeError, "Bar4::test(double)"
b = Fred1()
if b.test(3) != 3:
raise RuntimeError, "Fred1::test(int)"
if b.test(3.5) != 7.0:
raise RuntimeError, "Fred1::test(double)"
b = Fred2()
if b.test(3) != 3:
raise RuntimeError, "Fred2::test(int)"
if b.test(3.5) != 7.0:
raise RuntimeError, "Fred2::test(double)"
from using_private import *
f = FooBar()
f.x = 3
if f.blah(4) != 4:
raise RuntimeError, "blah(int)"
if f.defaulted() != -1:
raise RuntimeError, "defaulted()"
if f.defaulted(222) != 222:
raise RuntimeError, "defaulted(222)"
from using_protected import *
f = FooBar()
f.x = 3
if f.blah(4) != 4:
raise RuntimeError, "blah(int)"
import varargs_overload
if varargs_overload.vararg_over1("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over1(2) != "2":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over2("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over2(2, 2.2) != "2 2.2":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over3("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over3(2, 2.2, "hey") != "2 2.2 hey":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over4("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over4(123) != "123":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over4("Hello", 123) != "Hello":
raise RuntimeError, "Failed"
# Same as above but non-vararg function declared first
if varargs_overload.vararg_over6("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over6(2) != "2":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over7("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over7(2, 2.2) != "2 2.2":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over8("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over8(2, 2.2, "hey") != "2 2.2 hey":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over9("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over9(123) != "123":
raise RuntimeError, "Failed"
if varargs_overload.vararg_over9("Hello", 123) != "Hello":
raise RuntimeError, "Failed"
import varargs
if varargs.test("Hello") != "Hello":
raise RuntimeError, "Failed"
f = varargs.Foo("Greetings")
if f.str != "Greetings":
raise RuntimeError, "Failed"
if f.test("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs.test_def("Hello", 1) != "Hello":
raise RuntimeError, "Failed"
if varargs.test_def("Hello") != "Hello":
raise RuntimeError, "Failed"
###
if varargs.test_plenty("Hello") != "Hello":
raise RuntimeError, "Failed"
if varargs.test_plenty("Hello", 1) != "Hello":
raise RuntimeError, "Failed"
if varargs.test_plenty("Hello", 1, 2) != "Hello":
raise RuntimeError, "Failed"
try:
varargs.test_plenty("Hello", 1, 2, 3)
raise RuntimeError
except TypeError:
pass
from virtual_derivation import *
#
# very innocent example
#
b = B(3)
if b.get_a() != b.get_b():
raise RuntimeError, "something is really wrong"
import virtual_poly
d = virtual_poly.NDouble(3.5)
i = virtual_poly.NInt(2)
#
# the copy methods return the right polymorphic types
#
dc = d.copy()
ic = i.copy()
if d.get() != dc.get():
raise RuntimeError
if i.get() != ic.get():
raise RuntimeError
virtual_poly.incr(ic)
if (i.get() + 1) != ic.get():
raise RuntimeError
dr = d.ref_this()
if d.get() != dr.get():
raise RuntimeError
#
# 'narrowing' also works
#
ddc = virtual_poly.NDouble_narrow(d.nnumber())
if d.get() != ddc.get():
raise RuntimeError
dic = virtual_poly.NInt_narrow(i.nnumber())
if i.get() != dic.get():
raise RuntimeError
import voidtest
voidtest.globalfunc()
f = voidtest.Foo()
f.memberfunc()
voidtest.Foo_staticmemberfunc()
def fvoid():
pass
if f.memberfunc() != fvoid():
raise RuntimeError
v1 = voidtest.vfunc1(f)
v2 = voidtest.vfunc2(f)
if v1 != v2:
raise RuntimeError
v3 = voidtest.vfunc3(v1)
if v3.this != f.this:
raise RuntimeError
v4 = voidtest.vfunc1(f)
if v4 != v1:
raise RuntimeError
v3.memberfunc()
import wrapmacro
a = 2
b = -1
wrapmacro.maximum(a, b)
wrapmacro.maximum(a / 7.0, -b * 256)
wrapmacro.GUINT16_SWAP_LE_BE_CONSTANT(1)
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'abstract_access'
include Abstract_access
begin
a = A.new
rescue TypeError
swig_assert(true, binding, 'A.new')
end
begin
b = B.new
rescue TypeError
swig_assert(true, binding, 'B.new')
end
begin
c = C.new
rescue TypeError
swig_assert(true, binding, 'C.new')
end
swig_assert( 'D.new' )
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'abstract_inherit_ok'
include Abstract_inherit_ok
#
# Shouldn't be able to instantiate Foo, because it declares
# a pure virtual function.
#
exceptionRaised = false
begin
Foo.new
rescue NameError
exceptionRaised = true
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Abstract_inherit_ok::Foo
exceptionRaised = true
ensure
swig_assert( "exceptionRaised", binding )
end
#
# This one's OK since we cleared it with a %feature("notabstract")
# declaration in the interface file.
#
exceptionRaised = false
begin
spam = Spam.new
raise RuntimeError unless spam.blah == 0
rescue NameError
exceptionRaised = true
ensure
swig_assert( "!exceptionRaised", binding )
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'abstract_inherit'
include Abstract_inherit
#
# Shouldn't be able to instantiate any of these classes
# since none of them implements the pure virtual function
# declared in the base class (Foo).
#
exceptionRaised = false
begin
Foo.new
rescue NameError
exceptionRaised = true
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Abstract_inherit::Foo
exceptionRaised = true
ensure
swig_assert( "exceptionRaised", binding )
end
exceptionRaised = false
begin
Bar.new
rescue NameError
exceptionRaised = true
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Abstract_inherit::Bar
exceptionRaised = true
ensure
swig_assert( "exceptionRaised", binding )
end
exceptionRaised = false
begin
Spam.new
rescue NameError
exceptionRaised = true
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Abstract_inherit::Spam
exceptionRaised = true
ensure
swig_assert( "exceptionRaised", binding )
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'abstract_signature'
include Abstract_signature
#
# Shouldn't be able to instantiate Abstract_foo, because it declares
# a pure virtual function.
#
exceptionRaised = false
begin
foo = Abstract_foo.new
begin
foo.meth(1)
rescue RuntimeError
# here we are using directors
exceptionRaised = true
end
rescue NameError
exceptionRaised = true
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Abstract_signature::Abstract_foo
exceptionRaised = true
ensure
swig_assert( "exceptionRaised", binding)
end
#
# Shouldn't be able to instantiate an Abstract_bar either, because it doesn't
# implement the pure virtual function with the correct signature.
#
exceptionRaised = false
begin
bar = Abstract_bar.new
begin
bar.meth(1)
rescue RuntimeError
# here we are using directors
exceptionRaised = true
end
rescue NameError
exceptionRaised = true
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Abstract_signature::Abstract_bar
exceptionRaised = true
ensure
swig_assert( "exceptionRaised", binding)
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'abstract_typedef2'
include Abstract_typedef2
swig_assert( 'a = A_UF.new' )
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'abstract_typedef'
include Abstract_typedef
swig_assert_each_line(<<'EOF', binding)
e = Engine.new
a = A.new
a.write(e)
EOF
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'abstract_virtual'
include Abstract_virtual
swig_assert('d = D.new')
swig_assert('e = E.new')
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'access_change'
#
# this test will currently fail, as it exposes functions that were
# made protected from public. swig limitation for now.
#
exit(0)
include Access_change
klass = BaseInt.new
public = ['PublicProtectedPublic1', 'PublicProtectedPublic2',
'PublicProtectedPublic3', 'PublicProtectedPublic4']
methods = (klass.public_methods - Object.methods).sort
pmethods = (klass.protected_methods - Object.methods).sort
swig_assert( methods == public,
" incorrect public methods for BaseInt\n" +
"#{methods.inspect} !=\n#{public.inspect}" )
klass = DerivedInt.new
public = ['PublicProtectedPublic3', 'PublicProtectedPublic4',
'WasProtected1', 'WasProtected2', 'WasProtected3', 'WasProtected4']
methods = (klass.public_methods - Object.methods).sort
swig_assert( methods == public,
" incorrect public methods for DerivedInt\n" +
"#{methods.inspect} !=\n#{public.inspect}" )
klass = BottomInt.new
public = ['PublicProtectedPublic1', 'PublicProtectedPublic2',
'PublicProtectedPublic3', 'PublicProtectedPublic4',
'WasProtected1', 'WasProtected2']
methods = (klass.public_methods - Object.methods).sort
swig_assert( methods == public,
" incorrect public methods for BottomInt\n" +
"#{methods.inspect} !=\n#{public.inspect}" )
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'add_link'
include Add_link
#
# This test currently fails due to swig
#
exit(0)
swig_assert( 'Foo.new' )
swig_assert( 'Foo.blah' )
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'aggregate'
include Aggregate
# Confirm that move() returns correct results under normal use
result = move(UP)
raise RuntimeError unless (result == UP)
result = move(DOWN)
raise RuntimeError unless (result == DOWN)
result = move(LEFT)
raise RuntimeError unless (result == LEFT)
result = move(RIGHT)
raise RuntimeError unless (result == RIGHT)
# Confirm that it raises an exception when the contract is violated
failed = false
begin
move(0)
rescue RuntimeError
failed = true
end
raise RuntimeError unless failed
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'anonymous_bitfield'
include Anonymous_bitfield
foo = Foo.new
{'x' => 4,
'y' => 3,
'f' => 1,
'z' => 8,
'seq' => 3 }.each do |m, v|
foo.send("#{m}=", v)
val = foo.send(m)
swig_assert("val == v", binding)
end
{'x' => (1 << 4),
'y' => (1 << 4),
'f' => (1 << 1),
'z' => (1 << 16),
'seq' => (1 << (4*8-6)) }.each do |m, v|
foo.send("#{m}=", v)
val = foo.send(m)
swig_assert("val != v", binding)
end
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'apply_signed_char'
include Apply_signed_char
['CharValFunction', 'CCharValFunction', 'CCharRefFunction'].each do |m|
[ 3, -3 ].each do |v|
val = send( m, v )
swig_assert( "v == val", binding, "for #{m}")
end
end
{ 'globalchar' => -109,
'globalconstchar' => -110,
}.each do |k,v|
val = Apply_signed_char.send( k )
swig_assert( "v == val", binding, "for #{k}")
end
a = DirectorTest.new
['CharValFunction', 'CCharValFunction', 'CCharRefFunction'].each do |m|
[ 3, -3 ].each do |v|
val = a.send( m, v )
swig_assert( "v == val", binding, "for DirectorTest.#{m}")
end
end
{ 'memberchar' => -111,
'memberconstchar' => -112,
}.each do |k,v|
val = a.send( k )
swig_assert( "v == val", binding, "for #{k}")
end
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'apply_strings'
include Apply_strings
begin
x = UcharPtr.new
swig_assert( fail, "UcharPtr should not be defined")
rescue NameError
end
ptr = 'a'
['UCharFunction', 'SCharFunction', 'CUCharFunction',
'CSCharFunction'].each do |m|
val = Apply_strings.send(m, ptr)
swig_assert( "val == ptr", binding )
end
['CharFunction', 'CCharFunction'].each do |m|
begin
val = Apply_strings.send(m, ptr)
swig_assert( false, nil, "Apply_strings.#{m} should raise TypeError" )
rescue TypeError
end
end
ptr = 'a'
foo = DirectorTest.new
['UCharFunction', 'SCharFunction', 'CUCharFunction',
'CSCharFunction'].each do |m|
val = foo.send(m, ptr)
swig_assert( "val == ptr", binding, "DirectorTest.#{m}" )
end
['CharFunction', 'CCharFunction'].each do |m|
begin
val = foo.send(m, ptr)
swig_assert( false, nil, "DirectorTest.#{m} should raise TypeError" )
rescue TypeError
end
end
# ary = Apply_strings.DigitsGlobalB
# { 0 => 'A',
# 1 => 'B',
# 2 => 'B' }.each do |k,v|
# val = ary[k]
# swig_assert( val == v, "Apply_strings.DigitsGlobalB[#{k}] #{val} != #{v}")
# end
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'argout'
include Argout
swig_assert_each_line(<<'EOF', binding)
t = new_intp
intp_assign(t, 5)
v = incp(t)
val = intp_value(t)
val == 6
t = new_intp
intp_assign(t, 5)
v = incr(t)
v == 5
val = intp_value(t)
val == 6
t = new_intp
intp_assign(t, 5)
v = inctr(t)
v == 5
val = intp_value(t)
val == 6
EOF
#
# @todo: how to use voidhandle and handle?
#
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'arrays_global'
Arrays_global.array_i = Arrays_global.array_const_i
#!/usr/bin/env ruby
#
# Test run of arrays.i
#
#
require 'swig_assert'
require 'arrays'
include Arrays
a = SimpleStruct.new
a.double_field = 2.0
b = SimpleStruct.new
b.double_field = 1.0
# @bug: this is broken
#
# c = [a,b]
# fn_taking_arrays(c)
#
# a = ArrayStruct.new
# a.array_i[0] = 0
#
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'array_member'
include Array_member
f = Foo.new
f.data = Array_member.global_data
0.upto(7) { |i|
unless get_value(f.data, i) == get_value(Array_member.global_data, i)
raise RuntimeError, "Bad array assignment"
end
}
0.upto(7) { |i|
set_value(f.data, i, -i)
}
Array_member.global_data = f.data
0.upto(7) { |i|
unless get_value(f.data, i) == get_value(Array_member.global_data, i)
raise RuntimeError, "Bad array assignment"
end
}
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'bools'
# bool constant check
if (Bools::Constbool != false)
print "Runtime test 1 failed\n"
exit 1
end
# bool variables check
if (Bools.bool1 != true)
print "Runtime test 2 failed\n"
exit 1
end
if (Bools.bool2 != false)
print "Runtime test 3 failed\n"
exit 1
end
if (Bools.value(Bools.pbool) != Bools.bool1)
print "Runtime test 4 failed\n"
exit 1
end
if (Bools.value(Bools.rbool) != Bools.bool2)
print "Runtime test 5 failed\n"
exit 1
end
if (Bools.value(Bools.const_pbool) != Bools.bool1)
print "Runtime test 6 failed\n"
exit 1
end
if (Bools.const_rbool != Bools.bool2)
print "Runtime test 7 failed\n"
exit 1
end
# bool functions check
if (Bools.bo(false) != false)
print "Runtime test 8 failed\n"
exit 1
end
if (Bools.bo(true) != true)
print "Runtime test 9 failed\n"
exit 1
end
if (Bools.value(Bools.rbo(Bools.rbool)) != Bools.value(Bools.rbool))
print "Runtime test 10 failed\n"
exit 1
end
if (Bools.value(Bools.pbo(Bools.pbool)) != Bools.value(Bools.pbool))
print "Runtime test 11 failed\n"
exit 1
end
if (Bools.const_rbo(Bools.const_rbool) != Bools.const_rbool)
print "Runtime test 12 failed\n"
exit 1
end
if (Bools.value(Bools.const_pbo(Bools.const_pbool)) != Bools.value(Bools.const_pbool))
print "Runtime test 13 failed\n"
exit 1
end
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'casts'
include Casts
swig_assert( B.ancestors.include?(A), 'B.ancestors.include? A' )
a = A.new
a.hello
b = B.new
b.hello
swig_assert( b.kind_of?( A ), ' B.kind_of? A' )
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'cast_operator'
include Cast_operator
a = A.new
t = a.tochar
swig_assert( t == 'hi' )
#!/usr/bin/env ruby
#Encoding: ASCII-8BIT
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'char_constant'
if Char_constant::CHAR_CONSTANT != 'x'
raise RuntimeError, "Invalid value for CHAR_CONSTANT."
end
if Char_constant::STRING_CONSTANT != 'xyzzy'
raise RuntimeError, "Invalid value for STRING_CONSTANT."
end
if Char_constant::ESC_CONST != "\001"
raise RuntimeError, "Invalid value for ESC_CONST."
end
if Char_constant::NULL_CONST != "\000"
raise RuntimeError, "Invalid value for NULL_CONST."
end
if Char_constant::SPECIALCHAR != "\341" #'�'
raise RuntimeError, "Invalid value for SPECIALCHAR."
end
#!/usr/bin/env ruby
#
# This script allows you to compare the tests in the current directory
# (Ruby) against the tests of other languages to see which ones are missing
#
#
#
#
#
ignore = ['ruby','std','typemaps']
curr = Dir.pwd.sub(/.*\//, '')
langs = Dir.glob('../*').select { |x| File.directory?("../#{x}") }
langs.map! { |x| x.sub(/^\.\.\/*/, '') }
langs -= ignore
# Add generic test directory, too
langs << ''
testsB = Dir.glob("*runme*").map { |x| x.sub(/\.\w+$/, '') }
all_tests = []
langs.each do |lang|
testsA = Dir.glob("../#{lang}/*runme*")
testsA.map! { |x| x.sub(/.*\/(\w+)\.\w+$/, '\1') }
testsA.delete_if { |x| x =~ /~$/ } # ignore emacs backups
diff = testsA - testsB
unless diff.empty?
puts '-'*70
title = !lang.empty? ? "#{lang[0,1].upcase}#{lang[1..-1]}" : 'Generic'
title = "Missing #{title} tests"
puts title
puts '='*title.size
puts diff.join(', ')
all_tests += diff
end
end
all_tests.uniq!
puts '-'*70
puts 'All missing tests'
puts '================='
puts all_tests.join(', ')
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'class_ignore'
a = Class_ignore::Bar.new
# Even though we didn't wrap the Foo class, this call
# to do_blah() should succeed.
if Class_ignore.do_blah(a) != "Bar::blah"
raise RuntimeError
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'constover'
error = 0
p = Constover.test("test")
if p != "test"
puts "test failed!"
error = 1
end
p = Constover.test_pconst("test")
if p != "test_pconst"
puts "test_pconst failed!"
error = 1
end
f = Constover::Foo.new
p = f.test("test")
if p != "test"
print "member-test failed!"
error = 1
end
p = f.test_pconst("test")
if p != "test_pconst"
print "member-test_pconst failed!"
error = 1
end
p = f.test_constm("test")
if p != "test_constmethod"
print "member-test_constm failed!"
error = 1
end
p = f.test_pconstm("test")
if p != "test_pconstmethod"
print "member-test_pconstm failed!"
error = 1
end
exit(error)
#!/usr/bin/env ruby
#
#
require 'swig_assert'
require 'const_const'
include Const_const
swig_assert_each_line <<EOF
foo(1) # 1 is unused
EOF
require 'swig_assert'
require 'cpp11_hash_tables'
[Cpp11_hash_tables::MapIntInt.new({1=>7}),
Cpp11_hash_tables::MultiMapIntInt.new({1=>7}),
Cpp11_hash_tables::UnorderedMapIntInt.new({1=>7}),
Cpp11_hash_tables::UnorderedMultiMapIntInt.new({1=>7})].each{|x|
swig_assert_equal("x.find_all{|e,k| e == 1}", "[[1,7]]", binding)
swig_assert_equal("x[1]", "7", binding)
swig_assert_equal("x[2]", "nil", binding)
x[2] = 9
swig_assert_equal("x[2]", "9", binding)
x.delete(2)
swig_assert_equal("x[2]", "nil", binding)
swig_assert_equal("x.empty?", "false", binding)
x.delete(1)
swig_assert_equal("x.empty?", "true", binding)
swig_assert_equal("x.include?(1)", "false", binding)
}
[Cpp11_hash_tables::MultiMapIntInt.new({1=>7}),
Cpp11_hash_tables::UnorderedMultiMapIntInt.new({1=>7})].each{|x|
x[1] = 9
swig_assert_equal("x[1].sort", "[7,9]", binding)
}
[Cpp11_hash_tables::SetInt.new([1]),
Cpp11_hash_tables::MultiSetInt.new([1]),
Cpp11_hash_tables::UnorderedSetInt.new([1]),
Cpp11_hash_tables::UnorderedMultiSetInt.new([1])].each{|x|
swig_assert_equal("x.find_all{|e| e == 1}", "[1]", binding)
swig_assert_equal("x.include?(1)", "true", binding)
swig_assert_equal("x.include?(2)", "false", binding)
x << 2
swig_assert_equal("x.include?(2)", "true", binding)
x.erase(2)
swig_assert_equal("x.empty?", "false", binding)
x.erase(1)
swig_assert_equal("x.empty?", "true", binding)
}
[Cpp11_hash_tables::MultiSetInt.new([1]),
Cpp11_hash_tables::UnorderedMultiSetInt.new([1])].each{|x|
x << 1
swig_assert_equal("x.count(1)", "2", binding)
}
[Cpp11_hash_tables::MapIntInt,
Cpp11_hash_tables::MultiMapIntInt,
Cpp11_hash_tables::UnorderedMapIntInt,
Cpp11_hash_tables::UnorderedMultiMapIntInt,
Cpp11_hash_tables::SetInt,
Cpp11_hash_tables::MultiSetInt,
Cpp11_hash_tables::UnorderedSetInt,
Cpp11_hash_tables::UnorderedMultiSetInt].each{|k|
swig_assert("k.include?(Enumerable)", binding)
}
require "swig_assert"
require "cpp11_shared_ptr_const"
include Cpp11_shared_ptr_const
swig_assert_equal_simple(1, foo( Foo.new(1) ).get_m )
swig_assert_equal_simple(7, const_foo( Foo.new(7) ).get_m )
swig_assert_equal_simple(7, foo_vec( Foo.new(7) )[0].get_m )
swig_assert_equal_simple(8, const_foo_vec( Foo.new(8) )[0].get_m )
require "cpp11_shared_ptr_nullptr_in_containers"
include Cpp11_shared_ptr_nullptr_in_containers
a = ret_vec_c_shared_ptr()
raise unless a[0].get_m == 0
raise unless a[1] == nil
raise unless a[2].get_m == 2
a = ret_arg_vec([C.new(7), nil, C.new(9)])
raise unless a[0].get_m == 7
raise unless a[1] == nil
raise unless a[2].get_m == 9
raise unless is_last_null([C.new(7), C.new(8), nil])
raise if is_last_null([C.new(7), C.new(8)])
require 'swig_assert'
require 'cpp11_shared_ptr_upcast'
include Cpp11_shared_ptr_upcast
# non-overloaded
swig_assert_equal_simple( 7, derived_num1(Derived.new(7)) )
swig_assert_equal_simple( 7, derived_num2([Derived.new(7)]) )
swig_assert_equal_simple( 7, derived_num3({0 => Derived.new(7)}) )
swig_assert_equal_simple(-1, base_num1(Derived.new(7)) )
swig_assert_equal_simple(-1, base_num2([Derived.new(7)]) )
swig_assert_equal_simple(-1, base_num3({0 => Derived.new(7)}) )
swig_assert_equal_simple( 999, derived_num1(nil) )
swig_assert_equal_simple( 999, derived_num2([nil]) )
swig_assert_equal_simple( 999, derived_num3({0 => nil}) )
swig_assert_equal_simple( 999, base_num1(nil) )
swig_assert_equal_simple( 999, base_num2([nil]) )
swig_assert_equal_simple( 999, base_num3({0 => nil}) )
# overloaded
swig_assert_equal_simple( 7, derived_num(Derived.new(7)) )
swig_assert_equal_simple( 7, derived_num([Derived.new(7)]) )
swig_assert_equal_simple( 7, derived_num({0 => Derived.new(7)}) )
swig_assert_equal_simple(-1, base_num(Derived.new(7)) )
swig_assert_equal_simple(-1, base_num([Derived.new(7)]) )
swig_assert_equal_simple(-1, base_num({0 => Derived.new(7)}) )
# ptr to shared_ptr
swig_assert_equal_simple( 7, derived2_num1(Derived2.new(7)) )
swig_assert_equal_simple( 7, derived2_num2([Derived2.new(7)]) )
swig_assert_equal_simple( 7, derived2_num3({0 => Derived2.new(7)}) )
swig_assert_equal_simple( -1, base2_num1(Derived2.new(7)) )
begin
# Upcast for pointers to shared_ptr in this generic framework has not been implemented
swig_assert_equal_simple( -1, base2_num2([Derived2.new(7)]) )
raise RuntimeError, "Failed to catch TypeError"
rescue TypeError
end
begin
# Upcast for pointers to shared_ptr in this generic framework has not been implemented
swig_assert_equal_simple( -1, base2_num3({0 => Derived2.new(7)}) )
raise RuntimeError, "Failed to catch TypeError"
rescue TypeError
end
swig_assert_equal_simple( 888, derived2_num1(nil) )
swig_assert_equal_simple( 999, derived2_num2([nil]) ) # although 888 would be more consistent
swig_assert_equal_simple( 999, derived2_num3({0 => nil}) ) # although 888 would be more consistent
swig_assert_equal_simple( 888, base2_num1(nil) )
swig_assert_equal_simple( 999, base2_num2([nil]) ) # although 888 would be more consistent
swig_assert_equal_simple( 999, base2_num3({0 => nil}) ) # although 888 would be more consistent
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'cpp11_std_array'
include Cpp11_std_array
def failed(a, b, msg)
raise RuntimeError, "#{msg} #{a} #{b}"
end
def compare_sequences(a, b)
if a.size != b.size
failed(a, b, "different sizes")
end
for i in 0..a.size-1
failed(a, b, "elements are different:") if a[i] != b[i]
end
end
def compare_containers(rubyarray, swigarray)
compare_sequences(rubyarray, swigarray)
end
def setslice_exception(swigarray, newval)
begin
swigarray[0..swigarray.size] = newval
raise RuntimeError, "swigarray[] = #{newval} missed set exception for swigarray: #{swigarray}"
rescue ArgumentError => e
# print "exception: #{e}"
end
end
# Check std::array has similar behaviour to a Ruby array
# except it is not resizable
ps = [0, 1, 2, 3, 4, 5]
ai = ArrayInt6.new(ps)
compare_containers(ps, ai)
# slices
compare_containers(ps[0..5], ai[0..5])
compare_containers(ps[-6..-1], ai[-6..-1])
compare_containers(ps[0..10], ai[0..10])
# Reverse (.reverse is not provided)
rev = []
ai.reverse_each { |i| rev.push i }
compare_containers(ps.reverse, rev)
# Modify content
for i in 0..ps.size-1
ps[i] = ps[i] * 10
ai[i] = ai[i] * 10
end
compare_containers(ps, ai)
# Empty
ai = ArrayInt6.new()
compare_containers([0, 0, 0, 0, 0, 0], ai)
# Set slice
newvals = [10, 20, 30, 40, 50, 60]
ai[0, 6] = newvals
compare_containers(ai, newvals)
ai[-6, 6] = newvals
compare_containers(ai, newvals)
setslice_exception(ai, [1, 2, 3, 4, 5, 6, 7])
setslice_exception(ai, [1, 2, 3, 4, 5])
setslice_exception(ai, [1, 2, 3, 4])
setslice_exception(ai, [1, 2, 3])
setslice_exception(ai, [1, 2])
setslice_exception(ai, [1])
setslice_exception(ai, [])
# Check return
compare_containers(arrayOutVal(), [-2, -1, 0, 0, 1, 2])
compare_containers(arrayOutConstRef(), [-2, -1, 0, 0, 1, 2])
compare_containers(arrayOutRef(), [-2, -1, 0, 0, 1, 2])
compare_containers(arrayOutPtr(), [-2, -1, 0, 0, 1, 2])
# Check passing arguments
ai = arrayInVal([9, 8, 7, 6, 5, 4])
compare_containers(ai, [90, 80, 70, 60, 50, 40])
ai = arrayInConstRef([9, 8, 7, 6, 5, 4])
compare_containers(ai, [90, 80, 70, 60, 50, 40])
ai = ArrayInt6.new([9, 8, 7, 6, 5, 4])
arrayInRef(ai)
compare_containers(ai, [90, 80, 70, 60, 50, 40])
ai = ArrayInt6.new([9, 8, 7, 6, 5, 4])
arrayInPtr(ai)
compare_containers(ai, [90, 80, 70, 60, 50, 40])
# indexing
ai = ArrayInt6.new([9, 8, 7, 6, 5, 4])
swig_assert_equal(ai[0], 9, binding)
swig_assert_equal(ai[5], 4, binding)
swig_assert_equal(ai[6], nil, binding)
swig_assert_equal(ai[-7], nil, binding)
# fill
ai.fill(111)
compare_containers(ai, [111, 111, 111, 111, 111, 111])
# various
ai = ArrayInt6.new([9, 8, 7, 6, 5, 4])
swig_assert(ai.include? 9)
swig_assert(!ai.include?(99))
swig_assert(ai.kind_of? ArrayInt6)
swig_assert(ai.find {|x| x == 6 } == 6)
swig_assert(ai.find {|x| x == 66 } == nil)
swig_assert(ai.respond_to?(:each))
swig_assert(ai.respond_to?(:each_with_index))
ai = [0, 10, 20, 30, 40, 50]
ai.each_with_index { |e,i| swig_assert(e/10 == i) }
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'cpp11_strongly_typed_enumerations'
include Cpp11_strongly_typed_enumerations
def enumCheck(actual, expected)
raise RuntimeError,"Enum value mismatch. Expected #{expected} Actual: #{actual}" if actual != expected
return expected + 1
end
val = 0
val = enumCheck(Enum1_Val1, val)
val = enumCheck(Enum1_Val2, val)
val = enumCheck(Enum1_Val3, 13)
val = enumCheck(Enum1_Val4, val)
val = enumCheck(Enum1_Val5a, 13)
val = enumCheck(Enum1_Val6a, val)
val = 0
val = enumCheck(Enum2_Val1, val)
val = enumCheck(Enum2_Val2, val)
val = enumCheck(Enum2_Val3, 23)
val = enumCheck(Enum2_Val4, val)
val = enumCheck(Enum2_Val5b, 23)
val = enumCheck(Enum2_Val6b, val)
val = 0
val = enumCheck(Val1, val)
val = enumCheck(Val2, val)
val = enumCheck(Val3, 43)
val = enumCheck(Val4, val)
val = 0
val = enumCheck(Enum5_Val1, val)
val = enumCheck(Enum5_Val2, val)
val = enumCheck(Enum5_Val3, 53)
val = enumCheck(Enum5_Val4, val)
val = 0
val = enumCheck(Enum6_Val1, val)
val = enumCheck(Enum6_Val2, val)
val = enumCheck(Enum6_Val3, 63)
val = enumCheck(Enum6_Val4, val)
val = 0
val = enumCheck(Enum7td_Val1, val)
val = enumCheck(Enum7td_Val2, val)
val = enumCheck(Enum7td_Val3, 73)
val = enumCheck(Enum7td_Val4, val)
val = 0
val = enumCheck(Enum8_Val1, val)
val = enumCheck(Enum8_Val2, val)
val = enumCheck(Enum8_Val3, 83)
val = enumCheck(Enum8_Val4, val)
val = 0
val = enumCheck(Enum10_Val1, val)
val = enumCheck(Enum10_Val2, val)
val = enumCheck(Enum10_Val3, 103)
val = enumCheck(Enum10_Val4, val)
val = 0
val = enumCheck(Class1::Enum12_Val1, 1121)
val = enumCheck(Class1::Enum12_Val2, 1122)
val = enumCheck(Class1::Enum12_Val3, val)
val = enumCheck(Class1::Enum12_Val4, val)
val = enumCheck(Class1::Enum12_Val5c, 1121)
val = enumCheck(Class1::Enum12_Val6c, val)
val = 0
val = enumCheck(Class1::Val1, 1131)
val = enumCheck(Class1::Val2, 1132)
val = enumCheck(Class1::Val3, val)
val = enumCheck(Class1::Val4, val)
val = enumCheck(Class1::Val5d, 1131)
val = enumCheck(Class1::Val6d, val)
val = 0
val = enumCheck(Class1::Enum14_Val1, 1141)
val = enumCheck(Class1::Enum14_Val2, 1142)
val = enumCheck(Class1::Enum14_Val3, val)
val = enumCheck(Class1::Enum14_Val4, val)
val = enumCheck(Class1::Enum14_Val5e, 1141)
val = enumCheck(Class1::Enum14_Val6e, val)
# Requires nested class support to work
#val = 0
#val = enumCheck(Class1::Struct1.Enum12_Val1, 3121)
#val = enumCheck(Class1::Struct1.Enum12_Val2, 3122)
#val = enumCheck(Class1::Struct1.Enum12_Val3, val)
#val = enumCheck(Class1::Struct1.Enum12_Val4, val)
#val = enumCheck(Class1::Struct1.Enum12_Val5f, 3121)
#val = enumCheck(Class1::Struct1.Enum12_Val6f, val)
#
#val = 0
#val = enumCheck(Class1::Struct1.Val1, 3131)
#val = enumCheck(Class1::Struct1.Val2, 3132)
#val = enumCheck(Class1::Struct1.Val3, val)
#val = enumCheck(Class1::Struct1.Val4, val)
#
#val = 0
#val = enumCheck(Class1::Struct1.Enum14_Val1, 3141)
#val = enumCheck(Class1::Struct1.Enum14_Val2, 3142)
#val = enumCheck(Class1::Struct1.Enum14_Val3, val)
#val = enumCheck(Class1::Struct1.Enum14_Val4, val)
#val = enumCheck(Class1::Struct1.Enum14_Val5g, 3141)
#val = enumCheck(Class1::Struct1.Enum14_Val6g, val)
val = 0
val = enumCheck(Class2::Enum12_Val1, 2121)
val = enumCheck(Class2::Enum12_Val2, 2122)
val = enumCheck(Class2::Enum12_Val3, val)
val = enumCheck(Class2::Enum12_Val4, val)
val = enumCheck(Class2::Enum12_Val5h, 2121)
val = enumCheck(Class2::Enum12_Val6h, val)
val = 0
val = enumCheck(Class2::Val1, 2131)
val = enumCheck(Class2::Val2, 2132)
val = enumCheck(Class2::Val3, val)
val = enumCheck(Class2::Val4, val)
val = enumCheck(Class2::Val5i, 2131)
val = enumCheck(Class2::Val6i, val)
val = 0
val = enumCheck(Class2::Enum14_Val1, 2141)
val = enumCheck(Class2::Enum14_Val2, 2142)
val = enumCheck(Class2::Enum14_Val3, val)
val = enumCheck(Class2::Enum14_Val4, val)
val = enumCheck(Class2::Enum14_Val5j, 2141)
val = enumCheck(Class2::Enum14_Val6j, val)
# Requires nested class support to work
#val = 0
#val = enumCheck(Class2::Struct1.Enum12_Val1, 4121)
#val = enumCheck(Class2::Struct1.Enum12_Val2, 4122)
#val = enumCheck(Class2::Struct1.Enum12_Val3, val)
#val = enumCheck(Class2::Struct1.Enum12_Val4, val)
#val = enumCheck(Class2::Struct1.Enum12_Val5k, 4121)
#val = enumCheck(Class2::Struct1.Enum12_Val6k, val)
#
#val = 0
#val = enumCheck(Class2::Struct1.Val1, 4131)
#val = enumCheck(Class2::Struct1.Val2, 4132)
#val = enumCheck(Class2::Struct1.Val3, val)
#val = enumCheck(Class2::Struct1.Val4, val)
#val = enumCheck(Class2::Struct1.Val5l, 4131)
#val = enumCheck(Class2::Struct1.Val6l, val)
#
#val = 0
#val = enumCheck(Class2::Struct1.Enum14_Val1, 4141)
#val = enumCheck(Class2::Struct1.Enum14_Val2, 4142)
#val = enumCheck(Class2::Struct1.Enum14_Val3, val)
#val = enumCheck(Class2::Struct1.Enum14_Val4, val)
#val = enumCheck(Class2::Struct1.Enum14_Val5m, 4141)
#val = enumCheck(Class2::Struct1.Enum14_Val6m, val)
class1 = Class1.new
enumCheck(class1.class1Test1(Enum1_Val5a), 13)
enumCheck(class1.class1Test2(Class1::Enum12_Val5c), 1121)
#enumCheck(class1.class1Test3(Class1::Struct1.Enum12_Val5f), 3121)
enumCheck(globalTest1(Enum1_Val5a), 13)
enumCheck(globalTest2(Class1::Enum12_Val5c), 1121)
#enumCheck(globalTest3(Class1::Struct1.Enum12_Val5f), 3121)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
# Note: This example assumes that namespaces are flattened
require 'cpp_namespace'
n = Cpp_namespace.fact(4)
if n != 24
raise "Bad return value!"
end
if Cpp_namespace.Foo != 42
raise "Bad variable value!"
end
t = Cpp_namespace::Test.new
if t.method() != "Test::method"
raise "Bad method return value!"
end
if Cpp_namespace.do_method(t) != "Test::method"
raise "Bad return value!"
end
if Cpp_namespace.do_method2(t) != "Test::method"
raise "Bad return value!"
end
Cpp_namespace.weird("hello", 4)
t2 = Cpp_namespace::Test2.new
t3 = Cpp_namespace::Test3.new
t4 = Cpp_namespace::Test4.new
t5 = Cpp_namespace::Test5.new
if Cpp_namespace.foo3(42) != 42
raise "Bad return value!"
end
if Cpp_namespace.do_method3(t2, 40) != "Test2::method"
raise "Bad return value!"
end
if Cpp_namespace.do_method3(t3, 40) != "Test3::method"
raise "Bad return value!"
end
if Cpp_namespace.do_method3(t4, 40) != "Test4::method"
raise "Bad return value!"
end
if Cpp_namespace.do_method3(t5, 40) != "Test5::method"
raise "Bad return value!"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'default_constructor'
include Default_constructor
# Ruby 1.6 raises NameError if you try to call Class.new where no constructor
# is defined; Ruby 1.7 changed this to NoMethodError
NoConstructorError = Kernel.const_defined?("NoMethodError") ? NoMethodError : NameError
# This should be no problem
a = A.new
# Nor should this
aa = AA.new
# The default constructor for B is private, so this should raise an exception
begin
b = B.new
rescue ArgumentError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::BB
exceptionRaised = true
end
# The two-argument constructor for B should work
b = B.new(3, 4)
# BB shouldn't inherit B's default constructor, so this should raise an exception
begin
bb = BB.new
puts "Whoa. new BB created."
rescue NoConstructorError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::BB
exceptionRaised = true
end
# C's constructor is protected, so this should raise an exception
begin
c = C.new
print "Whoa. new C created."
rescue NoConstructorError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::C
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::C
# pass
end
# CC gets a default constructor, so no problem here
cc = CC.new
# D's constructor is private, so this should fail
begin
d = D.new
puts "Whoa. new D created"
rescue NoConstructorError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::D
# pass
end
# DD shouldn't get a default constructor, so this should fail
begin
dd = DD.new
puts "Whoa. new DD created"
rescue NoConstructorError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::DD
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::D
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::DD
# pass
end
# AD shouldn't get a default constructor, so this should fail
begin
ad = AD.new
puts "Whoa. new AD created"
rescue NoConstructorError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::AD
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::AD
# pass
end
# Both of the arguments to E's constructor have default values,
# so this should be fine.
e = E.new
# EE should get a default constructor
ee = EE.new
# EB should not get a default constructor (because B doesn't have one)
begin
eb = EB.new
puts "Whoa. new EB created"
rescue NoConstructorError
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::EB
# pass
rescue TypeError
# In Ruby 1.8 the exception raised is:
# TypeError: allocator undefined for Default_constructor::EB
# pass
end
# This should work fine
f = F.new
# This should work fine
g = G.new
# This should work fine
gg = GG.new
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_abstract'
class MyFoo < Director_abstract::Foo
def ping
"MyFoo::ping()"
end
end
a = MyFoo.new
if a.ping != "MyFoo::ping()"
raise RuntimeError, a.ping
end
if a.pong != "Foo::pong();MyFoo::ping()"
raise RuntimeError, a.pong
end
class MyExample1 < Director_abstract::Example1
def color(r,g,b)
r
end
end
#m1 = MyExample1.new
#
#if m1.color(1,2,3) != 1
# raise RuntimeError, m1.color
#end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_basic'
class MyFoo < Director_basic::Foo
def ping
"MyFoo::ping()"
end
end
a = MyFoo.new
raise RuntimeError if a.ping != "MyFoo::ping()"
raise RuntimeError if a.pong != "Foo::pong();MyFoo::ping()"
b = Director_basic::Foo.new
raise RuntimeError if b.ping != "Foo::ping()"
raise RuntimeError if b.pong != "Foo::pong();Foo::ping()"
a = Director_basic::MyClass.new
a = Director_basic::MyClassT_i.new
a = Director_basic::MyClass.new 1
a = Director_basic::MyClassT_i.new 1
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_constructor'
include Director_constructor
class Test < Foo
def initialize(i)
super(i)
end
def doubleit()
self.a = (self.a * 2)
end
def test
3
end
end
a = Test.new(5) #dies here
raise RuntimeError if a.getit != 5
raise RuntimeError if a.do_test != 3
a.doubleit
raise RuntimeError if a.getit != 10
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_default'
a = Director_default::Foo.new 1
a = Director_default::Foo.new
a.Msg
a.Msg "hello"
a.GetMsg
a.GetMsg "hello"
a = Director_default::Bar.new 1
a = Director_default::Bar.new
a.Msg
a.Msg "hello"
a.GetMsg
a.GetMsg "hello"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_detect'
class MyBar < Director_detect::Bar
def initialize(v)
@val = v
end
def get_value
@val = @val + 1
end
def get_class
@val = @val + 1
Director_detect::A
end
def just_do_it
@val = @val + 1
end
def clone
MyBar.new(@val)
end
def val
@val
end
end
b = MyBar.new(2)
f = b
v = f.get_value
a = f.get_class
f.just_do_it
c = b.clone
vc = c.get_value
raise RuntimeError if (v != 3) || (b.val != 5) || (vc != 6)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_exception'
include Director_exception
class MyFoo < Foo
def ping
raise NotImplementedError, "MyFoo::ping() EXCEPTION"
end
end
class MyFoo2 < Foo
def ping
nil # error: should return a string
end
end
class MyFoo3 < Foo
def ping
5 # error: should return a string
end
end
ok = false
a = MyFoo.new
b = launder(a)
begin
b.pong
rescue NotImplementedError
ok = true
end
raise RuntimeError unless ok
ok = false
a = MyFoo2.new
b = launder(a)
begin
b.pong
rescue TypeError
ok = true
end
a = MyFoo3.new
b = launder(a)
begin
b.pong
rescue TypeError
ok = true
end
raise RuntimeError unless ok
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_frob'
foo = Director_frob::Bravo.new;
s = foo.abs_method;
raise RuntimeError if s != "Bravo::abs_method()"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_nested'
NoProtectedError = Kernel.const_defined?("NoMethodError") ? NoMethodError : NameError
class A < Director_nested::FooBar_int
protected
def do_step
"A::do_step;"
end
def get_value
"A::get_value"
end
end
a = A.new
begin
a.do_advance
rescue NoProtectedError
end
raise RuntimeError if a.step != "Bar::step;Foo::advance;Bar::do_advance;A::do_step;"
class B < Director_nested::FooBar_int
protected
def do_advance
"B::do_advance;" + do_step
end
def do_step
"B::do_step;"
end
def get_value
"B::get_value"
end
end
b = B.new
raise RuntimeError if b.step != "Bar::step;Foo::advance;B::do_advance;B::do_step;"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_protected'
NoProtectedError = Kernel.const_defined?("NoMethodError") ? NoMethodError : NameError
class FooBar < Director_protected::Bar
protected
def ping
"FooBar::ping();"
end
end
class Hello < FooBar
public
def pang
ping
end
end
b = Director_protected::Bar.new
fb = FooBar.new
p = 0
begin
b.ping
p = 1
rescue NoProtectedError
end
h = Hello.new
raise RuntimeError if p == 1
raise RuntimeError if b.pong != "Bar::pong();Foo::pong();Bar::ping();"
raise RuntimeError if fb.pong != "Bar::pong();Foo::pong();FooBar::ping();"
raise RuntimeError if h.pang != "FooBar::ping();"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'director_smartptr'
include Director_smartptr
class Director_smartptr_MyBarFoo < Foo
def ping()
return "director_smartptr_MyBarFoo.ping()"
end
def pong()
return "director_smartptr_MyBarFoo.pong();" + ping()
end
def upcall(fooBarPtr)
return "override;" + fooBarPtr.FooBarDo()
end
def makeFoo()
return Foo.new()
end
end
class Director_smartptr_MyBarFooDerived < FooDerived
def ping()
return "director_smartptr_MyBarFooDerived.ping()"
end
def pong()
return "director_smartptr_MyBarFooDerived.pong();" + ping()
end
def upcall(fooBarPtr)
return "overrideDerived;" + fooBarPtr.FooBarDo()
end
def makeFoo()
return Foo.new()
end
end
def check(got, expected)
if (got != expected)
raise RuntimeError, "Failed, got: #{got} expected: #{expected}"
end
end
fooBar = Director_smartptr::FooBar.new()
myBarFoo = Director_smartptr_MyBarFoo.new()
check(myBarFoo.ping(), "director_smartptr_MyBarFoo.ping()")
check(Foo.callPong(myBarFoo), "director_smartptr_MyBarFoo.pong();director_smartptr_MyBarFoo.ping()")
check(Foo.callUpcall(myBarFoo, fooBar), "override;Bar::Foo2::Foo2Bar()")
myFoo = myBarFoo.makeFoo()
check(myFoo.pong(), "Foo::pong();Foo::ping()")
check(Foo.callPong(myFoo), "Foo::pong();Foo::ping()")
check(myFoo.upcall(FooBar.new()), "Bar::Foo2::Foo2Bar()")
myFoo2 = Foo.new().makeFoo()
check(myFoo2.pong(), "Foo::pong();Foo::ping()")
check(Foo.callPong(myFoo2), "Foo::pong();Foo::ping()")
check(myFoo2.upcall(FooBar.new()), "Bar::Foo2::Foo2Bar()")
myBarFooDerived = Director_smartptr_MyBarFooDerived.new()
check(myBarFooDerived.ping(), "director_smartptr_MyBarFooDerived.ping()")
check(FooDerived.callPong(myBarFooDerived), "director_smartptr_MyBarFooDerived.pong();director_smartptr_MyBarFooDerived.ping()")
check(FooDerived.callUpcall(myBarFooDerived, fooBar), "overrideDerived;Bar::Foo2::Foo2Bar()")
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_string'
class B < Director_string::A
def initialize(some_string)
super(some_string)
end
end
b = B.new("hello")
b.get_first
b.get(0)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_unroll'
class MyFoo < Director_unroll::Foo
def ping
"MyFoo::ping()"
end
end
a = MyFoo.new
b = Director_unroll::Bar.new
b.set(a)
c = b.get()
raise RuntimeError if a != c
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'director_wombat'
include Director_wombat
# Test base class functionality
barObj = Bar.new
# Bar#meth should return a Foo_integers instance
fooIntsObj = barObj.meth
raise RuntimeError unless fooIntsObj.instance_of?(Foo_integers)
# Foo_integers#meth(n) should return n
raise RuntimeError if fooIntsObj.meth(42) != 42
#
# Now subclass Foo_integers, but override its virtual method
# meth(n) so that it returns the number plus one.
#
class MyFooInts < Foo_integers
def meth(n)
n + 1
end
end
#
# Subclass Bar and override its virtual method meth()
# so that it returns a new MyFooInts instance instead of
# a Foo_integers instance.
#
class MyBar < Bar
def meth
MyFooInts.new
end
end
#
# Now repeat previous tests:
#
# Create a MyBar instance...
#
barObj = MyBar.new
# MyBar#meth should return a MyFooInts instance
fooIntsObj = barObj.meth
raise RuntimeError unless fooIntsObj.instance_of?(MyFooInts)
# MyFooInts#meth(n) should return n+1
raise RuntimeError if fooIntsObj.meth(42) != 43
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'disown'
include Disown
a = A.new
b = B.new
b.acquire(a)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'dynamic_cast'
f = Dynamic_cast::Foo.new
b = Dynamic_cast::Bar.new
x = f.blah
y = b.blah
a = Dynamic_cast.do_test(y)
if a != "Bar::test"
puts "Failed!!"
end
#!/usr/bin/env ruby
#
# Runtime tests for enums.i
#
require 'swig_assert'
require 'enums'
swig_assert_each_line( <<EOF )
Enums::CSP_ITERATION_FWD == 0
Enums::CSP_ITERATION_BWD == 11
Enums::ABCDE == 0
Enums::FGHJI == 1
Enums.bar1(1)
Enums.bar2(1)
Enums.bar3(1)
Enums::Boo == 0
Enums::Hoo == 5
Enums::Globalinstance1 == 0
Enums::Globalinstance2 == 1
Enums::Globalinstance3 == 30
Enums::AnonEnum1 == 0
Enums::AnonEnum2 == 100
Enums::BAR1 == 0
Enums::BAR2 == 1
EOF
#
# @bug:
#
# swig_assert_each_line( <<EOF )
# Enums::IFoo::Phoo == 50
# Enums::IFoo::Char == 'a'[0]
# EOF
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'enum_thorough'
include Enum_thorough
# Just test an in and out typemap for enum SWIGTYPE and const enum SWIGTYPE & typemaps
raise RuntimeError if speedTest4(SpeedClass::Slow) != SpeedClass::Slow
raise RuntimeError if speedTest5(SpeedClass::Slow) != SpeedClass::Slow
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'extend_template_ns'
include Extend_template_ns
f = Foo_One.new
if f.test1(37) != 37
raise RuntimeError
end
if f.test2(42) != 42
raise RuntimeError
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'extend_template'
f = Extend_template::Foo_0.new
if f.test1(37) != 37
raise RuntimeError
end
if f.test2(42) != 42
raise RuntimeError
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'friends'
a = Friends::A.new(2)
raise RuntimeError if Friends::get_val1(a) != 2
raise RuntimeError if Friends::get_val2(a) != 4
raise RuntimeError if Friends::get_val3(a) != 6
#!/usr/bin/env ruby
#
# Tests for function_typedef.i
#
#
require 'swig_assert'
require 'function_typedef'
include Function_typedef
# Hmm... not sure how to test this.
#!/usr/bin/env ruby
#
# C++ version of global_immutable_vars_runme.rb
#
require 'swig_assert'
require 'global_immutable_vars_cpp'
# first check if all variables can be read
swig_assert_each_line( <<EOF )
Global_immutable_vars_cpp::default_mutable_var == 40
Global_immutable_vars_cpp::global_immutable_var == 41
Global_immutable_vars_cpp::specific_mutable_var == 42
Global_immutable_vars_cpp::global_mutable_var == 43
Global_immutable_vars_cpp::specific_immutable_var == 44
EOF
# check that all mutable variables can be modified
swig_assert_each_line( <<EOF )
Global_immutable_vars_cpp::default_mutable_var = 80
Global_immutable_vars_cpp::default_mutable_var == 80
Global_immutable_vars_cpp::specific_mutable_var = 82
Global_immutable_vars_cpp::specific_mutable_var == 82
Global_immutable_vars_cpp::global_mutable_var = 83
Global_immutable_vars_cpp::global_mutable_var == 83
EOF
# now check that immutable variables cannot be modified
had_exception = false
begin
Global_immutable_vars_cpp::global_immutable_var = 81
rescue NoMethodError => e
had_exception = true
end
swig_assert(had_exception, nil,
"Global_immutable_vars_cpp::global_immutable_var is writable (expected to be immutable)")
had_exception = false
begin
Global_immutable_vars_cpp::specific_immutable_var = 81
rescue NoMethodError => e
had_exception = true
end
swig_assert(had_exception, nil,
"Global_immutable_vars_cpp::specific_immutable_var is writable (expected to be immutable)")
swig_assert(Global_immutable_vars_cpp::check_values(80, 41, 82, 83, 44) == 1, nil, "Check values failed")
#!/usr/bin/env ruby
#
# Here the proper generation of mutable and immutable variables is tested
# in the target language.
# Immutable variables do not have "<var>=" methods generated by SWIG,
# therefore trying to assign these variables shall throw a NoMethodError
# exception.
#
require 'swig_assert'
require 'global_immutable_vars'
# first check if all variables can be read
swig_assert_each_line( <<EOF )
Global_immutable_vars::default_mutable_var == 40
Global_immutable_vars::global_immutable_var == 41
Global_immutable_vars::specific_mutable_var == 42
Global_immutable_vars::global_mutable_var == 43
Global_immutable_vars::specific_immutable_var == 44
EOF
# check that all mutable variables can be modified
swig_assert_each_line( <<EOF )
Global_immutable_vars::default_mutable_var = 80
Global_immutable_vars::default_mutable_var == 80
Global_immutable_vars::specific_mutable_var = 82
Global_immutable_vars::specific_mutable_var == 82
Global_immutable_vars::global_mutable_var = 83
Global_immutable_vars::global_mutable_var == 83
EOF
# now check that immutable variables cannot be modified
had_exception = false
begin
Global_immutable_vars::global_immutable_var = 81
rescue NoMethodError => e
had_exception = true
end
swig_assert(had_exception, nil,
"Global_immutable_vars::global_immutable_var is writable (expected to be immutable)")
had_exception = false
begin
Global_immutable_vars::specific_immutable_var = 81
rescue NoMethodError => e
had_exception = true
end
swig_assert(had_exception, nil,
"Global_immutable_vars::specific_immutable_var is writable (expected to be immutable)")
swig_assert(Global_immutable_vars::check_values(80, 41, 82, 83, 44) == 1, nil, "Check values failed")
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'grouping'
x = Grouping.test1(42)
if x != 42
raise RuntimeError
end
Grouping.test2(42)
x = Grouping.do_unary(37, Grouping::NEGATE)
if x != -37
raise RuntimeError
end
Grouping.test3 = 42
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'ignore_parameter'
include Ignore_parameter
# Global function tests
raise RuntimeError unless jaguar(0, 1.0) == "hello"
raise RuntimeError unless lotus("foo", 1.0) == 101
raise RuntimeError unless tvr("foo", 0) == 8.8
raise RuntimeError unless ferrari() == 101
# Member function tests
sc = SportsCars.new
raise RuntimeError unless sc.daimler(0, 1.0) == "hello"
raise RuntimeError unless sc.astonmartin("foo", 1.0) == 101
raise RuntimeError unless sc.bugatti("foo", 0) == 8.8
raise RuntimeError unless sc.lamborghini() == 101
# Constructor tests
MiniCooper.new(0, 1.0)
MorrisMinor.new("foo", 1.0)
FordAnglia.new("foo", 0)
AustinAllegro.new()
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
# This is the import runtime testcase.
require 'imports_a'
require 'imports_b'
x = Imports_b::B.new
x.hello
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'inherit_missing'
a = Inherit_missing.new_Foo()
b = Inherit_missing::Bar.new
c = Inherit_missing::Spam.new
x = Inherit_missing.do_blah(a)
if x != "Foo::blah"
puts "Whoa! Bad return #{x}"
end
x = Inherit_missing.do_blah(b)
if x != "Bar::blah"
puts "Whoa! Bad return #{x}"
end
x = Inherit_missing.do_blah(c)
if x != "Spam::blah"
puts "Whoa! Bad return #{x}"
end
#!/usr/bin/env ruby
#
# Put script description here.
#
require 'swig_assert'
require 'integers'
include Integers
swig_assert_each_line <<EOF
signed_char_identity(-3) == -3
unsigned_char_identity(5) == 5
signed_short_identity(-3) == -3
unsigned_short_identity(5) == 5
signed_int_identity(-3) == -3
unsigned_int_identity(5) == 5
signed_long_identity(-3) == -3
unsigned_long_identity(5) == 5
signed_long_long_identity(-3) == -3
unsigned_long_long_identity(5) == 5
EOF
require 'li_boost_shared_ptr_bits'
require 'swig_gc'
v = Li_boost_shared_ptr_bits::VectorIntHolder.new()
v.push(Li_boost_shared_ptr_bits::IntHolder.new(11))
v.push(Li_boost_shared_ptr_bits::IntHolder.new(22))
v.push(Li_boost_shared_ptr_bits::IntHolder.new(33))
sum = Li_boost_shared_ptr_bits::sum(v)
if (sum != 66)
raise RuntimeError, "sum is wrong"
end
hidden = Li_boost_shared_ptr_bits::HiddenDestructor.create()
GC.track_class = Li_boost_shared_ptr_bits::HiddenPrivateDestructor
GC.stats if $VERBOSE
hidden = nil
GC.start
hiddenPrivate = Li_boost_shared_ptr_bits::HiddenPrivateDestructor.create()
if (Li_boost_shared_ptr_bits::HiddenPrivateDestructor.DeleteCount != 0)
# GC doesn't always run
# raise RuntimeError, "Count should be zero"
end
GC.stats if $VERBOSE
hiddenPrivate = nil
GC.start
if (Li_boost_shared_ptr_bits::HiddenPrivateDestructor.DeleteCount != 1)
# GC doesn't always run
# raise RuntimeError, "Count should be one"
end
require 'li_boost_shared_ptr_director'
include Li_boost_shared_ptr_director
class Derived < Base
def initialize(flag)
@return_none = flag
super()
end
def ret_c_shared_ptr
if @return_none
nil
else
C.new
end
end
def ret_c_by_value
C.new
end
def take_c_by_value(c)
c.get_m
end
def take_c_by_ref(c)
c.get_m
end
def take_c_by_pointer(c)
if c
c.get_m
else
-2
end
end
def take_c_by_pointer_ref(c)
if c
c.get_m
else
-3
end
end
def take_c_shared_ptr_by_value(c)
if c
c.get_m
else
-4
end
end
def take_c_shared_ptr_by_ref(c)
if c
c.get_m
else
-5
end
end
def take_c_shared_ptr_by_pointer(c)
if c
c.get_m
else
-6
end
end
def take_c_shared_ptr_by_pointer_ref(c)
if c
c.get_m
else
-7
end
end
end
a = Derived.new(false)
b = Derived.new(true)
raise unless call_ret_c_shared_ptr(a) == 1
raise unless call_ret_c_shared_ptr(b) == -1
raise unless call_ret_c_by_value(a) == 1
raise unless call_take_c_by_value(a) == 5
raise unless call_take_c_by_ref(a) == 6
raise unless call_take_c_by_pointer(a) == 7
raise unless call_take_c_by_pointer_ref(a) == 8
raise unless call_take_c_shared_ptr_by_value(a) == 9
raise unless call_take_c_shared_ptr_by_ref(a) == 10
raise unless call_take_c_shared_ptr_by_pointer(a) == 11
raise unless call_take_c_shared_ptr_by_pointer_ref(a) == 12
raise unless call_take_c_by_pointer_with_null(a) == -2
raise unless call_take_c_by_pointer_ref_with_null(a) == -3
raise unless call_take_c_shared_ptr_by_value_with_null(a) == -4
raise unless call_take_c_shared_ptr_by_ref_with_null(a) == -5
raise unless call_take_c_shared_ptr_by_pointer_with_null(a) == -6
raise unless call_take_c_shared_ptr_by_pointer_ref_with_null(a) == -7
require 'li_boost_shared_ptr'
require 'swig_gc'
#debug = $VERBOSE
debug = false
# simple shared_ptr usage - created in C++
class Li_boost_shared_ptr_runme
def main(debug)
if (debug)
puts "Started"
end
Li_boost_shared_ptr::debug_shared = debug
# Change loop count to run for a long time to monitor memory
loopCount = 1 # 5000
1.upto(loopCount) do
self.runtest()
end
# Expect 1 instance - the one global variable (GlobalValue)
GC.track_class = Li_boost_shared_ptr::Klass
invokeGC("Final GC")
# Actual count is 3 due to memory leaks calling rb_raise in the call to Li_boost_shared_ptr::valuetest(nil)
# as setjmp/longjmp are used thereby failing to call destructors of Klass instances on the stack in _wrap_valuetest
# This is a generic problem in Ruby wrappers, not shared_ptr specific
# expectedCount = 1
expectedCount = 3
actualCount = Li_boost_shared_ptr::Klass.getTotal_count()
if (actualCount != expectedCount)
# raise RuntimeError, "GC failed to run (li_boost_shared_ptr). Expected count: #{expectedCount} Actual count: #{actualCount}"
puts "GC failed to run (li_boost_shared_ptr). Expected count: #{expectedCount} Actual count: #{actualCount}"
end
wrapper_count = Li_boost_shared_ptr::shared_ptr_wrapper_count()
if (wrapper_count != Li_boost_shared_ptr.NOT_COUNTING)
# Expect 1 instance - the one global variable (GlobalSmartValue)
if (wrapper_count != 1)
raise RuntimeError, "shared_ptr wrapper count=#{wrapper_count}"
end
end
if (debug)
puts "Finished"
end
end
def invokeGC(debug_msg)
puts "invokeGC #{debug_msg} start" if $VERBOSE
GC.stats if $VERBOSE
GC.start
puts "invokeGC #{debug_msg} end" if $VERBOSE
end
def runtest
# simple shared_ptr usage - created in C++
k = Li_boost_shared_ptr::Klass.new("me oh my")
val = k.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(1, k)
# simple shared_ptr usage - not created in C++
k = Li_boost_shared_ptr::factorycreate()
val = k.getValue()
self.verifyValue("factorycreate", val)
self.verifyCount(1, k)
# pass by shared_ptr
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::smartpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointertest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::smartpointerpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointertest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr reference
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::smartpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerreftest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer reference
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::smartpointerpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointerreftest", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# const pass by shared_ptr
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::constsmartpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# const pass by shared_ptr pointer
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::constsmartpointerpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# const pass by shared_ptr reference
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::constsmartpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by value
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::valuetest(k)
val = kret.getValue()
self.verifyValue("me oh my valuetest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by pointer
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::pointertest(k)
val = kret.getValue()
self.verifyValue("me oh my pointertest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by reference
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::reftest(k)
val = kret.getValue()
self.verifyValue("me oh my reftest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by pointer reference
k = Li_boost_shared_ptr::Klass.new("me oh my")
kret = Li_boost_shared_ptr::pointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my pointerreftest", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# null tests
k = nil
if (Li_boost_shared_ptr::smartpointertest(k) != nil)
raise RuntimeError, "return was not null"
end
if (Li_boost_shared_ptr::smartpointerpointertest(k) != nil)
raise RuntimeError, "return was not null"
end
if (Li_boost_shared_ptr::smartpointerreftest(k) != nil)
raise RuntimeError, "return was not null"
end
if (Li_boost_shared_ptr::smartpointerpointerreftest(k) != nil)
raise RuntimeError, "return was not null"
end
if (Li_boost_shared_ptr::nullsmartpointerpointertest(nil) != "null pointer")
raise RuntimeError, "not null smartpointer pointer"
end
begin
Li_boost_shared_ptr::valuetest(k)
raise RuntimeError, "Failed to catch null pointer"
rescue ArgumentError
end
if (Li_boost_shared_ptr::pointertest(k) != nil)
raise RuntimeError, "return was not null"
end
begin
Li_boost_shared_ptr::reftest(k)
raise RuntimeError, "Failed to catch null pointer"
rescue ArgumentError
end
# $owner
k = Li_boost_shared_ptr::pointerownertest()
val = k.getValue()
self.verifyValue("pointerownertest", val)
self.verifyCount(1, k)
k = Li_boost_shared_ptr::smartpointerpointerownertest()
val = k.getValue()
self.verifyValue("smartpointerpointerownertest", val)
self.verifyCount(1, k)
# //////////////////////////////// Derived class //////////////////////
# derived pass by shared_ptr
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::derivedsmartptrtest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrtest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by shared_ptr pointer
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::derivedsmartptrpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by shared_ptr ref
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::derivedsmartptrreftest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by shared_ptr pointer ref
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::derivedsmartptrpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# derived pass by pointer
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::derivedpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedpointertest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# derived pass by ref
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::derivedreftest(k)
val = kret.getValue()
self.verifyValue("me oh my derivedreftest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# //////////////////////////////// Derived and base class mixed ///////
# pass by shared_ptr (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::smartpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointertest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::smartpointerpointertest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointertest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr reference (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::smartpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by shared_ptr pointer reference (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::smartpointerpointerreftest(k)
val = kret.getValue()
self.verifyValue("me oh my smartpointerpointerreftest-Derived", val)
self.verifyCount(2, k)
self.verifyCount(2, kret)
# pass by value (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::valuetest(k)
val = kret.getValue()
self.verifyValue("me oh my valuetest", val) # note slicing
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by pointer (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::pointertest(k)
val = kret.getValue()
self.verifyValue("me oh my pointertest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# pass by ref (mixed)
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
kret = Li_boost_shared_ptr::reftest(k)
val = kret.getValue()
self.verifyValue("me oh my reftest-Derived", val)
self.verifyCount(1, k)
self.verifyCount(1, kret)
# //////////////////////////////// Overloading tests //////////////////
# Base class
k = Li_boost_shared_ptr::Klass.new("me oh my")
self.verifyValue(Li_boost_shared_ptr::overload_rawbyval(k), "rawbyval")
self.verifyValue(Li_boost_shared_ptr::overload_rawbyref(k), "rawbyref")
self.verifyValue(Li_boost_shared_ptr::overload_rawbyptr(k), "rawbyptr")
self.verifyValue(
Li_boost_shared_ptr::overload_rawbyptrref(k), "rawbyptrref")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyval(k), "smartbyval")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyref(k), "smartbyref")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyptr(k), "smartbyptr")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyptrref(k), "smartbyptrref")
# Derived class
k = Li_boost_shared_ptr::KlassDerived.new("me oh my")
self.verifyValue(Li_boost_shared_ptr::overload_rawbyval(k), "rawbyval")
self.verifyValue(Li_boost_shared_ptr::overload_rawbyref(k), "rawbyref")
self.verifyValue(Li_boost_shared_ptr::overload_rawbyptr(k), "rawbyptr")
self.verifyValue(
Li_boost_shared_ptr::overload_rawbyptrref(k), "rawbyptrref")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyval(k), "smartbyval")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyref(k), "smartbyref")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyptr(k), "smartbyptr")
self.verifyValue(
Li_boost_shared_ptr::overload_smartbyptrref(k), "smartbyptrref")
# 3rd derived class
k = Li_boost_shared_ptr::Klass3rdDerived.new("me oh my")
val = k.getValue()
self.verifyValue("me oh my-3rdDerived", val)
self.verifyCount(1, k)
val = Li_boost_shared_ptr::test3rdupcast(k)
self.verifyValue("me oh my-3rdDerived", val)
self.verifyCount(1, k)
# //////////////////////////////// Member variables ///////////////////
# smart pointer by value
m = Li_boost_shared_ptr::MemberVariables.new()
k = Li_boost_shared_ptr::Klass.new("smart member value")
m.SmartMemberValue = k
val = k.getValue()
self.verifyValue("smart member value", val)
self.verifyCount(2, k)
kmember = m.SmartMemberValue
val = kmember.getValue()
self.verifyValue("smart member value", val)
self.verifyCount(3, kmember)
self.verifyCount(3, k)
GC.track_class = Li_boost_shared_ptr::MemberVariables
m = nil
invokeGC("m = nil (A)")
self.verifyCount(2, kmember)
self.verifyCount(2, k)
# smart pointer by pointer
m = Li_boost_shared_ptr::MemberVariables.new()
k = Li_boost_shared_ptr::Klass.new("smart member pointer")
m.SmartMemberPointer = k
val = k.getValue()
self.verifyValue("smart member pointer", val)
self.verifyCount(1, k)
kmember = m.SmartMemberPointer
val = kmember.getValue()
self.verifyValue("smart member pointer", val)
self.verifyCount(2, kmember)
self.verifyCount(2, k)
m = nil
invokeGC("m = nil (B)")
self.verifyCount(2, kmember)
self.verifyCount(2, k)
# smart pointer by reference
m = Li_boost_shared_ptr::MemberVariables.new()
k = Li_boost_shared_ptr::Klass.new("smart member reference")
m.SmartMemberReference = k
val = k.getValue()
self.verifyValue("smart member reference", val)
self.verifyCount(2, k)
kmember = m.SmartMemberReference
val = kmember.getValue()
self.verifyValue("smart member reference", val)
self.verifyCount(3, kmember)
self.verifyCount(3, k)
# The C++ reference refers to SmartMemberValue...
kmemberVal = m.SmartMemberValue
val = kmember.getValue()
self.verifyValue("smart member reference", val)
self.verifyCount(4, kmemberVal)
self.verifyCount(4, kmember)
self.verifyCount(4, k)
m = nil
invokeGC("m = nil (C)")
self.verifyCount(3, kmemberVal)
self.verifyCount(3, kmember)
self.verifyCount(3, k)
# plain by value
m = Li_boost_shared_ptr::MemberVariables.new()
k = Li_boost_shared_ptr::Klass.new("plain member value")
m.MemberValue = k
val = k.getValue()
self.verifyValue("plain member value", val)
self.verifyCount(1, k)
kmember = m.MemberValue
val = kmember.getValue()
self.verifyValue("plain member value", val)
self.verifyCount(1, kmember)
self.verifyCount(1, k)
m = nil
invokeGC("m = nil (D)")
self.verifyCount(1, kmember)
self.verifyCount(1, k)
# plain by pointer
m = Li_boost_shared_ptr::MemberVariables.new()
k = Li_boost_shared_ptr::Klass.new("plain member pointer")
m.MemberPointer = k
val = k.getValue()
self.verifyValue("plain member pointer", val)
self.verifyCount(1, k)
kmember = m.MemberPointer
val = kmember.getValue()
self.verifyValue("plain member pointer", val)
self.verifyCount(1, kmember)
self.verifyCount(1, k)
m = nil
invokeGC("m = nil (E)")
self.verifyCount(1, kmember)
self.verifyCount(1, k)
# plain by reference
m = Li_boost_shared_ptr::MemberVariables.new()
k = Li_boost_shared_ptr::Klass.new("plain member reference")
m.MemberReference = k
val = k.getValue()
self.verifyValue("plain member reference", val)
self.verifyCount(1, k)
kmember = m.MemberReference
val = kmember.getValue()
self.verifyValue("plain member reference", val)
self.verifyCount(1, kmember)
self.verifyCount(1, k)
m = nil
invokeGC("m = nil (F)")
self.verifyCount(1, kmember)
self.verifyCount(1, k)
# null member variables
m = Li_boost_shared_ptr::MemberVariables.new()
# shared_ptr by value
k = m.SmartMemberValue
if (k != nil)
raise RuntimeError, "expected null"
end
m.SmartMemberValue = nil
k = m.SmartMemberValue
if (k != nil)
raise RuntimeError, "expected null"
end
self.verifyCount(0, k)
# plain by value
begin
m.MemberValue = nil
raise RuntimeError, "Failed to catch null pointer"
rescue ArgumentError
end
# ////////////////////////////////// Global variables /////////////////
# smart pointer
kglobal = Li_boost_shared_ptr.GlobalSmartValue
if (kglobal != nil)
raise RuntimeError, "expected null"
end
k = Li_boost_shared_ptr::Klass.new("smart global value")
Li_boost_shared_ptr.GlobalSmartValue = k
self.verifyCount(2, k)
kglobal = Li_boost_shared_ptr.GlobalSmartValue
val = kglobal.getValue()
self.verifyValue("smart global value", val)
self.verifyCount(3, kglobal)
self.verifyCount(3, k)
self.verifyValue(
"smart global value", Li_boost_shared_ptr.GlobalSmartValue.getValue())
Li_boost_shared_ptr.GlobalSmartValue = nil
# plain value
k = Li_boost_shared_ptr::Klass.new("global value")
Li_boost_shared_ptr.GlobalValue = k
self.verifyCount(1, k)
kglobal = Li_boost_shared_ptr.GlobalValue
val = kglobal.getValue()
self.verifyValue("global value", val)
self.verifyCount(1, kglobal)
self.verifyCount(1, k)
self.verifyValue(
"global value", Li_boost_shared_ptr.GlobalValue.getValue())
begin
Li_boost_shared_ptr.GlobalValue = nil
raise RuntimeError, "Failed to catch null pointer"
rescue ArgumentError
end
# plain pointer
kglobal = Li_boost_shared_ptr.GlobalPointer
if (kglobal != nil)
raise RuntimeError, "expected null"
end
k = Li_boost_shared_ptr::Klass.new("global pointer")
Li_boost_shared_ptr.GlobalPointer = k
self.verifyCount(1, k)
kglobal = Li_boost_shared_ptr.GlobalPointer
val = kglobal.getValue()
self.verifyValue("global pointer", val)
self.verifyCount(1, kglobal)
self.verifyCount(1, k)
Li_boost_shared_ptr.GlobalPointer = nil
# plain reference
k = Li_boost_shared_ptr::Klass.new("global reference")
Li_boost_shared_ptr.GlobalReference = k
self.verifyCount(1, k)
kglobal = Li_boost_shared_ptr.GlobalReference
val = kglobal.getValue()
self.verifyValue("global reference", val)
self.verifyCount(1, kglobal)
self.verifyCount(1, k)
begin
Li_boost_shared_ptr.GlobalReference = nil
raise RuntimeError, "Failed to catch null pointer"
rescue ArgumentError
end
# ////////////////////////////////// Templates ////////////////////////
pid = Li_boost_shared_ptr::PairIntDouble.new(10, 20.2)
if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4)
raise RuntimeError, "Base values wrong"
end
if (pid.val1 != 10 or pid.val2 != 20.2)
raise RuntimeError, "Derived Values wrong"
end
end
def verifyValue(expected, got)
if (expected != got)
raise RuntimeError, "verify value failed. Expected: #{expected} Got: #{got}"
end
end
def verifyCount(expected, k)
got = Li_boost_shared_ptr::use_count(k)
if (expected != got)
puts "skipped verifyCount expect/got: #{expected}/#{got}"
# raise RuntimeError, "verify use_count failed. Expected: #{expected} Got: #{got}"
end
end
end
runme = Li_boost_shared_ptr_runme.new()
runme.main(debug)
require 'li_boost_shared_ptr_template'
begin
b = Li_boost_shared_ptr_template::BaseINTEGER.new()
d = Li_boost_shared_ptr_template::DerivedINTEGER.new()
if (b.bar() != 1)
raise RuntimeError("test 1")
end
if (d.bar() != 2)
raise RuntimeError("test 2")
end
if (Li_boost_shared_ptr_template.bar_getter(b) != 1)
raise RuntimeError("test 3")
end
# Needs fixing as it does for Python
# if (Li_boost_shared_ptr_template.bar_getter(d) != 2)
# raise RuntimeError("test 4")
# end
end
begin
b = Li_boost_shared_ptr_template::BaseDefaultInt.new()
d = Li_boost_shared_ptr_template::DerivedDefaultInt.new()
d2 = Li_boost_shared_ptr_template::DerivedDefaultInt2.new()
if (b.bar2() != 3)
raise RuntimeError("test 5")
end
if (d.bar2() != 4)
raise RuntimeError("test 6")
end
if (d2.bar2() != 4)
raise RuntimeError("test 6")
end
if (Li_boost_shared_ptr_template.bar2_getter(b) != 3)
raise RuntimeError("test 7")
end
# Needs fixing as it does for Python
# if (Li_boost_shared_ptr_template.bar2_getter(d) != 4)
# raise RuntimeError("test 8")
# end
# if (Li_boost_shared_ptr_template.bar2_getter(d2) != 4)
# raise RuntimeError("test 8")
# end
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_carrays_cpp'
include Li_carrays_cpp
#
# Testing for %array_functions(int,intArray)
#
ary = new_intArray(2)
intArray_setitem(ary, 0, 0)
intArray_setitem(ary, 1, 1)
intArray_getitem(ary, 0)
intArray_getitem(ary, 1)
delete_intArray(ary)
#
# Testing for %array_class(double, doubleArray)
#
ary = DoubleArray.new(2)
ary[0] = 0.0
ary[1] = 1.0
ary[0]
ary[1]
ptr = ary.cast
ary2 = DoubleArray.frompointer(ptr)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_carrays'
include Li_carrays
#
# Testing for %array_functions(int,intArray)
#
ary = new_intArray(2)
intArray_setitem(ary, 0, 0)
intArray_setitem(ary, 1, 1)
intArray_getitem(ary, 0)
intArray_getitem(ary, 1)
delete_intArray(ary)
#
# Testing for %array_class(double, doubleArray)
#
ary = DoubleArray.new(2)
ary[0] = 0.0
ary[1] = 1.0
ary[0]
ary[1]
ptr = ary.cast
ary2 = DoubleArray.frompointer(ptr)
#!/usr/bin/env ruby
#
# Test for li_cstring.i
#
require 'swig_assert'
require 'li_cstring'
include Li_cstring
swig_assert_each_line <<EOF
count("hello", 'l'[0]) == 2
test1 == 'Hello World'
test2
test3('hello') == 'hello-suffix'
test4('hello') == 'hello-suffix'
test5(5) == 'xxxxx'
test6(6) == 'xxx'
test7 == 'Hello world!'
test8 == (32..32+63).map {|x| x.chr }.join
EOF
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_factory'
circle = Li_factory::Geometry.create(Li_factory::Geometry::CIRCLE)
r = circle.radius()
if (r != 1.5)
raise RuntimeError, "Invalid value for r"
end
new_circle = circle.clone()
r = new_circle.radius()
if (r != 1.5)
raise RuntimeError, "Invalid value for r"
end
point = Li_factory::Geometry.create(Li_factory::Geometry::POINT)
w = point.width()
if (w != 1.0)
raise RuntimeError, "Invalid value for w"
end
new_point = point.clone()
w = new_point.width()
if (w != 1.0)
raise RuntimeError, "Invalid value for w"
end
#!/usr/bin/env ruby
#
# li_math.i tests
#
#
require 'swig_assert'
require 'li_math'
swig_assert_each_line <<EOF
Li_math.cos(-5) == Math.cos(-5)
Li_math.sin(-5) == Math.sin(-5)
EOF
#!/usr/bin/env ruby
require 'swig_assert'
require 'li_std_auto_ptr'
def gc_check(expected_count)
# GC.start(full_mark: true, immediate_sweep: true)
GC.start
# GC is not reliably run, skip check
# swig_assert_equal_simple(expected_count, Li_std_auto_ptr::Klass::getTotal_count())
end
k1 = Li_std_auto_ptr::makeKlassAutoPtr("first")
k2 = Li_std_auto_ptr::makeKlassAutoPtr("second")
swig_assert_equal_simple(2, Li_std_auto_ptr::Klass::getTotal_count())
gc_check(2)
k1 = nil
gc_check(1)
swig_assert_equal_simple(k2.getLabel(), "second")
gc_check(1)
k2 = nil
gc_check(0)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_std_containers_overload'
include Li_std_containers_overload
def check(got, expected)
if (got != expected)
raise RuntimeError, "Failed check. '#{got}' != '#{expected}'"
end
end
v = VectorX.new()
check(VectorOverload(v), "vector<X>")
v = VectorY.new()
check(VectorOverload(v), "vector<Y>")
v = VectorInt.new()
check(VectorOverload(v), "vector<int>")
v = VectorString.new()
check(VectorOverload(v), "vector<string>")
v = [X.new()]
check(VectorOverload(v), "vector<X>")
v = [Y.new()]
check(VectorOverload(v), "vector<Y>")
v = [1, 2, 3]
check(VectorOverload(v), "vector<int>")
v = ["aaa", "bbb", "ccc"]
check(VectorOverload(v), "vector<string>")
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_std_deque'
include Li_std_deque
# Test constructors for std::deque<int>
intDeque = IntDeque.new
intDeque2 = IntDeque.new(3)
intDeque3 = IntDeque.new(4, 42)
intDeque4 = IntDeque.new(intDeque3)
# Test constructors for std::deque<double>
doubleDeque = DoubleDeque.new
doubleDeque2 = DoubleDeque.new(3)
doubleDeque3 = DoubleDeque.new(4, 42.0)
doubleDeque4 = DoubleDeque.new(doubleDeque3)
# Test constructors for std::deque<Real>
realDeque = RealDeque.new
realDeque2 = RealDeque.new(3)
realDeque3 = RealDeque.new(4, 42.0)
realDeque4 = RealDeque.new(realDeque3)
# average() should return the average of all values in a std::deque<int>
intDeque << 2
intDeque << 4
intDeque << 6
avg = average(intDeque)
raise RuntimeError if avg != 4.0
#
# half() should return a std::deque<float>, where each element is half
# the value of the corresponding element in the input deque<float>.
# The original deque's contents are unchanged.
#
realDeque.clear
realDeque << 2.0
halfDeque = half(realDeque)
raise RuntimeError unless halfDeque[0] == 1.0
#
# halve_in_place() should...
#
halve_in_place(doubleDeque)
#!/usr/bin/env ruby
#
# This is a test of STL containers using proc
# objects to change the sorting function used in them. Same as a
# std::binary_predicate in C++.
#
#
#
#
#
require 'swig_assert'
require 'li_std_functors'
def _set(container)
swig_assert_each_line(<<EOF, binding)
cont = #{container}.new
[9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
i0 = cont.begin()
cont.to_a == [1,2,3,4,5,6,7,8,9]
cont = #{container}.new( proc { |a,b| b < a } )
[9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
cont.to_a == [9, 8, 7, 6, 5, 4, 3, 2, 1]
cont = #{container}.new( proc { |a,b| b > a } )
[9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
cont.to_a == [1, 2, 3, 4, 5, 6, 7, 8, 9]
cont = #{container}.new(proc { |a,b| b < a } )
cont.insert(1)
cont.to_a == [1]
i0 = cont.begin()
cont.erase(i0) # don't use i0 anymore, it is invalid now
cont.to_a == []
EOF
end
def b_lessthan_a(b, a)
res = b < a
# print b, "<", a, "=", res
return res
end
def _map(container)
swig_assert_each_line(<<EOF, binding)
cont = #{container}.new
cont['z'] = 9
cont['y'] = 1
cont['x'] = 8
cont['w'] = 2
cont.to_a == [['w',2],['x',8],['y',1],['z',9]]
cont = #{container}.new(proc { |a,b| b_lessthan_a(b, a) } )
cont['z'] = 9
cont['y'] = 1
cont['x'] = 8
cont['w'] = 2
cont.to_a == [['z',9],['y',1],['x',8],['w',2]]
EOF
end
def test
yield method(:_set), Li_std_functors::Set
yield method(:_map), Li_std_functors::Map
end
# these should fail and not segfault
begin
Li_std_functors::Set.new('sd')
rescue
end
test do |proc, container|
proc.call(container)
end
require 'swig_assert'
require 'li_std_list'
include Li_std_list
x = DoubleList.new([1,2,3])
swig_assert_equal("[1.0]", "x.find_all{|e| e == 1 }", binding)
#!/usr/bin/env ruby
#
# Tests for std::map
#
#
#
#
#
require 'swig_assert'
require 'li_std_map'
swig_assert_each_line(<<'EOF', binding)
a1 = Li_std_map::A.new(3)
a2 = Li_std_map::A.new(7)
p0 = Li_std_map::Pairii.new(1,2)
p1 = Li_std_map::PairA.new(1,a1)
m = {}
m[1] = a1
m[2] = a2
pp1 = Li_std_map::p_identa(p1)
mm = Li_std_map::m_identa(m)
m = Li_std_map::MapA.new
m[1] = a1
m[2] = a2
m.respond_to?(:each_key) == true
m.respond_to?(:each_value) == true
pm ={}
m.each_key { |k| pm[k] = m[k] }
m.each_key { |k| swig_assert_equal("pm[k].object_id", "m[k].object_id", binding, 'only true if %trackings is on') }
m = {}
m[1] = [1,2]
m["foo"] = "hello"
pm = Li_std_map::LanguageMap.new
m.each_key { |k| pm[k] = m[k] }
m.each_key { |k| swig_assert_equal("pm[#{k.inspect}]", "m[#{k.inspect}]", binding) }
EOF
mii = Li_std_map::IntIntMap.new
mii[1] = 1
mii[1] = 2
swig_assert( "mii[1] == 2", binding )
#!/usr/bin/env ruby
#
# Tests for std::multimap
#
#
#
#
#
require 'swig_assert'
require 'li_std_multimap'
swig_assert_each_line(<<'EOF', binding)
a1 = Li_std_multimap::A.new(3)
a2 = Li_std_multimap::A.new(7)
m = Li_std_multimap::MultimapA.new
m[0] = a1
m[0] = a2
m[0].size == 2
m.respond_to?(:each) == true
m.respond_to?(:each_key) == true
m.respond_to?(:each_value) == true
m.values_at(0)[0] == m[0]
EOF
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_std_pair_lang_object'
include Li_std_pair_lang_object
swig_assert_each_line(<<'EOF', binding)
val = ValuePair.new
val.first = 'sd'
val.second = [5,4,3]
EOF
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_std_pair'
include Li_std_pair
swig_assert_each_line(<<'EOF', binding)
#
# Because of template specializations for pair<int, int>, these should return
# an Array of size 2, where both elements are Fixnums.
#
intPair = makeIntPair(7, 6)
intPair.instance_of?(Array)
intPair.size == 2
intPair[0] == 7 && intPair[1] == 6
intPairConstRef = makeIntPairConstRef(7, 6)
intPairConstRef.instance_of?(Array)
intPairConstRef[0] == 7 && intPairConstRef[1] == 6
#
# Each of these should return a reference to a wrapped
# std::pair<int, int> object (i.e. an IntPair instance).
#
intPairPtr = makeIntPairPtr(7, 6)
intPairPtr.instance_of?(IntPair)
intPairPtr[0] == 7 && intPairPtr[1] == 6
intPairRef = makeIntPairRef(7, 6)
intPairRef.instance_of?(IntPair)
intPairRef[0] == 7 && intPairRef[1] == 6
#
# Now test various input typemaps. Each of the wrapped C++ functions
# (product1, product2 and product3) is expecting an argument of a
# different type (see li_std_pair.i). Typemaps should be in place to
# convert this Array into the expected argument type.
#
product1(intPair) == 42
product2(intPair) == 42
product3(intPair) == 42
#
# Similarly, each of the input typemaps should know what to do
# with an IntPair instance.
#
product1(intPairPtr) == 42
product2(intPairPtr) == 42
product3(intPairPtr) == 42
EOF
#!/usr/bin/env ruby
#
# A simple std::queue test
#
#
#
#
#
require 'swig_assert'
require 'li_std_queue'
include Li_std_queue
swig_assert_each_line(<<'EOF', binding)
a = IntQueue.new
a << 1
a << 2
a << 3
a.back == 3
a.front == 1
a.pop
a.back == 3
a.front == 2
a.pop
a.back == 3
a.front == 3
a.pop
a.size == 0
a.empty? == true
EOF
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'li_std_set'
include Li_std_set
swig_assert_each_line(<<'EOF', binding)
s = Set_string.new
s.push("a")
s.push("b")
s << "c"
sum = ''
s.each { |x| sum << x }
sum == 'abc'
b = s.begin # only if swig iterators are on
e = s.end
sum = ''
while b != e; sum << b.value; b.next; end
sum == 'abc'
b = s.rbegin # only if swig iterators are on
e = s.rend
sum = ''
while b != e; sum << b.value; b.next; end
sum == 'cba'
si = Set_int.new
si << 1
si.push(2)
si.push(3)
i = s.begin()
i.next()
s.erase(i)
s.to_s == 'ac'
b = s.begin
e = s.end
e - b == 2
m = b + 1
m.value == 'c'
s = LanguageSet.new
s.insert([1,2])
s.insert(1)
s.insert("hello")
#s.to_a == [1,[1,2],'hello'] # sort order: s.sort {|a,b| a.hash <=> b.hash}
# Test above is flawed as LanguageSet sorts by each element's hash, so the order will change from one invocation to the next. Sort a conversion to array instead.
sa = s.to_a.sort { |x, y| x.to_s <=> y.to_s }
sa == [1,[1,2],'hello']
EOF
iv = Set_int.new([0,1,2,3,4,5,6])
iv.delete_if { |x| x == 0 || x == 3 || x == 6 }
swig_assert_equal(iv.to_s, '1245', binding)
#!/usr/bin/env ruby
require 'benchmark'
require 'li_std_speed'
include Li_std_speed
def benchmark(f, phigh, sequences)
print f.class
puts '%10s ' % 'n' + sequences.inject('') { |a,s| a << '%10s' % s.class }
0.upto(phigh-1) do |p|
n = 2**p
print "%10d"%n
$stdout.flush
for s in sequences
cont = s.new((0..n).to_a)
Benchmark.benchmark { f.call(cont) }
end
end
end
def iterate(cont)
# expected: O(n)
# got: O(n**2) for set/list (vector/deque fine)
it = cont.begin
last = cont.end
while it != last
it.next
end
end
def erase(cont)
# expected: O(n)
# got: O(n**2) for vector/deque and O(n**3) for set/list
it = cont.end
# can't reuse begin since it might get invalidated
while it != cont.begin
it.previous
# set returns None, so need to reobtain end
it = cont.erase(it) or cont.end
end
end
def insert(cont)
it = cont.end
size = cont.size
if cont.kind_of? RbSet
# swig stl missing hint version of insert for set
# expected would be O(n) with iterator hint version
# expected: O(n*log(n))
# got: O(n**3*log(n))
size.upto(size<<1) { |x| cont.insert(x) }
else
# expected: O(n)
# got: O(n**3) for list (vector/deque fine)
size.upto(size<<1) { |x| cont.push(x) }
end
end
if $0 == __FILE__
sequences = [RbVector,RbDeque,RbSet,RbList]
for f,phigh in [[method(:iterate),15], [method(:insert),15],
[method(:erase),11]]
benchmark(f, phigh, sequences)
end
end
#!/usr/bin/env ruby
#
# A simple std::stack test
#
#
#
#
#
require 'swig_assert'
require 'li_std_stack'
include Li_std_stack
swig_assert_each_line(<<'EOF', binding)
a = IntStack.new
a << 1
a << 2
a << 3
a.top == 3
a.pop
a.top == 2
a.pop
a.top == 1
a.pop
a.size == 0
a.empty? == true
# a.top == Qnil
EOF
#!/usr/bin/env ruby
#
# Simple test of std::ostringstream.
#
#
#
#
#
require 'swig_assert'
require 'li_std_stream'
include Li_std_stream
swig_assert_each_line(<<'EOF', binding)
a = A.new
o = Ostringstream.new
o << a << " " << 2345 << " " << 1.435
o.str == "A class 2345 1.435"
EOF
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_std_string'
include Li_std_string
# Checking expected use of %typemap(in) std::string {}
test_value("Fee")
# Checking expected result of %typemap(out) std::string {}
raise RuntimeError unless test_value("Fi") == "Fi"
# Verify type-checking for %typemap(in) std::string {}
exceptionRaised = false
begin
test_value(0)
rescue TypeError
exceptionRaised = true
ensure
raise RuntimeError unless exceptionRaised
end
# Checking expected use of %typemap(in) const std::string & {}
test_const_reference("Fo")
# Checking expected result of %typemap(out) const std::string& {}
raise RuntimeError unless test_const_reference("Fum") == "Fum"
# Verify type-checking for %typemap(in) const std::string & {}
exceptionRaised = false
begin
test_const_reference(0)
rescue TypeError
exceptionRaised = true
ensure
raise RuntimeError unless exceptionRaised
end
#
# Input and output typemaps for pointers and non-const references to
# std::string are *not* supported; the following tests confirm
# that none of these cases are slipping through.
#
exceptionRaised = false
begin
test_pointer("foo")
rescue TypeError
exceptionRaised = true
ensure
raise RuntimeError unless exceptionRaised
end
result = test_pointer_out()
raise RuntimeError if result.is_a? String
exceptionRaised = false
begin
test_const_pointer("bar")
rescue TypeError
exceptionRaised = true
ensure
raise RuntimeError unless exceptionRaised
end
result = test_const_pointer_out()
raise RuntimeError if result.is_a? String
exceptionRaised = false
begin
test_reference("foo")
rescue TypeError
exceptionRaised = true
ensure
raise RuntimeError unless exceptionRaised
end
result = test_reference_out()
raise RuntimeError if result.is_a? String
# Member Strings
myStructure = Structure.new
if (myStructure.MemberString2 != "member string 2")
raise RuntimeError
end
s = "Hello"
myStructure.MemberString2 = s
if (myStructure.MemberString2 != s)
raise RuntimeError
end
if (myStructure.ConstMemberString != "const member string")
raise RuntimeError
end
if (Structure.StaticMemberString2 != "static member string 2")
raise RuntimeError
end
Structure.StaticMemberString2 = s
if (Structure.StaticMemberString2 != s)
raise RuntimeError
end
if (Structure.ConstStaticMemberString != "const static member string")
raise RuntimeError
end
if (test_reference_input("hello") != "hello")
raise RuntimeError
end
s = test_reference_inout("hello")
if (s != "hellohello")
raise RuntimeError
end
if (stdstring_empty() != "")
raise RuntimeError
end
if (c_empty() != "")
raise RuntimeError
end
if (c_null() != nil)
raise RuntimeError
end
if (get_null(c_null()) != nil)
raise RuntimeError
end
#!/usr/bin/env ruby
require 'swig_assert'
require 'li_std_vector_enum'
include Li_std_vector_enum
ev = EnumVector.new()
swig_assert(ev.nums[0] == 10)
swig_assert(ev.nums[1] == 20)
swig_assert(ev.nums[2] == 30)
it = ev.nums.begin
v = it.value()
swig_assert(v == 10)
it.next()
v = it.value()
swig_assert(v == 20)
expected = 10
ev.nums.each do|val|
swig_assert(val == expected)
expected += 10
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'li_std_vector'
include Li_std_vector
iv = IntVector.new(4)
swig_assert( "iv.respond_to? :each", binding )
begin
iv.each
swig_assert( false, nil, "iv.each worked with no block!")
rescue ArgumentError
end
swig_assert_each_line(<<'EOF', binding)
iv.respond_to?(:each) == true
iv.respond_to?(:each_with_index) == true
EOF
iv.each_with_index { |e,i|
swig_assert("#{e} == 0", binding, "for iv[#{i}] == 0")
}
0.upto(3) { |i| iv[i] = i }
{ "iv[-1]" => 3,
"iv.slice(0,2).to_s" => "01",
"iv.slice(1,2).to_s" => "12",
"iv[0,-2]" => nil,
"iv[0,3].to_s" => "012",
"iv[0,10].to_s" => "0123",
"iv[1..2].to_s" => '12',
"iv[1..3].to_s" => '123',
"iv[1..4].to_s" => '123',
"iv[1..-2].to_s" => '12',
"iv[2..-3].to_s" => '',
}.each do |k,v|
swig_assert( "#{k} == #{v.inspect}", binding )
end
swig_assert_each_line(<<'EOF', binding)
iv << 5
iv.push 5
iv.pop == 5
iv.unshift(7)
iv.shift == 7
iv.unshift(7, 3)
iv.insert(1,5)
iv.insert(0, 3)
iv.unshift(2,3,4)
x = average(iv)
y = average([1, 2, 3, 4])
half([10, 10.5, 11, 11.5])
EOF
iv = IntVector.new([0,1,2,3,4,5,6])
iv.delete_if { |x| x == 0 || x == 3 || x == 6 }
swig_assert_equal(iv.to_s, '1245', binding)
iv[1,2] = [-2, -4]
swig_assert_equal(iv.to_s, '1-2-45', binding)
iv = IntVector.new([0,1,2,3])
iv[0,1] = [-1, -2]
swig_assert_equal(iv.to_s, '-1-2123', binding)
iv = IntVector.new([1,2,3,4])
iv[1,3] = [6,7,8,9]
#__setitem__ needs fixing
#swig_assert_equal(iv.to_s, '16789', binding)
iv = IntVector.new([1,2,3,4])
swig_assert_equal(iv[0], 1, binding)
swig_assert_equal(iv[3], 4, binding)
swig_assert_equal(iv[4], nil, binding)
swig_assert_equal(iv[-5], nil, binding)
iv[-1] = 9
iv[-4] = 6
swig_assert_equal(iv.to_s, '6239', binding)
begin
iv[-5] = 99
raise "exception missed"
rescue IndexError
end
iv[6] = 5
swig_assert_equal(iv.to_s, '6239555', binding)
def failed(a, b, msg)
a = 'nil' if a == nil
b = 'nil' if b == nil
raise RuntimeError, "#{msg}: #{a} ... #{b}"
end
def compare_sequences(a, b)
if a != nil && b != nil
if a.size != b.size
failed(a, b, "different sizes")
end
for i in 0..a.size-1
failed(a, b, "elements are different") if a[i] != b[i]
end
else
unless a == nil && b == nil
failed(a, b, "only one of the sequences is nil")
end
end
end
def compare_expanded_sequences(a, b)
# a can contain nil elements which indicate additional elements
# b won't contain nil for additional elements
if a != nil && b != nil
if a.size != b.size
failed(a, b, "different sizes")
end
for i in 0..a.size-1
failed(a, b, "elements are different") if a[i] != b[i] && a[i] != nil
end
else
unless a == nil && b == nil
failed(a, b, "only one of the sequences is nil")
end
end
end
def check_slice(i, length)
aa = [1,2,3,4]
iv = IntVector.new(aa)
aa_slice = aa[i, length]
iv_slice = iv[i, length]
compare_sequences(aa_slice, iv_slice)
aa_slice = aa.slice(i, length)
iv_slice = iv.slice(i, length)
compare_sequences(aa_slice, iv_slice)
end
def check_range(i, j)
aa = [1,2,3,4]
iv = IntVector.new(aa)
aa_range = aa[i..j]
iv_range = iv[i..j]
compare_sequences(aa_range, iv_range)
aa_range = aa[Range.new(i, j, true)]
iv_range = iv[Range.new(i, j, true)]
compare_sequences(aa_range, iv_range)
end
def set_slice(i, length, expect_nil_expanded_elements)
aa = [1,2,3,4]
iv = IntVector.new(aa)
aa_new = [8, 9]
iv_new = IntVector.new(aa_new)
aa[i, length] = aa_new
iv[i, length] = iv_new
if expect_nil_expanded_elements
compare_expanded_sequences(aa, iv)
else
compare_sequences(aa, iv)
end
end
for i in -5..5
for length in -5..5
check_slice(i, length)
end
end
for i in -5..5
for j in -5..5
check_range(i, j)
end
end
for i in -4..4
for length in 0..4
set_slice(i, length, false)
end
end
for i in [5, 6]
for length in 0..5
set_slice(i, length, true)
end
end
dv = DoubleVector.new(10)
swig_assert( "dv.respond_to? :each_with_index", binding )
dv.each_with_index { |e,i| swig_assert_equal("dv[#{i}]", 0.0, binding) }
0.upto(9) { |i| dv[i] = i/2.0 }
{ "dv[-1]" => 4.5,
"dv.slice(0,2).to_s" => "0.00.5",
"dv[0,-2]" => nil,
"dv[0,3].to_s" => "0.00.51.0",
"dv[3,3].to_s" => "1.52.02.5",
}.each do |k,v|
swig_assert_equal( k, v.inspect, binding )
end
swig_assert_each_line(<<'EOF', binding)
dv.delete_at(2)
dv.delete_if { |x| x == 2.0 }
dv.include? 3.0
dv.find {|x| x == 3.0 }
dv.kind_of? DoubleVector
halved = []
halved = dv.map { |x| x / 2 }
halve_in_place(dv)
halved.to_a == dv.to_a
sv = StructVector.new
sv << Li_std_vector::Struct.new
sv[0].class == Li_std_vector::Struct
sv[1] = Li_std_vector::Struct.new
EOF
bv = BoolVector.new(2)
[true, false, true, true].each { |i| bv.push(i) }
0.upto(bv.size-1) { |i| bv[i] = !bv[i] }
bv_check = [true, true, false, true, false, false]
for i in 0..bv.size-1 do
swig_assert(bv_check[i] == bv[i], binding, "bv[#{i}]")
end
swig_assert_each_line(<<'EOF', binding)
lv = LanguageVector.new
lv << 1
lv << [1,2]
lv << 'asd'
lv[0], lv[1] = lv[1], lv[0]
EOF
# this should assert
begin
lv = LanguageVector.new('crapola')
rescue
end
# -*- coding: utf-8 -*-
require 'swig_assert'
require 'li_std_wstring_inherit'
x = "abc"
swig_assert_equal("Li_std_wstring_inherit.test_value(Li_std_wstring_inherit::Wstring.new(x))", "x", binding)
x = "y"
swig_assert_equal("Li_std_wstring_inherit.test_value(x)", "x", binding)
a = Li_std_wstring_inherit::A.new(x)
swig_assert_equal("Li_std_wstring_inherit.test_value(a)", "x", binding)
# -*- coding: utf-8 -*-
require 'swig_assert'
require 'li_std_wstring'
h = "h"
swig_assert_equal("Li_std_wstring.test_wcvalue(h)", "h", binding)
x = "abc"
swig_assert_equal("Li_std_wstring.test_ccvalue(x)", "x", binding)
swig_assert_equal("Li_std_wstring.test_cvalue(x)", "x", binding)
swig_assert_equal("Li_std_wstring.test_wchar_overload(x)", "x", binding)
swig_assert_equal("Li_std_wstring.test_wchar_overload()", "nil", binding)
Li_std_wstring.test_pointer(nil)
Li_std_wstring.test_const_pointer(nil)
begin
Li_std_wstring.test_value(nil)
raise RuntimeError, "NULL check failed"
rescue TypeError => e
end
begin
Li_std_wstring.test_reference(nil)
raise RuntimeError, "NULL check failed"
rescue ArgumentError => e
swig_assert_simple(e.message.include? "invalid null reference")
end
begin
Li_std_wstring.test_const_reference(nil)
raise RuntimeError, "NULL check failed"
rescue ArgumentError => e
swig_assert_simple(e.message.include? "invalid null reference")
end
x = "hello"
swig_assert_equal("Li_std_wstring.test_const_reference(x)", "x", binding)
s = "abc"
swig_assert("Li_std_wstring.test_equal_abc(s)", binding)
begin
Li_std_wstring.test_throw
rescue RuntimeError => e
swig_assert_equal("e.message", "'throwing test_throw'", binding)
end
x = "abc\0def"
swig_assert_equal("Li_std_wstring.test_value(x)", "x", binding)
swig_assert_equal("Li_std_wstring.test_ccvalue(x)", '"abc"', binding)
swig_assert_equal("Li_std_wstring.test_wchar_overload(x)", '"abc"', binding)
#!/usr/bin/env ruby
#
# Example using pointers to member functions
#
#
#
require 'swig_assert'
require 'member_pointer'
include Member_pointer
def check(what, expected, actual)
if not expected == actual
raise RuntimeError, "Failed: #{what} Expected: #{expected} Actual: #{actual}"
end
end
# Get the pointers
area_pt = Member_pointer::areapt
perim_pt = Member_pointer::perimeterpt
# Create some objects
s = Member_pointer::Square.new(10)
# Do some calculations
check "Square area ", 100.0, Member_pointer::do_op(s, area_pt)
check "Square perim", 40.0, Member_pointer::do_op(s, perim_pt)
memberPtr = Member_pointer::areavar
memberPtr = Member_pointer::perimetervar
# Try the variables
check "Square area ", 100.0, Member_pointer::do_op(s, Member_pointer::areavar)
check "Square perim", 40.0, Member_pointer::do_op(s, Member_pointer::perimetervar)
# Modify one of the variables
Member_pointer::areavar = perim_pt
check "Square perimeter", 40.0, Member_pointer::do_op(s, Member_pointer::areavar)
# Try the constants
memberPtr = Member_pointer::AREAPT
memberPtr = Member_pointer::PERIMPT
memberPtr = Member_pointer::NULLPT
check "Square area ", 100.0, Member_pointer::do_op(s, Member_pointer::AREAPT)
check "Square perim", 40.0, Member_pointer::do_op(s, Member_pointer::PERIMPT)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'minherit'
a = Minherit::Foo.new
b = Minherit::Bar.new
c = Minherit::FooBar.new
d = Minherit::Spam.new
if a.xget() != 1
raise RuntimeError, "Bad attribute value"
end
if b.yget() != 2
raise RuntimeError, "Bad attribute value"
end
if c.xget() != 1 or c.yget() != 2 or c.zget() != 3
raise RuntimeError, "Bad attribute value"
end
if d.xget() != 1 or d.yget() != 2 or d.zget() != 3 or d.wget() != 4
raise RuntimeError, "Bad attribute value"
end
if Minherit.xget(a) != 1
raise RuntimeError, "Bad attribute value #{Minherit.xget(a)}"
end
if Minherit.yget(b) != 2
raise RuntimeError, "Bad attribute value #{Minherit.yget(b)}"
end
if Minherit.xget(c) != 1 or Minherit.yget(c) != 2 or Minherit.zget(c) != 3
raise RuntimeError, "Bad attribute value #{Minherit.xget(c)} #{Minherit.yget(c)} #{Minherit.zget(c)}"
end
if Minherit.xget(d) != 1 or Minherit.yget(d) != 2 or Minherit.zget(d) != 3 or Minherit.wget(d) != 4
raise RuntimeError, "Bad attribute value #{Minherit.xget(d)} #{Minherit.yget(d)} #{Minherit.zget(d)} #{Minherit.wget(d)}"
end
# Cleanse all of the pointers and see what happens
aa = Minherit.toFooPtr(a)
bb = Minherit.toBarPtr(b)
cc = Minherit.toFooBarPtr(c)
dd = Minherit.toSpamPtr(d)
if aa.xget() != 1
raise RuntimeError, "Bad attribute value"
end
if bb.yget() != 2
raise RuntimeError, "Bad attribute value"
end
if cc.xget() != 1 or cc.yget() != 2 or cc.zget() != 3
raise RuntimeError, "Bad attribute value"
end
if dd.xget() != 1 or dd.yget() != 2 or dd.zget() != 3 or dd.wget() != 4
raise RuntimeError, "Bad attribute value"
end
if Minherit.xget(aa) != 1
raise RuntimeError, "Bad attribute value #{Minherit.xget(aa)}"
end
if Minherit.yget(bb) != 2
raise RuntimeError, "Bad attribute value #{Minherit.yget(bb)}"
end
if Minherit.xget(cc) != 1 or Minherit.yget(cc) != 2 or Minherit.zget(cc) != 3
raise RuntimeError, "Bad attribute value #{Minherit.xget(cc)} #{Minherit.yget(cc)} #{Minherit.zget(cc)}"
end
if Minherit.xget(dd) != 1 or Minherit.yget(dd) != 2 or Minherit.zget(dd) != 3 or Minherit.wget(dd) != 4
raise RuntimeError, "Bad attribute value #{Minherit.xget(dd)} #{Minherit.yget(dd)} #{Minherit.zget(dd)} #{Minherit.wget(dd)}"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'namespace_typemap'
include Namespace_typemap
raise RuntimeError if stest1("hello") != "hello"
raise RuntimeError if stest2("hello") != "hello"
raise RuntimeError if stest3("hello") != "hello"
raise RuntimeError if stest4("hello") != "hello"
raise RuntimeError if stest5("hello") != "hello"
raise RuntimeError if stest6("hello") != "hello"
raise RuntimeError if stest7("hello") != "hello"
raise RuntimeError if stest8("hello") != "hello"
raise RuntimeError if stest9("hello") != "hello"
raise RuntimeError if stest10("hello") != "hello"
raise RuntimeError if stest11("hello") != "hello"
raise RuntimeError if stest12("hello") != "hello"
begin
ttest1(-14)
raise RuntimeError
rescue RangeError
end
#!/usr/bin/env ruby
#
# Simple test of %newobject
# * The purpose of this test is to confirm that a language module
# * correctly handles the case when C++ class member functions (of both
# * the static and non-static persuasion) have been tagged with the
# * %newobject directive.
#
# Ruby's GC is somewhat broken in that it will mark some more stack space
# leading to the collection of local objects to be delayed.
# Thus, upon invocation, it sometimes you can wait up to several
# instructions to kick in.
# See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/7449
#
#
#
#
#
require 'swig_assert'
require 'swig_gc'
require 'newobject1'
include Newobject1
GC.track_class = Foo
GC.start
100.times { foo1 = Foo.makeFoo; foo2 = foo1.makeMore }
GC.stats if $VERBOSE
swig_assert( 'Foo.fooCount == 200', binding, "but is #{Foo.fooCount}" )
GC.start
swig_assert( 'Foo.fooCount <= 2', binding, "but is #{Foo.fooCount}" )
#!/usr/bin/env ruby
#
# Ruby's GC is somewhat broken in that it will mark some more stack space
# leading to the collection of local objects to be delayed.
# Thus, upon invocation, it sometimes you can wait up to several
# instructions to kick in.
# See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/7449
#
#
#
#
#
require 'swig_assert'
require 'swig_gc'
require 'newobject2'
include Newobject2
GC.track_class = Foo
GC.disable
GC.stats if $VERBOSE
100.times { foo1 = makeFoo }
GC.stats if $VERBOSE
swig_assert( 'fooCount == 100', nil, "but is #{fooCount}" )
GC.enable
GC.start
swig_assert( 'fooCount <= 1', nil, "but is #{fooCount}" )
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_bool'
include Overload_bool
# Overloading bool, int, string
if overloaded(true) != "bool"
raise RuntimeError, "wrong!"
end
if overloaded(false) != "bool"
raise RuntimeError, "wrong!"
end
if overloaded(0) != "int"
raise RuntimeError, "wrong!"
end
if overloaded(1) != "int"
raise RuntimeError, "wrong!"
end
if overloaded(2) != "int"
raise RuntimeError, "wrong!"
end
if overloaded("1234") != "string"
raise RuntimeError, "wrong!"
end
# Test bool masquerading as integer
# Not possible
# Test int masquerading as bool
if boolfunction(0) != "false"
raise RuntimeError, "wrong!"
end
if boolfunction(1) != "true"
raise RuntimeError, "wrong!"
end
if boolfunction(2) != "true"
raise RuntimeError, "wrong!"
end
#############################################
# Overloading bool, int, string
if overloaded_ref(true) != "bool"
raise RuntimeError, "wrong!"
end
if overloaded_ref(false) != "bool"
raise RuntimeError, "wrong!"
end
if overloaded_ref(0) != "int"
raise RuntimeError, "wrong!"
end
if overloaded_ref(1) != "int"
raise RuntimeError, "wrong!"
end
if overloaded_ref(2) != "int"
raise RuntimeError, "wrong!"
end
if overloaded_ref("1234") != "string"
raise RuntimeError, "wrong!"
end
# Test bool masquerading as integer
# Not possible
# Test int masquerading as bool
if boolfunction_ref(0) != "false"
raise RuntimeError, "wrong!"
end
if boolfunction_ref(1) != "true"
raise RuntimeError, "wrong!"
end
if boolfunction_ref(2) != "true"
raise RuntimeError, "wrong!"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_copy'
include Overload_copy
f = Foo.new
g = Foo.new(f)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_extend2'
f = Overload_extend2::Foo.new
raise RuntimeError if f.test(3) != 1
raise RuntimeError if f.test("hello") != 2
raise RuntimeError if f.test(3.5,2.5) != 3
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_extend_c'
f = Overload_extend_c::Foo.new
raise RuntimeError if f.test(3) != 1
raise RuntimeError if f.test("hello") != 2
raise RuntimeError if f.test(3.5,2.5) != 6
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_extend'
f = Overload_extend::Foo.new
raise RuntimeError if f.test(3) != 1
raise RuntimeError if f.test("hello") != 2
raise RuntimeError if f.test(3.5,2.5) != 6
#!/usr/bin/env ruby
#
# Put script description here.
#
#
#
#
#
require 'swig_assert'
require 'overload_null'
include Overload_null
o = Overload.new
x = X.new
swig_assert(1 == o.byval1(x))
swig_assert(2 == o.byval1(nil))
swig_assert(3 == o.byval2(nil))
swig_assert(4 == o.byval2(x))
swig_assert(5 == o.byref1(x))
swig_assert(6 == o.byref1(nil))
swig_assert(7 == o.byref2(nil))
swig_assert(8 == o.byref2(x))
swig_assert(9 == o.byconstref1(x))
swig_assert(10 == o.byconstref1(nil))
swig_assert(11 == o.byconstref2(nil))
swig_assert(12 == o.byconstref2(x))
# const pointer references
swig_assert(13 == o.byval1cpr(x))
swig_assert(14 == o.byval1cpr(nil))
swig_assert(15 == o.byval2cpr(nil))
swig_assert(16 == o.byval2cpr(x))
# forward class declaration
swig_assert(17 == o.byval1forwardptr(x))
swig_assert(18 == o.byval1forwardptr(nil))
swig_assert(19 == o.byval2forwardptr(nil))
swig_assert(20 == o.byval2forwardptr(x))
swig_assert(21 == o.byval1forwardref(x))
swig_assert(22 == o.byval2forwardref(x))
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_simple'
include Overload_simple
if foo(3) != "foo:int"
raise RuntimeError, "foo(int)"
end
if foo(3.0) != "foo:double"
raise RuntimeError, "foo(double)"
end
if foo("hello") != "foo:char *"
raise RuntimeError, "foo(char *)"
end
f = Foo.new
b = Bar.new
if foo(f) != "foo:Foo *"
raise RuntimeError, "foo(Foo *)"
end
if foo(b) != "foo:Bar *"
raise RuntimeError, "foo(Bar *)"
end
v = malloc_void(32)
if foo(v) != "foo:void *"
raise RuntimeError, "foo(void *)"
end
s = Spam.new
if s.foo(3) != "foo:int"
raise RuntimeError, "Spam::foo(int)"
end
if s.foo(3.0) != "foo:double"
raise RuntimeError, "Spam::foo(double)"
end
if s.foo("hello") != "foo:char *"
raise RuntimeError, "Spam::foo(char *)"
end
if s.foo(f) != "foo:Foo *"
raise RuntimeError, "Spam::foo(Foo *)"
end
if s.foo(b) != "foo:Bar *"
raise RuntimeError, "Spam::foo(Bar *)"
end
if s.foo(v) != "foo:void *"
raise RuntimeError, "Spam::foo(void *)"
end
if Spam.bar(3) != "bar:int"
raise RuntimeError, "Spam::bar(int)"
end
if Spam.bar(3.0) != "bar:double"
raise RuntimeError, "Spam::bar(double)"
end
if Spam.bar("hello") != "bar:char *"
raise RuntimeError, "Spam::bar(char *)"
end
if Spam.bar(f) != "bar:Foo *"
raise RuntimeError, "Spam::bar(Foo *)"
end
if Spam.bar(b) != "bar:Bar *"
raise RuntimeError, "Spam::bar(Bar *)"
end
if Spam.bar(v) != "bar:void *"
raise RuntimeError, "Spam::bar(void *)"
end
# Test constructors
s = Spam.new
if s.type != "none"
raise RuntimeError, "Spam()"
end
s = Spam.new(3)
if s.type != "int"
raise RuntimeError, "Spam(int)"
end
s = Spam.new(3.4)
if s.type != "double"
raise RuntimeError, "Spam(double)"
end
s = Spam.new("hello")
if s.type != "char *"
raise RuntimeError, "Spam(char *)"
end
s = Spam.new(f)
if s.type != "Foo *"
raise RuntimeError, "Spam(Foo *)"
end
s = Spam.new(b)
if s.type != "Bar *"
raise RuntimeError, "Spam(Bar *)"
end
s = Spam.new(v)
if s.type != "void *"
raise RuntimeError, "Spam(void *)"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_subtype'
include Overload_subtype
f = Foo.new
b = Bar.new
if spam(f) != 1
raise RuntimeError, "foo"
end
if spam(b) != 2
raise RuntimeError, "bar"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'overload_template'
f = Overload_template.foo()
a = Overload_template.maximum(3,4)
b = Overload_template.maximum(3.4,5.2)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'primitive_ref'
include Primitive_ref
raise RuntimeError if ref_int(3) != 3
raise RuntimeError if ref_uint(3) != 3
raise RuntimeError if ref_short(3) != 3
raise RuntimeError if ref_ushort(3) != 3
raise RuntimeError if ref_long(3) != 3
raise RuntimeError if ref_ulong(3) != 3
raise RuntimeError if ref_schar(3) != 3
raise RuntimeError if ref_uchar(3) != 3
raise RuntimeError if ref_float(3.5) != 3.5
raise RuntimeError if ref_double(3.5) != 3.5
raise RuntimeError if ref_bool(true) != true
raise RuntimeError if ref_char('x') != 'x'
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'primitive_types'
include Primitive_types
raise RuntimeError if val_uchar(255) != 255
fail = 0
begin
val_uchar(-1)
rescue RangeError
fail = 1
end
fail = 0
begin
val_uchar(256)
rescue RangeError
fail = 1
end
raise RuntimeError if fail != 1
fail = 0
begin
val_uchar(256.0)
rescue TypeError
fail = 1
end
raise RuntimeError if fail != 1
fail = 0
begin
val_uchar("caca")
rescue TypeError
fail = 1
end
raise RuntimeError if fail != 1
# Test a number which won't fit in a 32 bit integer and is represented
# as a FIXNUM by Ruby.
raise RuntimeError if val_double(51767811298) != 51767811298
raise RuntimeError if val_double_2(1.0) != 4.0
raise RuntimeError if val_double_2(1) != 4
raise RuntimeError if val_double_2(1,1) != 2
fail = 0
begin
val_double_2("1.0",1.0)
rescue
fail = 1
end
raise RuntimeError if fail != 1
fail = 0
begin
val_double_2(1.0,"1.0")
rescue
fail = 1
end
raise RuntimeError if fail != 1
raise RuntimeError if val_float_2(1.0) != 4.0
raise RuntimeError if val_float_2(1) != 4
raise RuntimeError if val_float_2(1,1) != 2
fail = 0
begin
val_float_2("1.0",1.0)
rescue
fail = 1
end
raise RuntimeError if fail != 1
fail = 0
begin
val_float_2(1.0,"1.0")
rescue
fail = 1
end
raise RuntimeError if fail != 1
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'profiletest'
a = Profiletest::A.new()
b = Profiletest::B.new()
for i in 0...1000000
a = b.fn(a)
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'refcount'
a = Refcount::A3.new;
b1 = Refcount::B.new a;
b2 = Refcount::B.new a;
if a.ref_count() != 3
print "This program will crash... now\n"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'reference_global_vars'
# primitive reference variables
Reference_global_vars.var_bool = Reference_global_vars.createref_bool(true)
if (Reference_global_vars.value_bool(Reference_global_vars.var_bool) != true)
print "Runtime error test 1\n"
exit 1
end
Reference_global_vars.var_bool = Reference_global_vars.createref_bool(false)
if (Reference_global_vars.value_bool(Reference_global_vars.var_bool) != false)
print "Runtime error test 2 \n"
exit 1
end
Reference_global_vars.var_char = Reference_global_vars.createref_char('w')
if (Reference_global_vars.value_char(Reference_global_vars.var_char) != 'w')
print "Runtime error test 3 \n"
exit 1
end
Reference_global_vars.var_unsigned_char = Reference_global_vars.createref_unsigned_char(10)
if (Reference_global_vars.value_unsigned_char(Reference_global_vars.var_unsigned_char) != 10)
print "Runtime error test 4 \n"
exit 1
end
Reference_global_vars.var_signed_char = Reference_global_vars.createref_signed_char(10)
if (Reference_global_vars.value_signed_char(Reference_global_vars.var_signed_char) != 10)
print "Runtime error test 5 \n"
exit 1
end
Reference_global_vars.var_short = Reference_global_vars.createref_short(10)
if (Reference_global_vars.value_short(Reference_global_vars.var_short) != 10)
print "Runtime error test 6 \n"
exit 1
end
Reference_global_vars.var_unsigned_short = Reference_global_vars.createref_unsigned_short(10)
if (Reference_global_vars.value_unsigned_short(Reference_global_vars.var_unsigned_short) != 10)
print "Runtime error test 7 \n"
exit 1
end
Reference_global_vars.var_int = Reference_global_vars.createref_int(10)
if (Reference_global_vars.value_int(Reference_global_vars.var_int) != 10)
print "Runtime error test 8 \n"
exit 1
end
Reference_global_vars.var_unsigned_int = Reference_global_vars.createref_unsigned_int(10)
if (Reference_global_vars.value_unsigned_int(Reference_global_vars.var_unsigned_int) != 10)
print "Runtime error test 9 \n"
exit 1
end
Reference_global_vars.var_long = Reference_global_vars.createref_long(10)
if (Reference_global_vars.value_long(Reference_global_vars.var_long) != 10)
print "Runtime error test 10 \n"
exit 1
end
Reference_global_vars.var_unsigned_long = Reference_global_vars.createref_unsigned_long(10)
if (Reference_global_vars.value_unsigned_long(Reference_global_vars.var_unsigned_long) != 10)
print "Runtime error test 11 \n"
exit 1
end
Reference_global_vars.var_long_long = Reference_global_vars.createref_long_long(10)
if (Reference_global_vars.value_long_long(Reference_global_vars.var_long_long) != 10)
print "Runtime error test 12 \n"
exit 1
end
Reference_global_vars.var_unsigned_long_long = Reference_global_vars.createref_unsigned_long_long(10)
if (Reference_global_vars.value_unsigned_long_long(Reference_global_vars.var_unsigned_long_long) != 10)
print "Runtime error test 13 \n"
exit 1
end
Reference_global_vars.var_float = Reference_global_vars.createref_float(10.5)
if (Reference_global_vars.value_float(Reference_global_vars.var_float) != 10.5)
print "Runtime error test 14 \n"
exit 1
end
Reference_global_vars.var_double = Reference_global_vars.createref_double(10.5)
if (Reference_global_vars.value_double(Reference_global_vars.var_double) != 10.5)
print "Runtime error test 15 \n"
exit 1
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'rename_scope'
include Rename_scope
a = Natural_UP.new
b = Natural_BP.new
raise RuntimeError if a.rtest() != 1
raise RuntimeError if b.rtest() != 1
#!/usr/bin/env ruby
#
# Runtime tests for ruby_alias_global_function.i
#
require 'swig_assert'
require 'ruby_alias_global_function'
expected_name = get_my_name
swig_assert(fullname == expected_name, msg: "nickname not working as expected")
swig_assert(nickname == expected_name, msg: "fullname not working as expected")
if method(:nickname).respond_to?(:original_name)
swig_assert_equal_simple(method(:nickname).original_name, :get_my_name)
swig_assert_equal_simple(method(:fullname).original_name, :get_my_name)
else
swig_assert(method(:nickname) == method(:get_my_name), msg: "nickname is not an alias of get_my_name")
swig_assert(method(:fullname) == method(:get_my_name), msg: "fullname is not an alias of get_my_name")
end
#!/usr/bin/env ruby
#
# Runtime tests for ruby_alias_method.i
#
require 'swig_assert'
require 'ruby_alias_method'
include Ruby_alias_method
expected_name = "Chester Tester"
syn = Synonym.new(expected_name)
swig_assert(syn.getMyName() == expected_name, msg: "getMyName not working as expected")
swig_assert(syn.nickname() == expected_name, msg: "nickname not working as expected")
swig_assert(syn.fullname() == expected_name, msg: "fullname not working as expected")
if syn.method(:nickname).respond_to?(:original_name)
swig_assert_equal_simple(syn.method(:nickname).original_name, :getMyName)
swig_assert_equal_simple(syn.method(:fullname).original_name, :getMyName)
else
swig_assert(syn.method(:nickname) == syn.method(:getMyName))
swig_assert(syn.method(:fullname) == syn.method(:getMyName))
end
#!/usr/bin/env ruby
#
# Runtime tests for ruby_alias_module_function.i
#
require 'swig_assert'
require 'ruby_alias_module_function'
include Ruby_alias_module_function
expected_name = Ruby_alias_module_function.get_my_name
swig_assert(Ruby_alias_module_function.nickname == expected_name, msg: "nickname returned a different result than get_my_name")
swig_assert(Ruby_alias_module_function.fullname == expected_name, msg: "fullname returned a different result than get_my_name")
nickname_method = Ruby_alias_module_function.method(:nickname)
fullname_method = Ruby_alias_module_function.method(:fullname)
if nickname_method.respond_to?(:original_name)
swig_assert_equal_simple(nickname_method.original_name, :get_my_name)
swig_assert_equal_simple(fullname_method.original_name, :get_my_name)
else
original_method = Ruby_alias_module_function.method(:get_my_name)
swig_assert(nickname_method == original_method, msg: "nickname is not an alias of get_my_name")
swig_assert(fullname_method == original_method, msg: "fullname is not an alias of get_my_name")
end
#!/usr/bin/env ruby
#
# C++ version of ruby_global_immutable_vars_runme.rb.
#
require 'swig_assert'
require 'ruby_global_immutable_vars_cpp'
# first check if all variables can be read
swig_assert_each_line( <<EOF )
$default_mutable_var == 40
$global_immutable_var == 41
$specific_mutable_var == 42
$global_mutable_var == 43
$specific_immutable_var == 44
EOF
# check that all mutable variables can be modified
swig_assert_each_line( <<EOF )
$default_mutable_var = 80
$default_mutable_var == 80
$specific_mutable_var = 82
$specific_mutable_var == 82
$global_mutable_var = 83
$global_mutable_var == 83
EOF
# now check that immutable variables cannot be modified
had_exception = false
begin
$global_immutable_var = 81
rescue NameError => e
had_exception = true
end
swig_assert(had_exception, nil,
"$global_immutable_var is writable (expected to be immutable)")
had_exception = false
begin
$specific_immutable_var = 81
rescue NameError => e
had_exception = true
end
swig_assert(had_exception, nil,
"$specific_immutable_var is writable (expected to be immutable)")
swig_assert(check_values(80, 41, 82, 83, 44) == 1, nil, "Check values failed")
#!/usr/bin/env ruby
#
# This test program is similar to global_immutable_vars_runme.rb
# with the difference that the global variables to check are also
# Ruby global variables (SWIG Ruby option "-globalmodule").
#
# Immutable global variables shall throw a NameError exception.
#
require 'swig_assert'
require 'ruby_global_immutable_vars'
# first check if all variables can be read
swig_assert_each_line( <<EOF )
$default_mutable_var == 40
$global_immutable_var == 41
$specific_mutable_var == 42
$global_mutable_var == 43
$specific_immutable_var == 44
EOF
# check that all mutable variables can be modified
swig_assert_each_line( <<EOF )
$default_mutable_var = 80
$default_mutable_var == 80
$specific_mutable_var = 82
$specific_mutable_var == 82
$global_mutable_var = 83
$global_mutable_var == 83
EOF
# now check that immutable variables cannot be modified
had_exception = false
begin
$global_immutable_var = 81
rescue NameError => e
had_exception = true
end
swig_assert(had_exception, nil,
"$global_immutable_var is writable (expected to be immutable)")
had_exception = false
begin
$specific_immutable_var = 81
rescue NameError => e
had_exception = true
end
swig_assert(had_exception, nil,
"$specific_immutable_var is writable (expected to be immutable)")
swig_assert(check_values(80, 41, 82, 83, 44) == 1, nil, "Check values failed")
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'ruby_keywords'
kw = Ruby_keywords::Keywords.new
if kw.alias != 'alias' then
raise RuntimeError, 'Keyword method did not work: alias'
end
if kw.and != 'and' then
raise RuntimeError, 'Keyword method did not work: and'
end
if kw.begin != 'begin' then
raise RuntimeError, 'Keyword method did not work: begin'
end
if kw.break != 'break' then
raise RuntimeError, 'Keyword method did not work: break'
end
if kw.case != 'case' then
raise RuntimeError, 'Keyword method did not work: case'
end
if kw.class != 'class' then
raise RuntimeError, 'Keyword method did not work: class'
end
if kw.def != 'def' then
raise RuntimeError, 'Keyword method did not work: def'
end
if kw.defined? != 'defined?' then
raise RuntimeError, 'Keyword method did not work: defined?'
end
if kw.do != 'do' then
raise RuntimeError, 'Keyword method did not work: do'
end
if kw.else != 'else' then
raise RuntimeError, 'Keyword method did not work: else'
end
if kw.elsif != 'elsif' then
raise RuntimeError, 'Keyword method did not work: elsif'
end
if kw.end != 'end' then
raise RuntimeError, 'Keyword method did not work: end'
end
if kw.ensure != 'ensure' then
raise RuntimeError, 'Keyword method did not work: ensure'
end
if kw.false != 'false' then
raise RuntimeError, 'Keyword method did not work: false'
end
if kw.for != 'for' then
raise RuntimeError, 'Keyword method did not work: for'
end
if kw.if != 'if' then
raise RuntimeError, 'Keyword method did not work: if'
end
if kw.in != 'in' then
raise RuntimeError, 'Keyword method did not work: in'
end
if kw.module != 'module' then
raise RuntimeError, 'Keyword method did not work: module'
end
if kw.next != 'next' then
raise RuntimeError, 'Keyword method did not work: next'
end
if kw.nil != 'nil' then
raise RuntimeError, 'Keyword method did not work: nil'
end
if kw.not != 'not' then
raise RuntimeError, 'Keyword method did not work: not'
end
if kw.or != 'or' then
raise RuntimeError, 'Keyword method did not work: or'
end
if kw.redo != 'redo' then
raise RuntimeError, 'Keyword method did not work: redo'
end
if kw.rescue != 'rescue' then
raise RuntimeError, 'Keyword method did not work: rescue'
end
if kw.retry != 'retry' then
raise RuntimeError, 'Keyword method did not work: retry'
end
if kw.return != 'return' then
raise RuntimeError, 'Keyword method did not work: return'
end
if kw.self != 'self' then
raise RuntimeError, 'Keyword method did not work: self'
end
if kw.super != 'super' then
raise RuntimeError, 'Keyword method did not work: super'
end
if kw.then != 'then' then
raise RuntimeError, 'Keyword method did not work: then'
end
if kw.true != 'true' then
raise RuntimeError, 'Keyword method did not work: true'
end
if kw.under != 'under' then
raise RuntimeError, 'Keyword method did not work: under'
end
if kw.unless != 'unless' then
raise RuntimeError, 'Keyword method did not work: unless'
end
if kw.until != 'until' then
raise RuntimeError, 'Keyword method did not work: until'
end
if kw.when != 'when' then
raise RuntimeError, 'Keyword method did not work: when'
end
if kw.while != 'while' then
raise RuntimeError, 'Keyword method did not work: while'
end
if kw.yield != 'yield' then
raise RuntimeError, 'Keyword method did not work: yield'
end
#!/usr/bin/env ruby
#
# This is a simple speed benchmark suite for std containers,
# to verify their O(n) performance.
# It is not part of the standard tests.
require 'benchmark'
require 'mathn'
require 'ruby_li_std_speed'
include Ruby_li_std_speed
def benchmark(f, phigh, sequences)
puts f
print '%10s' % 'n'
maxlen = sequences.max { |a,b| a.to_s.size <=> b.to_s.size }
maxlen = maxlen.to_s.size - 12
sequences.each { |s| print "%#{maxlen}s" % "#{s.to_s.sub(/.*::/,'')}" }
puts
o_perf = Array.new(sequences.size, 0)
last_t = Array.new(sequences.size, nil)
1.upto(phigh) do |p|
n = 2**(p-1)
print "%10d" % n
sequences.each_with_index do |s, i|
cont = s.new((0..n).to_a)
Benchmark.benchmark('',0,"%#{maxlen-2}.6r") { |x|
t = x.report { f.call(cont) }
o_perf[i] += last_t[i] ? (t.real / last_t[i]) : t.real
last_t[i] = t.real
}
end
puts
end
print " avg. O(n)"
base = 1.0 / Math.log(2.0)
sequences.each_with_index do |s, i|
o_perf[i] /= phigh
# o_perf[i] = 1 if o_perf[i] < 1
o_perf[i] = Math.log(o_perf[i]) * base
print "%#{maxlen-1}.2f " % o_perf[i]
end
puts
end
def iterate(cont)
it = cont.begin
last = cont.end
while it != last
it.next
end
end
def erase(cont)
it = cont.end
# can't reuse begin since it might get invalidated
while it != cont.begin
it.previous
# set returns None, so need to reobtain end
it = cont.erase(it) || cont.end
end
end
def insert(cont)
size = cont.size
size.upto((size<<1) - 1) { |x| cont.push(x) }
end
if $0 == __FILE__
GC.disable
sequences = [RbVector,RbDeque,RbSet,RbList,
RbFloatVector,RbFloatDeque,RbFloatSet,RbFloatList]
n = 17
for f,phigh in [[method(:iterate),n], [method(:insert),n],
[method(:erase),n-4]]
benchmark(f, phigh, sequences)
end
end
#!/usr/bin/env ruby
#
# The Subversion bindings use this manually written proxy class approach
# to the Ruby bindings. Note that in C the struct svn_fs_t is an
# opaque pointer and the Ruby FileSystem proxy class is hand written around it.
# This testcase tests this and the C close function and subsequent error
# handling.
require 'swig_assert'
require 'ruby_manual_proxy'
module Svn
module Fs
module_function
def create(path)
f = Ruby_manual_proxy::svn_fs_create(path)
return f
end
FileSystem = SWIG::TYPE_p_svn_fs_t
class FileSystem
class << self
def create(*args)
Fs.create(*args)
end
end
def path
Ruby_manual_proxy::svn_fs_path(self)
end
end
end
end
f = Svn::Fs::FileSystem.create("/tmp/myfile")
path = f.path
f.close
begin
# regression in swig-3.0.8 meant ObjectPreviouslyDeleted error was thrown instead
path = f.path
raise RuntimeError.new("IOError (1) not thrown")
rescue IOError
end
file = nil
begin
path = Ruby_manual_proxy::svn_fs_path(file)
raise RuntimeError.new("IOError (2) not thrown")
rescue IOError
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'ruby_minherit_shared_ptr'
md = Ruby_minherit_shared_ptr::MultiDerived.new(11, 22)
if md.Base1Func != 11 then
raise RuntimeError
end
if md.Interface1Func != 22 then
raise RuntimeError
end
if Ruby_minherit_shared_ptr.BaseCheck(md) != 11 then
raise RuntimeError
end
if Ruby_minherit_shared_ptr.InterfaceCheck(md) != 22 then
raise RuntimeError
end
if Ruby_minherit_shared_ptr.DerivedCheck(md) != 33 then
raise RuntimeError
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'ruby_naming'
# Check class names
if not Ruby_naming
raise RuntimeError, 'Invalid module name for Ruby_naming'
end
if not Ruby_naming::MyClass
raise RuntimeError, 'Invalid class name for MyClass'
end
# Check constant names / values
if Ruby_naming::CONSTANT1 != 1
raise RuntimeError, "Incorrect value for CONSTANT1"
end
if Ruby_naming::CONSTANT2 != 2
raise RuntimeError, "Incorrect value for CONSTANT2"
end
# Check constant names / values
if Ruby_naming::CONSTANT3 != 3
raise RuntimeError, "Incorrect value for CONSTANT3"
end
if not (Ruby_naming::methods.include?("constant4") || Ruby_naming::methods.include?(:constant4))
raise RuntimeError, "Incorrect mapping for constant4"
end
if not (Ruby_naming::methods.include?("constant5") || Ruby_naming::methods.include?(:constant5))
raise RuntimeError, "Incorrect mapping for constant5"
end
if not (Ruby_naming::methods.include?("constant6") || Ruby_naming::methods.include?(:constant6))
raise RuntimeError, "Incorrect mapping for constant6"
end
if not (Ruby_naming::TestConstants.instance_methods.include?("constant7") || Ruby_naming::TestConstants.instance_methods.include?(:constant7))
raise RuntimeError, "Incorrect mapping for constant7"
end
if not (Ruby_naming::TestConstants.methods.include?("constant8") || Ruby_naming::TestConstants.methods.include?(:constant8))
raise RuntimeError, "Incorrect mapping for constant8"
end
# There is no constant9 because it is illegal C++
#if not Ruby_naming::TestConstants.instance_methods.include?("constant9")
# raise RuntimeError, "Incorrect mapping for constant9"
#end
if Ruby_naming::TestConstants::CONSTANT10 != 10
raise RuntimeError, "Incorrect value for CONSTANT10"
end
if not (Ruby_naming::methods.include?("constant11") || Ruby_naming::methods.include?(:constant11))
raise RuntimeError, "Incorrect mapping for constant11"
end
# Check enums
if Ruby_naming::constants.include?("Color")
raise RuntimeError, "Color enum should not be exposed to Ruby"
end
if Ruby_naming::Red != 0
raise RuntimeError, "Incorrect value for enum RED"
end
if Ruby_naming::Green != 1
raise RuntimeError, "Incorrect value for enum GREEN"
end
if Ruby_naming::Blue != 2
raise RuntimeError, "Incorrect value for enum BLUE"
end
# Check method names
my_class = Ruby_naming::MyClass.new()
if my_class.method_one != 1
raise RuntimeError, "Incorrect value for method_one"
end
if my_class.method_two != 2
raise RuntimeError, "Incorrect value for method_two"
end
if my_class.method_three != 3
raise RuntimeError, "Incorrect value for method_three"
end
if my_class.method_44_4 != 4
raise RuntimeError, "Incorrect value for method_44_4"
end
if my_class.predicate_method? != true
raise RuntimeError, "Incorrect value for predicate_method?"
end
if my_class.bang_method! != true
raise RuntimeError, "Incorrect value for bang_method!"
end
require 'swig_assert'
require 'ruby_rdata'
include Ruby_rdata
swig_assert_equal_simple(1, take_proc_or_cpp_obj_and_ret_1(Proc.new{}))
swig_assert_equal_simple(1, take_proc_or_cpp_obj_and_ret_1(C.new))
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'ruby_track_objects_directors'
class MyFoo < Ruby_track_objects_directors::Foo
def ping
"MyFoo::ping()"
end
end
a = MyFoo.new
raise RuntimeError if a.ping != "MyFoo::ping()"
raise RuntimeError if a.pong != "Foo::pong();MyFoo::ping()"
b = Ruby_track_objects_directors::Foo.new
raise RuntimeError if b.ping != "Foo::ping()"
raise RuntimeError if b.pong != "Foo::pong();Foo::ping()"
container = Ruby_track_objects_directors::Container.new
foo = MyFoo.new
container.set_foo(foo)
myFoo1 = container.get_foo
myFoo2 = container.get_foo
if not myFoo1.equal?(myFoo2)
raise RuntimeError, "MyFoo's should be the same"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'ruby_track_objects'
def test_same_ruby_object(foo1, foo2)
if not foo1.equal?(foo2)
raise "Ruby objects should be the same."
end
end
def test_same_cpp_object(foo1, foo2)
if not foo1.cpp_equal(foo2)
raise "C++ objects should be the same"
end
end
bar = Ruby_track_objects::Bar.new
foo1 = Ruby_track_objects::Foo.new()
bar.set_unowned_foo(foo1)
# test_simple_identity
foo2 = Ruby_track_objects::Foo.new()
foo3 = foo2
test_same_ruby_object(foo2, foo3)
test_same_cpp_object(foo2, foo3)
# test_unowned_foo_identity
foo4 = bar.get_unowned_foo()
test_same_ruby_object(foo1, foo4)
test_same_cpp_object(foo1, foo4)
# test_owned_foo_identity
foo5 = bar.get_owned_foo()
foo6 = bar.get_owned_foo()
test_same_ruby_object(foo5, foo6)
test_same_cpp_object(foo5, foo6)
# test_new_foo_identity
foo7 = Ruby_track_objects::Bar.get_new_foo()
foo8 = Ruby_track_objects::Bar.get_new_foo()
if foo7.equal?(foo8)
raise "Ruby objects should be different."
end
if foo7.cpp_equal(foo8)
raise "C++ objects should be different."
end
# test_set_owned_identity
foo9 = Ruby_track_objects::Foo.new
bar.set_owned_foo(foo9)
foo10 = bar.get_owned_foo()
test_same_ruby_object(foo9, foo10)
test_same_cpp_object(foo9, foo10)
# test_set_owned_identity2
begin
foo11 = Ruby_track_objects::Foo.new
bar.set_owned_foo(foo11)
foo11 = nil
end
GC.start
foo12 = bar.get_owned_foo()
if not (foo12.say_hello == "Hello")
raise "Invalid C++ object returned."
end
# test_set_owned_identity3
foo13 = bar.get_owned_foo_by_argument()
foo14 = bar.get_owned_foo_by_argument()
test_same_ruby_object(foo13, foo14)
test_same_cpp_object(foo13, foo14)
# Now create the factory
factory = Ruby_track_objects::Factory.new
# Create itemA which is really an itemB
itemA = factory.createItem
# Check class
if itemA.class != Ruby_track_objects::ItemA
raise RuntimeError, 'Item should have an ItemA class'
end
# Now downcast
itemB = Ruby_track_objects.downcast(itemA)
if itemB.class != Ruby_track_objects::ItemB
raise RuntimeError, 'Item should have an ItemB class'
end
if itemA.eql?(itemB)
raise RuntimeError, 'Items should be different'
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_const'
include Smart_pointer_const
f = Foo.new
b = Bar.new(f)
b.x = 3
raise RuntimeError if b.getx() != 3
fp = b.__deref__()
fp.x = 4
raise RuntimeError if fp.getx() != 4
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_multi'
include Smart_pointer_multi
f = Foo.new
b = Bar.new(f)
s = Spam.new(b)
g = Grok.new(b)
s.x = 3
raise RuntimeError if s.getx() != 3
g.x = 4
raise RuntimeError if g.getx() != 4
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_multi_typedef'
include Smart_pointer_multi_typedef
f = Foo.new
b = Bar.new(f)
s = Spam.new(b)
g = Grok.new(b)
s.x = 3
raise RuntimeError if s.getx() != 3
g.x = 4
raise RuntimeError if g.getx() != 4
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_not'
include Smart_pointer_not
f = Foo.new
b = Bar.new(f)
s = Spam.new(f)
g = Grok.new(f)
begin
x = b.x
puts "Error! b.x"
rescue NameError
end
begin
x = s.x
puts "Error! s.x"
rescue NameError
end
begin
x = g.x
puts "Error! g.x"
rescue NameError
end
begin
x = b.getx()
puts "Error! b.getx()"
rescue NameError
end
begin
x = s.getx()
puts "Error! s.getx()"
rescue NameError
end
begin
x = g.getx()
puts "Error! g.getx()"
rescue NameError
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_overload'
include Smart_pointer_overload
f = Foo.new
b = Bar.new(f)
raise RuntimeError if f.test(3) != 1
raise RuntimeError if f.test(3.5) != 2
raise RuntimeError if f.test("hello") != 3
raise RuntimeError if b.test(3) != 1
raise RuntimeError if b.test(3.5) != 2
raise RuntimeError if b.test("hello") != 3
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_rename'
include Smart_pointer_rename
f = Foo.new
b = Bar.new(f)
raise RuntimeError if b.test() != 3
raise RuntimeError if b.ftest1(1) != 1
raise RuntimeError if b.ftest2(2,3) != 2
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_simple'
include Smart_pointer_simple
f = Foo.new
b = Bar.new(f)
b.x = 3
raise RuntimeError if b.getx() != 3
fp = b.__deref__()
fp.x = 4
raise RuntimeError if fp.getx() != 4
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'smart_pointer_typedef'
include Smart_pointer_typedef
f = Foo.new
b = Bar.new(f)
b.x = 3
raise RuntimeError if b.getx() != 3
fp = b.__deref__()
fp.x = 4
raise RuntimeError if fp.getx() != 4
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'sneaky1'
x = Sneaky1.add(3, 4)
y = Sneaky1.subtract(3, 4)
z = Sneaky1.mul(3, 4)
w = Sneaky1.divide(3, 4)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'static_const_member_2'
include Static_const_member_2
c = Test_int.new
a = Test_int::Forward_field # should be available as a class constant
a = Test_int::Current_profile # should be available as a class constant
a = Test_int::RightIndex # should be available as a class constant
a = Test_int::Backward_field # should be available as a class constant
a = Test_int::LeftIndex # should be available as a class constant
a = Test_int.cavity_flags
#!/usr/bin/env ruby
#
# Standard containers test suite. Tests:
# std::complex, std::vector, std::set and std::map,
# and IN/OUT functions for them.
#
#
#
#
#
require 'swig_assert'
require 'std_containers'
include Std_containers
swig_assert_equal("[true, false]", "videntb([true, false])")
swig_assert_each_line(<<'EOF', binding)
cube = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
icube = cident(cube)
icube.each_index { |i| swig_assert_equal("cube[#{i}]","icube[#{i}]", binding, 'cident') }
p = [1,2]
p == pident(p)
v = [1,2,3,4,5,6]
iv = vident(v)
iv.each_index { |i| swig_assert_equal("iv[#{i}]","v[#{i}]", binding, 'vident') }
iv = videntu(v)
iv.each_index { |i| swig_assert_equal("iv[#{i}]","v[#{i}]", binding, 'videntu') }
vu = Vector_ui.new(v)
vu[2] == videntu(vu)[2]
v[0,3][1] == vu[0,3][1]
m = [[1,2,3],[2,3],[3,4]]
im = midenti(m)
0.upto(m.size-1){ |i| 0.upto(m[i].size-1) { |j| swig_assert_equal("m[#{i}][#{j}]","im[#{i}][#{j}]", binding, 'getslice') } }
m = [[1,0,1],[1,1],[1,1]]
im = midentb(m)
0.upto(m.size-1){ |i| 0.upto(m[i].size-1) { |j| swig_assert_equal("(m[#{i}][#{j}]==1)","im[#{i}][#{j}]", binding, 'getslice') } }
mi = Imatrix.new(m)
mc = Cmatrix.new(m)
mi[0][0] == mc[0][0] # or bad matrix
map ={}
map['hello'] = 1
map['hi'] = 2
map['3'] = 2
imap = Std_containers.mapident(map)
map.each_key { |k| swig_assert_equal("map['#{k}']", "imap['#{k}']", binding) }
mapc ={}
c1 = C.new
c2 = C.new
mapc[1] = c1
mapc[2] = c2
mapidentc(mapc)
vi = Vector_i.new([2,2,3,4])
v1 = vi.dup
v1.class == vi.class
v1 != vi
v1.object_id != vi.object_id
v = [1,2]
v1 = v_inout(vi)
vi[1] == v1[1]
# vi.class == v1.class # only if SWIG_RUBY_EXTRA_NATIVE_CONTAINERS was set
v1,v2 = [[1,2],[3,4]]
v1,v2 = v_inout2(v1,v2)
v2 == [1,2]
v1 == [3,4]
a1 = A.new(1)
a2 = A.new(2)
p1 = [1,a1]
p2 = [2,a2]
v = [p1,p2]
v2 = pia_vident(v)
# v2[0][1].a
# v2[1][1].a
# v3 = Std_containers.vector_piA(v2)
# v3[0][1].a
# v3[1][1].a
s = Set_i.new
s.push(1)
s.push(2)
s.push(3)
j = 1
s.each { |i| swig_assert_equal("#{i}","#{j}", binding, "for s[#{i}]"); j += 1 }
EOF
#!/usr/bin/env ruby
#
# This is a test of STL containers, iterators and using proc
# objects to change the sorting function used in them. Same as a
# std::binary_predicate in C++.
#
#
#
#
#
require 'swig_assert'
require 'stl_new'
def _sequence(container)
swig_assert_each_line(<<'EOF', binding)
cont = container.new([9,1,8,2,7,3,6,4,5])
cont.to_a == [9,1,8,2,7,3,6,4,5]
cont.size == 9
i = cont.begin
i.class == Stl_new::Iterator
cont.end - cont.begin == cont.size
cont.begin.value == 9
(cont.end-1).value == 5
cont[0],cont[1] = cont[1],cont[0]
cont.to_a == [1,9,8,2,7,3,6,4,5]
i0 = cont.begin
i1 = i0+1
tmp = i0.value # tmp = 1
tmp == 1
i0.value = i1.value # elem[0] = 9
i1.value = tmp # elem[1] = 1
cont.to_a == [9,1,8,2,7,3,6,4,5]
i0 += 8
prev = i0.value
i0 -= 8
cur = i0.value
i0.value = prev
prev = cur
i0 += 8
cur = i0.value
i0.value = prev
cont.to_a == [5,1,8,2,7,3,6,4,9]
i0 == cont.end-1
i0 != cont.end
EOF
end
def _random_iterator(container)
swig_assert_each_line(<<EOF, binding)
cont = #{container}.new([9,1,8,2,7,3,6,4,5])
Stl_new.nth_element(cont.begin,cont.begin+cont.size/2,cont.end)
cont.to_a == [3, 1, 2, 4, 5, 6, 7, 8, 9]
Stl_new.nth_element(cont.begin,cont.begin+1,cont.end, proc { |a,b| b<a } )
cont.to_a == [9, 8, 7, 6, 5, 4, 2, 1, 3]
EOF
end
def _set(container)
swig_assert_each_line(<<EOF, binding)
cont = #{container}.new
[9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
i0 = cont.begin()
cont.to_a == [1,2,3,4,5,6,7,8,9]
cont = #{container}.new( proc { |a,b| b < a } )
[9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
cont.to_a == [9, 8, 7, 6, 5, 4, 3, 2, 1]
cont = #{container}.new( proc { |a,b| b > a } )
[9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
cont.to_a == [1, 2, 3, 4, 5, 6, 7, 8, 9]
cont = #{container}.new(proc { |a,b| b < a } )
cont.insert(1)
cont.to_a == [1]
i0 = cont.begin()
cont.erase(i0) # don't use i0 anymore, it is invalid now
cont.to_a == []
EOF
end
def _map(container)
swig_assert_each_line(<<EOF, binding)
cont = #{container}.new
cont['z'] = 9
cont['y'] = 1
cont['x'] = 8
cont['w'] = 2
cont.to_a == [['w',2],['x',8],['y',1],['z',9]]
cont = #{container}.new(proc { |a,b| b < a } )
cont['z'] = 9
cont['y'] = 1
cont['x'] = 8
cont['w'] = 2
cont.to_a == [['z',9],['y',1],['x',8],['w',2]]
#cont.iterator.to_a == [['w',2],['x',8],['y',1],['z',9]]
EOF
end
def test
for container in [Stl_new::Vector, Stl_new::Deque, Stl_new::List]
yield method(:_sequence), container
end
yield method(:_set), Stl_new::Set
yield method(:_map), Stl_new::Map
# for container in [Stl_new::Vector, Stl_new::Deque]
# yield method(:_random_iterator), container
# end
end
test do |proc, container|
proc.call(container)
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'struct_value'
b = Struct_value::Bar.new
b.a.x = 3
raise RuntimeError if b.a.x != 3
b.b.x = 3
raise RuntimeError if b.b.x != 3
#!/usr/bin/env ruby
#
# Useful assert functions
#
#
# Exception raised when some swig binding test fails
#
class SwigRubyError < RuntimeError
end
#
# Simple assertions. Strings are not needed as arguments.
#
def swig_assert_equal_simple(a, b)
unless a == b
raise SwigRubyError.new("\n#{a} expected but was \n#{b}")
end
end
def swig_assert_simple(a)
unless a
raise SwigRubyError.new("assertion failed.")
end
end
#
# Asserts whether a and b are equal.
#
# scope - optional Binding where to run the code
# msg - optional additional message to print
#
def swig_assert_equal( a, b, scope = nil, msg = nil )
a = 'nil' if a == nil
b = 'nil' if b == nil
begin
check = "#{a} == #{b}"
if scope.kind_of? Binding
ok = eval(check.to_s, scope)
else
ok = eval(check.to_s)
if !msg
msg = scope
scope = nil
end
end
rescue => e
raise
end
unless ok
valA = eval(a, scope)
valB = eval(b, scope)
raise SwigRubyError.new("FAILED EQUALITY: #{check} was #{valA} not #{valB}")
end
if $VERBOSE
$stdout.puts "\tPASSED EQUALITY #{check} #{msg}"
end
return ok
rescue => e
trace = e.backtrace[1..-1]
$stderr.puts "#{trace[0,1]}: #{e}"
if trace.size > 1
$stderr.puts "\tfrom #{trace[1..-1].join("\n\t ")}"
end
exit(1)
end
#
# Asserts whether an expression runs properly and is true
#
# scope - optional Binding where to run the code
# msg - optional additional message to print
#
def swig_assert( expr, scope = nil, msg = nil )
begin
if scope.kind_of? Binding
ok = eval(expr.to_s, scope)
else
ok = eval(expr.to_s)
msg = scope if !msg
end
rescue
raise
end
raise SwigRubyError.new("FAILED: #{expr.to_s} - #{msg}") unless ok
if $VERBOSE
$stdout.puts "\tPASSED #{expr} #{msg}"
end
rescue => e
trace = e.backtrace[1..-1]
$stderr.puts "#{trace[0,1]}: #{e}"
if trace.size > 1
$stderr.puts "\tfrom #{trace[1..-1].join("\n\t ")}"
end
exit(1)
end
#
# Asserts whether an expression runs properly
#
# scope - optional Binding where to run the code
# msg - optional additional message to print
#
def swig_eval( expr, scope = nil, msg = nil )
begin
if scope.kind_of? Binding
eval(expr.to_s, scope)
else
eval(expr.to_s)
msg = scope if !msg
end
rescue => e
raise SwigRubyError.new("Wrong assert: #{expr.to_s} - #{e}")
end
if $VERBOSE
$stdout.puts "\tPASSED #{expr} #{msg}"
end
rescue => e
trace = e.backtrace[1..-1]
$stderr.puts "#{trace[0,1]}: #{e}"
if trace.size > 1
$stderr.puts "\tfrom #{trace[1..-1].join("\n\t ")}"
end
exit(1)
end
#
# Given a set of lines as text, runs each of them, asserting them.
# Lines that are of the form:
# a == b are run with swig_assert_equal
# others are run with swig_eval.
#
# scope - optional Binding where to run the code
# msg - optional additional message to print
#
def swig_assert_each_line( lines, scope = nil, msg = nil )
lines.split("\n").each do |line|
next if line.empty? or line =~ /^\s*#.*/
if line =~ /^\s*([^\s]*)\s*==\s*(.*)\s*$/
swig_assert_equal($1, $2, scope, msg)
else
swig_eval(line, scope, msg)
end
end
end
#!/usr/bin/env ruby
#
#
# VERY nice function from Robert Klemme to check memory leaks
# and check on what GC has collected since last call.
#
# Usage can be:
#
# require 'swig_gc'
#
# GC.stats
# # do some stuff..
# GC.start # collect and report stats
# # do some more...
# GC.stats # just report stats
#
# or:
#
# require 'swig_gc'
#
# GC.track_class = String # track just String classes
# GC.stats
# # do some stuff..
# GC.start # collect and report stats
# # do some more...
# GC.stats # just report stats
#
#
#
#
#
module GC
class << self
attr :last_stat
attr_accessor :track_class
alias :_start :start
def start
_start
stats if $VERBOSE
end
def stats
stats = Hash.new(0)
ObjectSpace.each_object {|o| stats[o.class] += 1}
if track_class
v = stats[track_class]
printf "\t%-30s %10d", track_class.to_s, v
if last_stat
printf " | delta %10d", (v - last_stat[track_class])
end
puts
else
stats.sort {|(k1,v1),(k2,v2)| v2 <=> v1}.each do |k,v|
printf "\t%-30s %10d", k, v
printf " | delta %10d", (v - last_stat[k]) if last_stat
puts
end
end
last_stat = stats
end
end
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_construct'
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_extend1'
a = Template_extend1::LBaz.new
b = Template_extend1::DBaz.new
raise RuntimeError unless a.foo() == "lBaz::foo"
raise RuntimeError unless b.foo() == "dBaz::foo"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_extend2'
a = Template_extend2::LBaz.new
b = Template_extend2::DBaz.new
raise RuntimeError unless a.foo() == "lBaz::foo"
raise RuntimeError unless b.foo() == "dBaz::foo"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_inherit'
include Template_inherit
a = FooInt.new
b = FooDouble.new
c = BarInt.new
d = BarDouble.new
e = FooUInt.new
f = BarUInt.new
raise ValueError if a.blah() != "Foo"
raise ValueError if b.blah() != "Foo"
raise ValueError if e.blah() != "Foo"
raise ValueError if c.blah() != "Bar"
raise ValueError if d.blah() != "Bar"
raise ValueError if f.blah() != "Bar"
raise ValueError if c.foomethod() != "foomethod"
raise ValueError if d.foomethod() != "foomethod"
raise ValueError if f.foomethod() != "foomethod"
raise ValueError if invoke_blah_int(a) != "Foo"
raise ValueError if invoke_blah_int(c) != "Bar"
raise ValueError if invoke_blah_double(b) != "Foo"
raise ValueError if invoke_blah_double(d) != "Bar"
raise ValueError if invoke_blah_uint(e) != "Foo"
raise ValueError if invoke_blah_uint(f) != "Bar"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_ns4'
d = Template_ns4.make_Class_DD()
raise RuntimeError if d.test() != "test"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_ns'
include Template_ns
p1 = Pairii.new(2, 3)
p2 = Pairii.new(p1)
raise RuntimeError if p2.first != 2
raise RuntimeError if p2.second != 3
p3 = Pairdd.new(3.5, 2.5)
p4 = Pairdd.new(p3)
raise RuntimeError if p4.first != 3.5
raise RuntimeError if p4.second != 2.5
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_rename'
i = Template_rename::IFoo.new
d = Template_rename::DFoo.new
a = i.blah_test(4)
b = i.spam_test(5)
c = i.groki_test(6)
x = d.blah_test(7)
y = d.spam(8)
z = d.grok_test(9)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_tbase_template'
include Template_tbase_template
a = make_Class_dd()
raise RuntimeError unless a.test() == "test"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_typedef_cplx2'
include Template_typedef_cplx2
#
# double case
#
d = make_Identity_double()
raise RuntimeError, "#{d} is not an instance" if d.is_a? SWIG::Pointer
classname = d.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{d} is not an ArithUnaryFunction"
end
e = make_Multiplies_double_double_double_double(d, d)
raise RuntimeError, "#{e} is not an instance" if e.is_a? SWIG::Pointer
classname = e.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{e} is not an ArithUnaryFunction"
end
#
# complex case
#
c = make_Identity_complex()
raise RuntimeError, "#{c}is not an instance" if c.is_a? SWIG::Pointer
classname = c.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{c} is not an ArithUnaryFunction"
end
f = make_Multiplies_complex_complex_complex_complex(c, c)
raise RuntimeError, "{f} is not an instance" if f.is_a? SWIG::Pointer
classname = f.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{f} is not an ArithUnaryFunction"
end
#
# Mix case
#
g = make_Multiplies_double_double_complex_complex(d, c)
raise RuntimeError, "#{g} is not an instance" if g.is_a? SWIG::Pointer
classname = g.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{g} is not an ArithUnaryFunction"
end
# This should raise NoMethodError if it fails
g.get_value()
h = make_Multiplies_complex_complex_double_double(c, d)
raise RuntimeError, "#{h} is not an instance" if h.is_a? SWIG::Pointer
classname = h.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{h} is not an ArithUnaryFunction"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_typedef_cplx3'
include Template_typedef_cplx3
#
# this is OK
#
s = Sin.new
s.get_base_value()
s.get_value()
s.get_arith_value()
my_func_r(s)
make_Multiplies_double_double_double_double(s,s)
z = CSin.new
z.get_base_value()
z.get_value()
z.get_arith_value()
my_func_c(z)
make_Multiplies_complex_complex_complex_complex(z,z)
#
# Here we fail
#
d = make_Identity_double()
my_func_r(d)
c = make_Identity_complex()
my_func_c(c)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_typedef_cplx4'
include Template_typedef_cplx4
#
# this is OK
#
s = Sin.new
s.get_base_value()
s.get_value()
s.get_arith_value()
my_func_r(s)
make_Multiplies_double_double_double_double(s,s)
z = CSin.new
z.get_base_value()
z.get_value()
z.get_arith_value()
my_func_c(z)
make_Multiplies_complex_complex_complex_complex(z,z)
#
# Here we fail
#
d = make_Identity_double()
my_func_r(d)
c = make_Identity_complex()
my_func_c(c)
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_typedef_cplx'
include Template_typedef_cplx
#
# double case
#
d = make_Identity_double()
raise RuntimeError, "#{d} is not an instance" if d.is_a? SWIG::Pointer
classname = d.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{d} is not an ArithUnaryFunction"
end
e = make_Multiplies_double_double_double_double(d, d)
raise RuntimeError, "#{e} is not an instance" if e.is_a? SWIG::Pointer
classname = e.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{e} is not an ArithUnaryFunction"
end
#
# complex case
#
c = make_Identity_complex()
raise RuntimeError, "#{c}is not an instance" if c.is_a? SWIG::Pointer
classname = c.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{c} is not an ArithUnaryFunction"
end
f = make_Multiplies_complex_complex_complex_complex(c, c)
raise RuntimeError, "{f} is not an instance" if f.is_a? SWIG::Pointer
classname = f.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{f} is not an ArithUnaryFunction"
end
#
# Mix case
#
g = make_Multiplies_double_double_complex_complex(d, c)
raise RuntimeError, "#{g} is not an instance" if g.is_a? SWIG::Pointer
classname = g.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{g} is not an ArithUnaryFunction"
end
h = make_Multiplies_complex_complex_double_double(c, d)
raise RuntimeError, "#{h} is not an instance" if h.is_a? SWIG::Pointer
classname = h.class.name.split(/::/).last
unless classname =~ /ArithUnaryFunction/
raise RuntimeError, "#{h} is not an ArithUnaryFunction"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'template_type_namespace'
include Template_type_namespace
result = foo()
raise RuntimeError unless result[0].is_a? String
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'throw_exception'
include Throw_exception
foo = Foo.new
begin
foo.test_int
rescue => ex
raise RuntimeError if ex.message != "37"
end
begin
foo.test_msg
rescue => ex
raise RuntimeError if ex.message != "Dead"
end
begin
foo.test_multi(1)
rescue => ex
raise RuntimeError if ex.message != "37"
end
begin
foo.test_multi(2)
rescue => ex
raise RuntimeError if ex.message != "Dead"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'typedef_inherit'
a = Typedef_inherit::Foo.new
b = Typedef_inherit::Bar.new
x = Typedef_inherit.do_blah(a)
if x != "Foo::blah"
puts "Whoa! Bad return #{x}"
end
x = Typedef_inherit.do_blah(b)
if x != "Bar::blah"
puts "Whoa! Bad return #{x}"
end
c = Typedef_inherit::Spam.new
d = Typedef_inherit::Grok.new
x = Typedef_inherit.do_blah2(c)
if x != "Spam::blah"
puts "Whoa! Bad return #{x}"
end
x = Typedef_inherit.do_blah2(d)
if x != "Grok::blah"
puts "Whoa! Bad return #{x}"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'typedef_scope'
b = Typedef_scope::Bar.new
x = b.test1(42, "hello")
if x != 42
puts "Failed!!"
end
x = b.test2(42, "hello")
if x != "hello"
puts "Failed!!"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'typemap_namespace'
include Typemap_namespace
raise RuntimeError if test1("hello") != "hello"
raise RuntimeError if test2("hello") != "hello"
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'typemap_ns_using'
raise RuntimeError unless Typemap_ns_using.spam(37) == 37
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'typename'
f = Typename::Foo.new
b = Typename::Bar.new
x = Typename.twoFoo(f)
unless x.is_a? Float
puts "Wrong return type!"
end
y = Typename.twoBar(b)
unless y.is_a? Integer
puts "Wrong return type!"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
# This is the union runtime testcase. It ensures that values within a
# union embedded within a struct can be set and read correctly.
require 'unions'
# Create new instances of SmallStruct and BigStruct for later use
small = Unions::SmallStruct.new()
small.jill = 200
big = Unions::BigStruct.new()
big.smallstruct = small
big.jack = 300
# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
# Ensure values in EmbeddedUnionTest are set correctly for each.
eut = Unions::EmbeddedUnionTest.new()
# First check the SmallStruct in EmbeddedUnionTest
eut.number = 1
eut.uni.small = small
Jill1 = eut.uni.small.jill
if (Jill1 != 200)
print "Runtime test1 failed. eut.uni.small.jill=" , Jill1 , "\n"
exit 1
end
Num1 = eut.number
if (Num1 != 1)
print "Runtime test2 failed. eut.number=" , Num1 , "\n"
exit 1
end
# Secondly check the BigStruct in EmbeddedUnionTest
eut.number = 2
eut.uni.big = big
Jack1 = eut.uni.big.jack
if (Jack1 != 300)
print "Runtime test3 failed. eut.uni.big.jack=" , Jack1 , "\n"
exit 1
end
Jill2 = eut.uni.big.smallstruct.jill
if (Jill2 != 200)
print "Runtime test4 failed. eut.uni.big.smallstruct.jill=" , Jill2 , "\n"
exit 1
end
Num2 = eut.number
if (Num2 != 2)
print "Runtime test5 failed. eut.number=" , Num2 , "\n"
exit 1
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using1'
raise RuntimeError unless Using1.spam(37) == 37
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using2'
raise RuntimeError unless Using2.spam(37) == 37
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using_composition'
include Using_composition
f = FooBar.new
if f.blah(3) != 3
raise RuntimeError,"FooBar::blah(int)"
end
if f.blah(3.5) != 3.5
raise RuntimeError,"FooBar::blah(double)"
end
if f.blah("hello") != "hello"
raise RuntimeError,"FooBar::blah(char *)"
end
f = FooBar2.new
if f.blah(3) != 3
raise RuntimeError,"FooBar2::blah(int)"
end
if f.blah(3.5) != 3.5
raise RuntimeError,"FooBar2::blah(double)"
end
if f.blah("hello") != "hello"
raise RuntimeError,"FooBar2::blah(char *)"
end
f = FooBar3.new
if f.blah(3) != 3
raise RuntimeError,"FooBar3::blah(int)"
end
if f.blah(3.5) != 3.5
raise RuntimeError,"FooBar3::blah(double)"
end
if f.blah("hello") != "hello"
raise RuntimeError,"FooBar3::blah(char *)"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using_extend'
include Using_extend
f = FooBar.new
if f.blah(3) != 3
raise RuntimeError,"blah(int)"
end
if f.blah(3.5) != 3.5
raise RuntimeError,"blah(double)"
end
if f.blah("hello") != "hello"
raise RuntimeError,"blah(char *)"
end
if f.blah(3,4) != 7
raise RuntimeError,"blah(int,int)"
end
if f.blah(3.5,7.5) != (3.5+7.5)
raise RuntimeError,"blah(double,double)"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using_inherit'
include Using_inherit
b = Bar.new
if b.test(3) != 3
raise RuntimeError,"Bar::test(int)"
end
if b.test(3.5) != 3.5
raise RuntimeError, "Bar::test(double)"
end
b = Bar2.new
if b.test(3) != 6
raise RuntimeError,"Bar2::test(int)"
end
if b.test(3.5) != 7.0
raise RuntimeError, "Bar2::test(double)"
end
b = Bar3.new
if b.test(3) != 6
raise RuntimeError,"Bar3::test(int)"
end
if b.test(3.5) != 7.0
raise RuntimeError, "Bar3::test(double)"
end
b = Bar4.new
if b.test(3) != 6
raise RuntimeError,"Bar4::test(int)"
end
if b.test(3.5) != 7.0
raise RuntimeError, "Bar4::test(double)"
end
b = Fred1.new
if b.test(3) != 3
raise RuntimeError,"Fred1::test(int)"
end
if b.test(3.5) != 7.0
raise RuntimeError, "Fred1::test(double)"
end
b = Fred2.new
if b.test(3) != 3
raise RuntimeError,"Fred2::test(int)"
end
if b.test(3.5) != 7.0
raise RuntimeError, "Fred2::test(double)"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using_private'
include Using_private
f = FooBar.new
f.x = 3
if f.blah(4) != 4
raise RuntimeError, "blah(int)"
end
if f.defaulted() != -1
raise RuntimeError, "defaulted()"
end
if f.defaulted(222) != 222
raise RuntimeError, "defaulted(hi)"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'using_protected'
include Using_protected
f = FooBar.new
f.x = 3
if f.blah(4) != 4
raise RuntimeError, "blah(int)"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'varargs'
if Varargs.test("Hello") != "Hello"
raise RuntimeError, "Failed"
end
f = Varargs::Foo.new("Greetings")
if f.str != "Greetings"
raise RuntimeError, "Failed"
end
if f.test("Hello") != "Hello"
raise RuntimeError, "Failed"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'virtual_derivation'
b = Virtual_derivation::B.new 3
if b.get_a() != b.get_b()
print "something is still wrong ", b.get_a(), b.get_b(), "\n"
end
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'virtual_poly'
d = Virtual_poly::NDouble.new(3.5)
i = Virtual_poly::NInt.new(2)
#
# polymorphic return type working
#
dc = d.copy
ic = i.copy
raise RuntimeError if d.get != dc.get
raise RuntimeError if i.get != ic.get
#
# 'narrowing' working ('nnumber' returns a NNumber)
#
ddc = Virtual_poly::NDouble.narrow(dc.nnumber)
raise RuntimeError if d.get != ddc.get
dic = Virtual_poly::NInt.narrow(ic.nnumber)
raise RuntimeError if i.get != dic.get
#!/usr/bin/env ruby
#
# Put description here
#
#
#
#
#
require 'swig_assert'
require 'voidtest'
Voidtest.globalfunc()
f = Voidtest::Foo.new
f.memberfunc()
Voidtest::Foo.staticmemberfunc()
v1 = Voidtest::vfunc1(f)
v3 = Voidtest::vfunc3(v1)
v3.memberfunc()
require 'mkmf'
dir_config('yourlib')
if have_header('yourlib.h') and have_library('yourlib', 'yourlib_init')
# If you use swig -c option, you may have to link libswigrb.
# have_library('swigrb')
create_makefile('yourlib')
end
md5: DBBC2961F336E7E50B952E6A75662E1D | sha1: 923B4507F7D1923B3113111C5FB9302E623573A6 | sha256: 94FA122052EEED10151D0629F4636E1AF5E10E3872243E09734E1203C1E4E862 | sha512: 4519EF78BDEA5513C4E187524F3C4E09150542107A2DF45DC77A55AAD47F84F0D844CEA77F6125C1E63776909A69F6DB617CA442A1F859CE3E8623BA3E00C81B
#!/usr/bin/env python
import sys
import os
import subprocess
def failed():
print("mkdist.py failed to complete")
sys.exit(2)
import argparse
parser = argparse.ArgumentParser(description="Build a SWIG distribution tarball swig-x.y.z.tar.gz")
parser.add_argument("version", help="version string in format x.y.z")
parser.add_argument("-b", "--branch", required=False, default="master", help="git branch name to create tarball from [master]")
parser.add_argument("-f", "--force-tag", required=False, action="store_true", help="force tag (replace git tag if it already exists)")
parser.add_argument("-s", "--skip-checks", required=False, action="store_true", help="skip checks (that local and remote repos are in sync)")
args = parser.parse_args()
version = args.version
branch = args.branch
dirname = "swig-" + version
force_tag = args.force_tag
skip_checks = args.skip_checks
if sys.version_info[0:2] < (2, 7):
print("Error: Python 2.7 or higher is required")
sys.exit(3)
# Check name matches normal unix conventions
if dirname.lower() != dirname:
print("directory name (" + dirname + ") should be in lowercase")
sys.exit(3)
# If directory and tarball exist, remove it
print("Removing " + dirname)
os.system("rm -rf " + dirname)
print("Removing " + dirname + ".tar if exists")
os.system("rm -f " + dirname + ".tar.gz")
print("Removing " + dirname + ".tar.gz if exists")
os.system("rm -f " + dirname + ".tar")
# Grab the code from git
print("Checking there are no local changes in git repo")
os.system("git remote update origin") == 0 or failed()
command = ["git", "status", "--porcelain", "-uno"]
out = subprocess.check_output(command)
if out.strip() != "":
print("Local git repository has modifications")
print(" ".join(command))
print(out)
sys.exit(3)
if not skip_checks:
print("Checking git repository is in sync with remote repository")
command = ["git", "log", "--oneline", branch + "..origin/" + branch]
out = subprocess.check_output(command)
if out.strip() != "":
print("Remote repository has additional modifications to local repository")
print(" ".join(command))
print(out)
sys.exit(3)
command = ["git", "log", "--oneline", "origin/" + branch + ".." + branch]
out = subprocess.check_output(command)
if out.strip() != "":
print("Local repository has modifications not pushed to the remote repository")
print("These should be pushed and checked that they pass Continuous Integration testing before continuing")
print(" ".join(command))
print(out)
sys.exit(3)
print("Tagging release")
tag = "'rel-" + version + "'"
force = "-f " if force_tag else ""
os.system("git tag -a -m " + tag + " " + force + tag) == 0 or failed()
outdir = os.path.basename(os.getcwd()) + "/" + dirname + "/"
print("Grabbing tagged release git repository using 'git archive' into " + outdir)
os.system("(cd .. && git archive --prefix=" + outdir + " " + tag + " . | tar -xf -)") == 0 or failed()
# Go build the system
print("Building system")
os.system("cd " + dirname + " && ./autogen.sh") == 0 or failed()
os.system("cd " + dirname + "/Source/CParse && bison -y -d parser.y && mv y.tab.c parser.c && mv y.tab.h parser.h") == 0 or failed()
os.system("cd " + dirname + " && make -f Makefile.in libfiles srcdir=./") == 0 or failed()
# Remove autoconf files
os.system("find " + dirname + " -name autom4te.cache -exec rm -rf {} \\;")
# Build documentation
print("Building html documentation")
os.system("cd " + dirname + "/Doc/Manual && make all clean-baks") == 0 or failed()
# Build the tar-ball
os.system("tar -cf " + dirname + ".tar " + dirname) == 0 or failed()
os.system("gzip " + dirname + ".tar") == 0 or failed()
print("Finished building " + dirname + ".tar.gz")
#!/usr/bin/env python
import sys
import os
def failed(message):
if message == "":
print("mkrelease.py failed to complete")
else:
print(message)
sys.exit(2)
import argparse
parser = argparse.ArgumentParser(description="Build a SWIG distribution source tarball swig-x.y.z.tar.gz and the Windows zip package swigwin-x.y.z.zip.\nUpload them both to SourceForge ready for release.\nThe release notes are also uploaded.")
parser.add_argument("version", help="version string in format x.y.z")
parser.add_argument("-b", "--branch", required=False, default="master", help="git branch name to create tarball from [master]")
parser.add_argument("-f", "--force-tag", required=False, action="store_true", help="force tag (replace git tag if it already exists)")
parser.add_argument("-s", "--skip-checks", required=False, action="store_true", help="skip checks (that local and remote repos are in sync)")
parser.add_argument("-u", "--username", required=False, help="SourceForge username (upload to SourceForge will be skipped if not provided)")
args = parser.parse_args()
version = args.version
branch = args.branch
dirname = "swig-" + version
force_tag = args.force_tag
skip_checks = args.skip_checks
username = args.username
print("Looking for rsync")
os.system("which rsync") and failed("rsync not installed/found. Please install.")
print("Making source tarball")
force = "--force-tag" if force_tag else ""
skip = "--skip-checks" if skip_checks else ""
os.system("python ./mkdist.py {} {} --branch {} {}".format(force, skip, branch, version)) and failed("")
print("Build Windows package")
os.system("./mkwindows.sh " + version) and failed("")
if username:
print("Uploading to SourceForge")
swig_dir_sf = username + ",[email protected]:/home/frs/project/s/sw/swig/swig/swig-" + version + "/"
swigwin_dir_sf = username + ",[email protected]:/home/frs/project/s/sw/swig/swigwin/swigwin-" + version + "/"
# If a file with 'readme' in the name exists in the same folder as the zip/tarball, it gets automatically displayed as the release notes by SF
full_readme_file = "readme-" + version + ".txt"
os.system("rm -f " + full_readme_file)
os.system("cat swig-" + version + "/README " + "swig-" + version + "/CHANGES.current " + "swig-" + version + "/RELEASENOTES " + "> " + full_readme_file)
os.system("rsync --archive --verbose -P --times -e ssh " + "swig-" + version + ".tar.gz " + full_readme_file + " " + swig_dir_sf) and failed("")
os.system("rsync --archive --verbose -P --times -e ssh " + "swigwin-" + version + ".zip " + full_readme_file + " " + swigwin_dir_sf) and failed("")
print("Finished")
print("Now log in to SourceForge and set the operating systems applicable to the newly uploaded tarball and zip file. Also remember to do a 'git push --tags'.")
#!/bin/sh
# Build Windows distribution (swigwin-2.0.x.zip) from source tarball (swig-2.0.x.tar.gz)
# Requires running in either:
# - MinGW environment
# - Linux using MinGW cross compiler
# - Cygwin using MinGW compiler
# path to zip program
zip=
wine=
# options for configure
extraconfigureoptions=
compileflags="-O2 -Wall -Wextra"
if test x$1 != x; then
version=$1
if test x$2 != x; then
zip=$2;
echo zip: $zip;
fi
else
echo "Usage: mkwindows.sh version [zip]"
echo " Build SWIG Windows distribution from source tarball. Works on Cygwin, MinGW or Linux"
echo " version should be 2.0.x"
echo " zip is full path to zip program - default is /c/cygwin/bin/zip on MinGW, zip on Linux and Cygwin"
exit 1
fi
uname=`uname -a`
mingw=`echo "$uname" | grep -i mingw`
linux=`echo "$uname" | grep -i linux`
cygwin=`echo "$uname" | grep -i cygwin`
if test "$mingw"; then
echo "Building native Windows executable on MinGW";
if test x$zip = x; then
zip=/c/cygwin/bin/zip
fi
else
if test "$linux"; then
echo "Building native Windows executable on Linux"
if test x$zip = x; then
zip=zip
wine=$(which wine)
fi
if test x$wine = x; then
echo "Could not detect wine - please install wine-stable package."
exit 1;
fi
echo "Checking that mingw 32-bit gcc is installed/available"
if test -n "`which i686-w64-mingw32-gcc`" ; then
i686-w64-mingw32-gcc --version || exit 1
i686-w64-mingw32-g++ --version || exit 1
extraconfigureoptions="--host=i686-w64-mingw32 --build=i686-linux"
# Statically link so that libstdc++-6.dll and libgcc_s_sjlj-1.dll don't have to be shipped
compileflags="$compileflags -static-libgcc -static-libstdc++"
elif test -n "`which i586-mingw32msvc-gcc`" ; then
i586-mingw32msvc-gcc --version || exit 1
i586-mingw32msvc-g++ --version || exit 1
extraconfigureoptions="--host=i586-mingw32msvc --build=i686-linux"
else
echo "Could not detect mingw gcc - please install mingw-w64 package."
exit 1;
fi
else
if test "$cygwin"; then
echo "Building native Windows executable on Cygwin"
if test x$zip = x; then
zip=zip
fi
compileflags="$compileflags -mno-cygwin"
else
echo "Unknown platform. Requires either Linux or MinGW."
exit 1;
fi
fi
fi
export CFLAGS="$compileflags"
export CXXFLAGS="$compileflags"
swigbasename=swig-$version
swigwinbasename=swigwin-$version
tarball=$swigbasename.tar.gz
pcre_tarball=`ls pcre-*.tar.*`
if ! test -f "$pcre_tarball"; then
echo "Could not find PCRE tarball. Please download a PCRE source tarball from http://www.pcre.org"
echo "and place in the same directory as the SWIG tarball."
exit 1
fi
if test -f "$tarball"; then
builddir=build-$version
if test -e $builddir; then
echo "Deleting directory $builddir..."
rm -rf $builddir
fi
echo "Creating directory $builddir..."
mkdir $builddir
cd $builddir
echo "Unzipping tarball..."
tar -zxf ../$tarball
sleep 2 # fix strange not finding newly created directory
if test -d $swigbasename; then
mv $swigbasename $swigwinbasename
tar -zxf ../$tarball
cd $swigbasename
(cd ../.. && cp $pcre_tarball $builddir/$swigbasename)
echo Running: Tools/pcre-build.sh $extraconfigureoptions
./Tools/pcre-build.sh $extraconfigureoptions
echo Running: ./configure $extraconfigureoptions --without-alllang
./configure $extraconfigureoptions --without-alllang
echo "Compiling (quietly)..."
make > build.log
echo "Simple check to see if swig.exe runs..."
env LD_LIBRARY_PATH= PATH= $wine ./swig.exe -version || exit 1
echo "Simple check to see if ccache-swig.exe runs..."
env LD_LIBRARY_PATH= PATH= $wine ./CCache/ccache-swig.exe -V || exit 1
echo "Creating $swigwinbasename.zip..."
cd ..
cp $swigbasename/swig.exe $swigwinbasename
cp $swigbasename/CCache/ccache-swig.exe $swigwinbasename/CCache
cp $swigbasename/Lib/swigwarn.swg $swigwinbasename/Lib
sleep 2 # fix strange not finding swig.exe
echo "Unzip into a directory of your choice. Please read the README file as well as Doc\Manual\Windows.html for installation instructions." > swig_windows_zip_comments.txt
rm -f ../$swigwinbasename.zip
$zip -q -r -9 -z < swig_windows_zip_comments.txt ../$swigwinbasename.zip $swigwinbasename
rm -f swig_windows_zip_comments.txt
echo "Cleaning up..."
cd ..
rm -rf $builddir
echo "Finished building $swigwinbasename.zip"
else
echo "Expecting tarball to create directory: $swigbasename but it does not exist"
exit 1
fi
else
echo tarball missing: $tarball
exit 1
fi
exit 0
rem Workaround 'nuget install' not being reliable by retrying a few times
@echo off
rem initiate the retry number
set errorCode=1
set retryNumber=0
set maxRetries=5
:RESTORE
nuget install %*
rem problem?
IF ERRORLEVEL %errorCode% GOTO :RETRY
rem everything is fine!
@echo Installed nuget, retries: %reTryNumber%
GOTO :EXIT
:RETRY
@echo Oops, nuget restore exited with code %errorCode% - let us try again!
set /a retryNumber=%retryNumber%+1
IF %reTryNumber% LSS %maxRetries% (GOTO :RESTORE)
IF %retryNumber% EQU %maxRetries% (GOTO :ERR)
:ERR
@echo Sorry, we tried restoring nuget packages for %maxRetries% times and all attempts were unsuccessful!
EXIT /B 1
:EXIT
#!/usr/bin/env python
import os
import subprocess
import argparse
import glob
def remove_old_files():
files = glob.glob("*.log")
for file in files:
os.remove(file)
def download():
repos = subprocess.Popen(["osc", "repositories"], stdout=subprocess.PIPE)
for line in repos.stdout:
command = ["osc", "buildlog", "--last"] + line.split()
filename = "-".join(line.split()) + ".log"
print("Downloading logs using: {}".format(" ".join(command)))
buildlog = subprocess.Popen(command, stdout=subprocess.PIPE)
print("Writing log to {}".format(filename))
file = open(filename, "w")
if buildlog.stderr != None:
print("Errors: {}".format(buildlog.stderr))
for log_line in buildlog.stdout:
file.write(log_line)
print("Finished")
parser = argparse.ArgumentParser(description="Download OpenBuild logs using osc. All the logs for each architecture from the last completed builds are downloaded and stored as .log files. Must be run from a working copy that is already checked out, eg after running obs-update.")
args = parser.parse_args()
remove_old_files()
download()
#!/bin/sh
pcre_subdir=pcre/pcre-swig-install
pcre_install_dir=`pwd`/$pcre_subdir
usage() {
echo "Helper script to build PCRE as a static library from a tarball just for use during the"
echo "SWIG build. It does not install PCRE for global use on your system."
echo "Usage: pcre-build.sh [--help] [args]"
echo " args - optional additional arguments passed on to the PCRE configure script (leave out"
echo " unless you are an expert at configure)"
echo " --help - Display this help information."
echo "Instructions:"
echo " - Download the latest PCRE source tarball from http://www.pcre.org and place in the"
echo " directory that you will configure and build SWIG."
echo " - Run this script in the same directory that you intend to configure and build SWIG in."
echo " This will configure and build PCRE as a static library."
echo " - Afterwards run the SWIG configure script which will then find and use the PCRE static"
echo " libraries in the $pcre_subdir subdirectory."
exit 0
}
bail() {
echo $1 >&2
exit 1
}
if test "$1" = "-h" -o "$1" = "-help" -o "$1" = "--help" ; then
usage
fi
if test -f "pcre-build.sh" ; then
echo "Error: this script should not be run in the Tools directory" >&2
echo ""
usage
fi
echo "Looking for PCRE tarball..."
rm -rf pcre
pcre_tarball=`ls pcre-*.tar*`
test -n "$pcre_tarball" || bail "Could not find tarball matching pattern: pcre-*.tar*"
test -f "$pcre_tarball" || bail "Could not find a single PCRE tarball. Found: $pcre_tarball"
echo "Extracting tarball: $pcre_tarball"
tar -xf $pcre_tarball || bail "Could not untar $pcre_tarball"
pcre_dir=`echo $pcre_tarball | sed -e "s/\.tar.*//"`
echo "Configuring PCRE in directory: pcre"
mv $pcre_dir pcre || bail "Could not create pcre directory"
cd pcre && ./configure --prefix=$pcre_install_dir --disable-shared $* || bail "PCRE configure failed"
echo "Building PCRE..."
${MAKE:-make} -s || bail "Could not build PCRE"
echo "Installing PCRE locally to $pcre_install_dir..."
${MAKE:-make} -s install || bail "Could not install PCRE"
echo ""
echo "The SWIG configure script can now be run, whereupon PCRE will automatically be detected and used from $pcre_install_dir/bin/pcre-config."
#!/usr/bin/env python
"""
From SWIG 1.3.37 we deprecated all SWIG symbols that start with Py,
since they are inappropriate and discouraged in Python documentation
(from http://www.python.org/doc/2.5.2/api/includes.html):
"All user visible names defined by Python.h (except those defined by the included
standard headers) have one of the prefixes "Py" or "_Py". Names beginning with
"_Py" are for internal use by the Python implementation and should not be used
by extension writers. Structure member names do not have a reserved prefix.
Important: user code should never define names that begin with "Py" or "_Py".
This confuses the reader, and jeopardizes the portability of the user code to
future Python versions, which may define additional names beginning with one
of these prefixes."
This file is a simple script used for change all of these symbols, for user code
or SWIG itself.
"""
import re
from shutil import copyfile
import sys
symbols = [
#(old name, new name)
("PySequence_Base", "SwigPySequence_Base"),
("PySequence_Cont", "SwigPySequence_Cont"),
("PySwigIterator_T", "SwigPyIterator_T"),
("PyPairBoolOutputIterator", "SwigPyPairBoolOutputIterator"),
("PySwigIterator", "SwigPyIterator"),
("PySwigIterator_T", "SwigPyIterator_T"),
("PyMapIterator_T", "SwigPyMapIterator_T"),
("PyMapKeyIterator_T", "SwigPyMapKeyIterator_T"),
("PyMapValueIterator_T", "SwigPyMapValueITerator_T"),
("PyObject_ptr", "SwigPtr_PyObject"),
("PyObject_var", "SwigVar_PyObject"),
("PyOper", "SwigPyOper"),
("PySeq", "SwigPySeq"),
("PySequence_ArrowProxy", "SwigPySequence_ArrowProxy"),
("PySequence_Cont", "SwigPySequence_Cont"),
("PySequence_InputIterator", "SwigPySequence_InputIterator"),
("PySequence_Ref", "SwigPySequence_Ref"),
("PySwigClientData", "SwigPyClientData"),
("PySwigClientData_Del", "SwigPyClientData_Del"),
("PySwigClientData_New", "SwigPyClientData_New"),
("PySwigIterator", "SwigPyIterator"),
("PySwigIteratorClosed_T", "SwigPyIteratorClosed_T"),
("PySwigIteratorOpen_T", "SwigPyIteratorOpen_T"),
("PySwigIterator_T", "SwigPyIterator_T"),
("PySwigObject", "SwigPyObject"),
("PySwigObject_Check", "SwigPyObject_Check"),
("PySwigObject_GetDesc", "SwigPyObject_GetDesc"),
("PySwigObject_New", "SwigPyObject_New"),
("PySwigObject_acquire", "SwigPyObject_acquire"),
("PySwigObject_append", "SwigPyObject_append"),
("PySwigObject_as_number", "SwigPyObject_as_number"),
("PySwigObject_compare", "SwigPyObject_compare"),
("PySwigObject_dealloc", "SwigPyObject_dealloc"),
("PySwigObject_disown", "SwigPyObject_disown"),
("PySwigObject_format", "SwigPyObject_format"),
("PySwigObject_getattr", "SwigPyObject_getattr"),
("PySwigObject_hex", "SwigPyObject_hex"),
("PySwigObject_long", "SwigPyObject_long"),
("PySwigObject_next", "SwigPyObject_next"),
("PySwigObject_oct", "SwigPyObject_oct"),
("PySwigObject_own", "SwigPyObject_own"),
("PySwigObject_print", "SwigPyObject_print"),
("PySwigObject_repr", "SwigPyObject_repr"),
("PySwigObject_richcompare", "SwigPyObject_richcompare"),
("PySwigObject_str", "SwigPyObject_str"),
("PySwigObject_type", "SwigPyObject_type"),
("PySwigPacked", "SwigPyPacked"),
("PySwigPacked_Check", "SwigPyPacked_Check"),
("PySwigPacked_New", "SwigPyPacked_New"),
("PySwigPacked_UnpackData", "SwigPyPacked_UnpackData"),
("PySwigPacked_compare", "SwigPyPacked_compare"),
("PySwigPacked_dealloc", "SwigPyPacked_dealloc"),
("PySwigPacked_print", "SwigPyPacked_print"),
("PySwigPacked_repr", "SwigPyPacked_repr"),
("PySwigPacked_str", "SwigPyPacked_str"),
("PySwigPacked_type", "SwigPyPacked_type"),
("pyseq", "swigpyseq"),
("pyswigobject_type", "swigpyobject_type"),
("pyswigpacked_type", "swigpypacked_type"),
]
res = [(re.compile("\\b(%s)\\b"%oldname), newname) for oldname, newname in symbols]
def patch_file(fn):
newf = []
changed = False
for line in open(fn):
for r, newname in res:
line, n = r.subn(newname, line)
if n>0:
changed = True
newf.append(line)
if changed:
copyfile(fn, fn+".bak")
f = open(fn, "w")
f.write("".join(newf))
f.close()
return changed
def main(fns):
for fn in fns:
try:
if patch_file(fn):
print "Patched file", fn
except IOError:
print "Error occurred during patching", fn
return
if __name__=="__main__":
if len(sys.argv) > 1:
main(sys.argv[1:])
else:
print "Patch your interface file for SWIG's Py* symbol name deprecation."
print "Usage:"
print " %s files..."%sys.argv[0]
#!/usr/bin/env python
def get_cflags(language, std, compiler):
if std == None or len(std) == 0:
std = "gnu89"
c_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wdeclaration-after-statement -Wmissing-field-initializers"
cflags = {
"csharp":"-Werror " + c_common,
"d":"-Werror " + c_common,
"go":"-Werror " + c_common + " -Wno-declaration-after-statement",
"guile":"-Werror " + c_common,
"java":"-Werror " + c_common,
"javascript":"-Werror " + c_common,
"lua":"-Werror " + c_common,
"mzscheme":"-Werror " + c_common,
"ocaml":"-Werror " + c_common,
"octave":"-Werror " + c_common,
"perl5":"-Werror " + c_common,
"php":"-Werror " + c_common,
"python":"-Werror " + c_common,
"r":"-Werror " + c_common,
"ruby":"-Werror " + c_common,
"scilab":"-Werror " + c_common,
"tcl":"-Werror " + c_common,
}
if compiler == "clang":
cflags["guile"] += " -Wno-attributes" # -Wno-attributes is for clang LLVM 3.5 and bdw-gc < 7.5 used by guile
if language not in cflags:
raise RuntimeError("{} is not a supported language".format(language))
return cflags[language]
def get_cxxflags(language, std, compiler):
if std == None or len(std) == 0:
std = "c++98"
cxx_common = "-fdiagnostics-show-option -std=" + std + " -Wno-long-long -Wreturn-type -Wmissing-field-initializers"
cxxflags = {
"csharp":"-Werror " + cxx_common,
"d":"-Werror " + cxx_common,
"go":"-Werror " + cxx_common,
"guile":"-Werror " + cxx_common,
"java":"-Werror " + cxx_common,
"javascript":"-Werror " + cxx_common + " -Wno-error=unused-function", # Until overload_rename is fixed for node
"lua":"-Werror " + cxx_common,
"mzscheme":"-Werror " + cxx_common,
"ocaml":"-Werror " + cxx_common,
"octave":"-Werror " + cxx_common,
"perl5":"-Werror " + cxx_common,
"php":"-Werror " + cxx_common,
"python":"-Werror " + cxx_common,
"r":"-Werror " + cxx_common,
"ruby":"-Werror " + cxx_common + " -Wno-deprecated-declarations", # For Ruby on MacOS Xcode 9.4 misconfiguration defining 'isfinite' to deprecated 'finite'
"scilab":"-Werror " + cxx_common,
"tcl":"-Werror " + cxx_common,
}
if compiler == "clang":
cxxflags["guile"] += " -Wno-attributes" # -Wno-attributes is for clang LLVM 3.5 and bdw-gc < 7.5 used by guile
if language not in cxxflags:
raise RuntimeError("{} is not a supported language".format(language))
return cxxflags[language]
import argparse
parser = argparse.ArgumentParser(description="Display CFLAGS or CXXFLAGS to use for testing the SWIG examples and test-suite.")
parser.add_argument("-l", "--language", required=True, help="set language to show flags for")
flags = parser.add_mutually_exclusive_group(required=True)
flags.add_argument("-c", "--cflags", action="store_true", default=False, help="show CFLAGS")
flags.add_argument("-x", "--cxxflags", action="store_true", default=False, help="show CXXFLAGS")
parser.add_argument("-s", "--std", required=False, help="language standard flags for the -std= option")
parser.add_argument("-C", "--compiler", required=False, help="compiler used (clang or gcc)")
args = parser.parse_args()
if args.cflags:
get_flags = get_cflags
elif args.cxxflags:
get_flags = get_cxxflags
else:
parser.print_help()
exit(1)
print(get_flags(args.language, args.std, args.compiler))
#!/bin/bash
# Install Linux packages where the version has been overidden in .travis.yml
set -e # exit on failure (same as -o errexit)
lsb_release -a
travis_retry sudo apt-get -qq update
if [[ -n "$GCC" ]]; then
travis_retry sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
travis_retry sudo apt-get -qq update
travis_retry sudo apt-get install -qq g++-$GCC
fi
travis_retry sudo apt-get -qq install libboost-dev libpcre3-dev
WITHLANG=$SWIGLANG
case "$SWIGLANG" in
"") ;;
"csharp")
travis_retry sudo apt-get -qq install mono-devel
;;
"d")
travis_retry wget http://downloads.dlang.org/releases/2.x/${VER}/dmd_${VER}-0_amd64.deb
travis_retry sudo dpkg -i dmd_${VER}-0_amd64.deb
;;
"go")
if [[ "$VER" ]]; then
eval "$(gimme ${VER}.x)"
fi
;;
"javascript")
case "$ENGINE" in
"node")
travis_retry wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.10/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
travis_retry nvm install ${VER}
nvm use ${VER}
if [ "$VER" == "0.10" ] || [ "$VER" == "0.12" ] || [ "$VER" == "4" ] || [ "$VER" == "6" ] ; then
# travis_retry sudo apt-get install -qq nodejs node-gyp
travis_retry npm install -g node-gyp@$VER
elif [ "$VER" == "8" ] ; then
travis_retry npm install -g node-gyp@6
else
travis_retry npm install -g node-gyp
fi
;;
"jsc")
travis_retry sudo apt-get install -qq libwebkitgtk-dev
;;
"v8")
travis_retry sudo apt-get install -qq libv8-dev
;;
esac
;;
"guile")
travis_retry sudo apt-get -qq install guile-2.0-dev
;;
"lua")
if [[ -z "$VER" ]]; then
travis_retry sudo apt-get -qq install lua5.2 liblua5.2-dev
else
travis_retry sudo apt-get -qq install lua${VER} liblua${VER}-dev
fi
;;
"mzscheme")
travis_retry sudo apt-get -qq install racket
;;
"ocaml")
travis_retry sudo apt-get -qq install ocaml camlp4
;;
"octave")
travis_retry sudo apt-get -qq install liboctave-dev
;;
"php")
travis_retry sudo add-apt-repository -y ppa:ondrej/php
travis_retry sudo apt-get -qq update
travis_retry sudo apt-get -qq install php$VER-cli php$VER-dev
;;
"python")
pip install --user pycodestyle
if [[ "$PY3" ]]; then
travis_retry sudo apt-get install -qq python3-dev
fi
WITHLANG=$SWIGLANG$PY3
if [[ "$VER" ]]; then
travis_retry sudo add-apt-repository -y ppa:deadsnakes/ppa
travis_retry sudo apt-get -qq update
travis_retry sudo apt-get -qq install python${VER}-dev
WITHLANG=$SWIGLANG$PY3=$SWIGLANG$VER
fi
;;
"r")
travis_retry sudo apt-get -qq install r-base
;;
"ruby")
if [[ "$VER" == "2.7" ]]; then
# Ruby 2.7 support is currently only rvm master (30 Dec 2019)
travis_retry rvm get master
rvm reload
rvm list known
fi
if [[ "$VER" ]]; then
travis_retry rvm install $VER
fi
;;
"scilab")
# Travis has the wrong version of Java pre-installed resulting in error using scilab:
# /usr/bin/scilab-bin: error while loading shared libraries: libjava.so: cannot open shared object file: No such file or directory
echo "JAVA_HOME was set to $JAVA_HOME"
unset JAVA_HOME
travis_retry sudo apt-get -qq install scilab
;;
"tcl")
travis_retry sudo apt-get -qq install tcl-dev
;;
esac
set +e # turn off exit on failure (same as +o errexit)
#!/bin/bash
# Install MacOS packages where the version has been overidden in .travis.yml
set -e # exit on failure (same as -o errexit)
# Disable 'brew cleanup', just wastes Travis job run time
export HOMEBREW_NO_INSTALL_CLEANUP=1
sw_vers
travis_retry brew update
travis_retry brew list
# travis_retry brew install pcre # Travis Xcode-7.3 has pcre
# travis_retry brew install boost
WITHLANG=$SWIGLANG
case "$SWIGLANG" in
"csharp")
travis_retry brew install mono
;;
"guile")
travis_retry Tools/brew-install guile
;;
"lua")
travis_retry brew install lua
;;
"octave")
travis_retry Tools/brew-install octave
;;
"python")
WITHLANG=$SWIGLANG$PY3
;;
esac
# Workaround for https://github.com/travis-ci/travis-ci/issues/6522
set +e # turn off exit on failure (same as +o errexit)
Please see the Doc/Manual/Windows.html file in the main manual for instructions for using and installing SWIG on Windows including running the examples.
The contents of this file were copied as follows:
- From: tools\install\swigwin-4.0.2\LICENSE
This file was created by chauto package generator.
SWIG is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. See the LICENSE-GPL file for
the full terms of the GNU General Public license version 3.
Portions of SWIG are also licensed under the terms of the licenses
in the file LICENSE-UNIVERSITIES. You must observe the terms of
these licenses, as well as the terms of the GNU General Public License,
when you distribute SWIG.
The SWIG library and examples, under the Lib and Examples top level
directories, are distributed under the following terms:
You may copy, modify, distribute, and make derivative works based on
this software, in source code or object code form, without
restriction. If you distribute the software to others, you may do
so according to the terms of your choice. This software is offered as
is, without warranty of any kind.
See the COPYRIGHT file for a list of contributors to SWIG and their
copyright notices.
The contents of this folder were downloaded as follows:
- From: https://cfhcable.dl.sourceforge.net/project/swig/swigwin/swigwin-4.0.2/swigwin-4.0.2.zip
- On: Tuesday, 04-Aug-20 21:54:25 CDT
- Hash: daadb32f19fe818cb9b0015243233fc81584844c11a48436385e87c050346559
This file was created by chauto package generator.
Log in or click on link to see number of positives.
- swig.exe (94fa122052ee) - ## / 71
- swig.4.0.2.04082020.nupkg (33082cb5097d) - ## / 56
- ccache-swig.exe (bfc4edf3747c) - ## / 70
In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).
Chocolatey Pro provides runtime protection from possible malware.
Add to Builder | Version | Downloads | Last Updated | Status |
---|---|---|---|---|
Simplified Wrapper and Interface Generator 4.1.1 | 66572 | Saturday, March 4, 2023 | Approved | |
Simplified Wrapper and Interface Generator 4.1.0 | 134 | Saturday, March 4, 2023 | Approved | |
Simplified Wrapper and Interface Generator 4.0.2.04082020 | 87734 | Thursday, August 6, 2020 | Approved | |
Simplified Wrapper and Interface Generator 4.0.2 | 9248 | Friday, July 3, 2020 | Approved | |
Simplified Wrapper and Interface Generator 4.0.1 | 66507 | Saturday, September 28, 2019 | Approved | |
Simplified Wrapper and Interface Generator 4.0.0 | 13735 | Wednesday, May 1, 2019 | Approved | |
SWIG 3.0.12 | 93411 | Wednesday, October 24, 2018 | Approved | |
SWIG 3.0.11 | 360 | Monday, October 22, 2018 | Approved | |
SWIG 3.0.10 | 248 | Monday, October 22, 2018 | Approved | |
swig 3.0.9 | 36319 | Sunday, June 4, 2017 | Approved | |
SWIG 3.0.8 | 1188 | Saturday, June 10, 2017 | Approved | |
SWIG 3.0.7 | 858 | Monday, October 22, 2018 | Approved | |
swig 3.0.6 | 13943 | Tuesday, July 7, 2015 | Approved | |
swig 3.0.5 | 3742 | Friday, May 22, 2015 | Approved | |
SWIG 3.0.4 | 236 | Tuesday, October 23, 2018 | Approved | |
SWIG 3.0.3 | 256 | Monday, October 22, 2018 | Approved | |
swig 3.0.2 | 6410 | Saturday, November 29, 2014 | Approved | |
SWIG 3.0.1 | 230 | Monday, October 22, 2018 | Approved | |
swig 3.0.0.20141127 | 400 | Friday, November 28, 2014 | Approved | |
swig 3.0.0 | 634 | Monday, May 19, 2014 | Unknown | |
swig 2.0.12 | 1099 | Tuesday, March 11, 2014 | Unknown | |
SWIG 2.0.11 | 258 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.10 | 331 | Monday, October 22, 2018 | Approved | |
swig 2.0.9 | 633 | Tuesday, December 18, 2012 | Unknown | |
SWIG 2.0.8 | 229 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.7 | 254 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.6 | 233 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.5 | 213 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.4 | 234 | Tuesday, October 23, 2018 | Approved | |
SWIG 2.0.3 | 218 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.2 | 234 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.1 | 229 | Monday, October 22, 2018 | Approved | |
SWIG 2.0.0 | 215 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.40 | 296 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.39 | 249 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.38 | 228 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.37 | 239 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.36 | 217 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.35 | 238 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.34 | 221 | Wednesday, October 24, 2018 | Approved | |
SWIG 1.3.33 | 221 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.32 | 259 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.31 | 305 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.30 | 236 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.29 | 231 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.28 | 243 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.27 | 232 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.25 | 207 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.24 | 197 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.23 | 225 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.22 | 220 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.21 | 168 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.20 | 194 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.19 | 199 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.18 | 188 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.17 | 148 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.16 | 201 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.15 | 185 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.14 | 189 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.13 | 172 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.12 | 180 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.11 | 203 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.10 | 181 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.9 | 189 | Tuesday, October 23, 2018 | Approved | |
SWIG 1.3.7 | 165 | Monday, October 22, 2018 | Approved | |
SWIG 1.3.6 | 217 | Monday, October 22, 2018 | Approved |
This package has no dependencies.
Ground Rules:
- This discussion is only about Simplified Wrapper and Interface Generator and the Simplified Wrapper and Interface Generator package. If you have feedback for Chocolatey, please contact the Google Group.
- This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
- The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
- Tell us what you love about the package or Simplified Wrapper and Interface Generator, or tell us what needs improvement.
- Share your experiences with the package, or extra configuration or gotchas that you've found.
- If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.