Merge branch 'master' into C

This commit is contained in:
Vadim Zeitlin 2019-07-24 20:26:50 +02:00
commit 55741f9e31
1702 changed files with 57386 additions and 21599 deletions

View file

@ -4,6 +4,7 @@ class
constants
contract
docstrings
doxygen
enum
exception
exceptproxy
@ -14,7 +15,6 @@ functor
import
import_template
import_packages
java
#libffi
multimap
operator

View file

@ -86,7 +86,7 @@ Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> op
<h2>A sample Python script</h2>
Click <a href="example.py">here</a> to see a script that calls the C++ functions from Python.
Click <a href="runme.py">here</a> to see a script that calls the C++ functions from Python.
<h2>Key points</h2>

View file

@ -17,7 +17,7 @@ to see a SWIG interface with some constant declarations in it.
<h2>Accessing Constants from Python</h2>
Click <a href="example.py">here</a> to see a script that prints out the values
Click <a href="runme.py">here</a> to see a script that prints out the values
of the constants contained in the above file.
<h2>Key points</h2>

View file

@ -0,0 +1,27 @@
TOP = ../..
SWIGEXE = $(TOP)/../swig
SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
CXXSRCS = example.cxx
TARGET = example
INTERFACE = example.i
LIBS = -lm
SWIGOPT = -doxygen
check: build
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run
build:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
SWIGOPT='$(SWIGOPT)' \
TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
static:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
SWIGOPT='$(SWIGOPT)' \
TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
clean:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean
rm -f example.html

View file

@ -0,0 +1,48 @@
/* File : example.cxx */
#include "example.h"
#define M_PI 3.14159265358979323846
/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
x += dx;
y += dy;
}
int Shape::nshapes = 0;
Circle::Circle(double r) : radius(r) {
NumCircles++;
}
double Circle::area() {
return M_PI*radius*radius;
}
double Circle::perimeter() {
return 2*M_PI*radius;
}
Square::Square(double w) : width(w) {
NumSquares++;
}
double Square::area() {
return width*width;
}
double Square::perimeter() {
return 4*width;
}
int NumSquares = 0;
int NumCircles = 0;
Square MakeSquare(double r) {
return Square(r);
}
Circle MakeCircle(double w) {
return Circle(w);
}

View file

@ -0,0 +1,152 @@
# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
CFG=example - Win32 Release
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "example.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "example - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c
# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c
# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "_DEBUG"
# ADD RSC /l 0x809 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_example.pyd" /pdbtype:sept
!ELSEIF "$(CFG)" == "example - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_example.pyd"
!ENDIF
# Begin Target
# Name "example - Win32 Debug"
# Name "example - Win32 Release"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\example.cxx
# End Source File
# Begin Source File
SOURCE=.\example_wrap.cxx
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\example.h
# End Source File
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# Begin Source File
SOURCE=.\example.i
!IF "$(CFG)" == "example - Win32 Debug"
# Begin Custom Build
InputPath=.\example.i
InputName=example
"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
echo In order to function correctly, please ensure the following environment variables are correctly set:
echo PYTHON_INCLUDE: %PYTHON_INCLUDE%
echo PYTHON_LIB: %PYTHON_LIB%
echo on
..\..\..\swig.exe -c++ -python "$(InputPath)"
# End Custom Build
!ELSEIF "$(CFG)" == "example - Win32 Release"
# Begin Custom Build
InputPath=.\example.i
InputName=example
"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
echo In order to function correctly, please ensure the following environment variables are correctly set:
echo PYTHON_INCLUDE: %PYTHON_INCLUDE%
echo PYTHON_LIB: %PYTHON_LIB%
echo on
..\..\..\swig.exe -c++ -python "$(InputPath)"
# End Custom Build
!ENDIF
# End Source File
# End Target
# End Project

View file

@ -0,0 +1,107 @@
/*! \file example.h
This file provides a simple set of Shape classes. */
/*! Base class for all shapes.
\author Bob
*/
class Shape {
public:
/*! Default constructor for creating a Shape */
Shape() {
nshapes++;
}
/*! Destructor for destroying a Shape */
virtual ~Shape() {
nshapes--;
}
double x; /*!< x co-ordinate */
double y; /*!< y co-ordinate */
void move(double dx, double dy); /*!< Move a shape to a new co-ordinate
\param dx x co-ordinate
\param dy y co-ordinate */
virtual double area() = 0; /*!< \return the area */
virtual double perimeter() = 0; /*!< \return the perimeter */
static int nshapes; /*!< Number of shapes currently in existence */
};
/*! A class for representing a circle.
\author Jack
*/
class Circle : public Shape {
private:
double radius;
public:
/*! Construct a circle
* \param r radius of the circle */
Circle(double r);
/*! Calculate the area of the circle
* \return calculated area */
virtual double area();
/*! Calculate the perimeter of the circle
* \return calculated perimeter of the circle */
virtual double perimeter();
};
/// A class for representing a square.
class Square : public Shape {
private:
double width;
public:
/** Construct a square
* \param w width of the square */
Square(double w);
/** Calculate the area of the square
* \return calculated area */
virtual double area();
/** Calculate the perimeter of the square
* \return calculated perimeter of the square */
virtual double perimeter();
};
/// A class for representing a rectangle, templated on the type for the rectangle dimensions
template<typename T>
class Rectangle : public Shape {
private:
T height;
T width;
public:
/** Construct a rectangle
* \param h height of the rectangle
* \param w width of the rectangle */
Rectangle(T h, T w) : height(h), width(w) {}
/** Calculate the area of the rectangle
* \return calculated area */
virtual double area() { return width*height; }
/** Calculate the perimeter of the rectangle
* \return calculated perimeter of the rectangle */
virtual double perimeter() { return 2*height + 2*width; }
};
/*! Factory function for creating a square
* \param r width of the square
* \return a fully constructed square */
Square MakeSquare(double r);
/*! Factory function for creating a circle
* \param w radius of the circle
* \return a fully constructed circle */
Circle MakeCircle(double w);
/*! Factory function for creating a rectangle
* \param h height of the rectangle
* \param w width of the rectangle
* \return a fully constructed rectangle */
template<typename T>
Rectangle<T> MakeRectangle(T h, T w) {
return Rectangle<T>(h, w);
}
/*! Total number of circles ever created */
extern int NumCircles;
/// Total number of squares ever created
extern int NumSquares;

View file

@ -0,0 +1,17 @@
%module example
%{
#include "example.h"
%}
%immutable NumSquares;
%immutable NumCircles;
%include "example.h"
/*! - this instantiation uses type int */
%template(RectangleInt) Rectangle<int>;
/*! - this instantiation uses type int */
%template(MakeRectangleInt) MakeRectangle<int>;

View file

@ -0,0 +1,28 @@
# 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"

View file

@ -19,7 +19,7 @@ of enumerated types are handled as integers.
<ul>
<li><a href="example.h">example.h</a>. Header file containing some enums.
<li><a href="example.i">example.i</a>. Interface file.
<li><a href="example.py">example.py</a>. Sample Python script.
<li><a href="runme.py">runme.py</a>. Sample Python script.
</ul>
<h2>Notes</h2>

View file

@ -1,6 +1,6 @@
/* File : example.h */
#include <string>
#include <string.h>
#ifndef SWIG
struct A {
};
@ -16,30 +16,26 @@ public:
char msg[256];
};
#if defined(_MSC_VER)
#pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#endif
class Test {
public:
int simple() throw(int) {
int simple() {
throw(37);
return 1;
}
int message() throw(const char *) {
int message() {
throw("I died.");
return 1;
}
int hosed() throw(Exc) {
int hosed() {
throw(Exc(42,"Hosed"));
return 1;
}
int unknown() throw(A*) {
int unknown() {
static A a;
throw &a;
return 1;
}
int multi(int x) throw(int, const char *, Exc) {
int multi(int x) {
if (x == 1) throw(37);
if (x == 2) throw("Bleah!");
if (x == 3) throw(Exc(42,"No-go-diggy-die"));
@ -47,7 +43,3 @@ public:
}
};
#if defined(_MSC_VER)
#pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#endif

View file

@ -7,6 +7,12 @@
%include "std_string.i"
%catches(int) Test::simple();
%catches(const char *) Test::message();
%catches(Exc) Test::hosed();
%catches(A*) Test::unknown();
%catches(int, const char *, Exc) Test::multi(int x);
/* Let's just grab the original header file here */
%include "example.h"

View file

@ -8,10 +8,6 @@ class FullError {
FullError(int m) : maxsize(m) { }
};
#if defined(_MSC_VER)
#pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#endif
template<typename T> class Queue {
int maxsize;
T *items;
@ -27,7 +23,7 @@ template<typename T> class Queue {
~Queue() {
delete [] items;
}
void enqueue(T x) throw(FullError) {
void enqueue(T x) {
if (nitems == maxsize) {
throw FullError(maxsize);
}
@ -47,8 +43,3 @@ template<typename T> class Queue {
}
};
#if defined(_MSC_VER)
#pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#endif

View file

@ -20,29 +20,12 @@
the header file, the enqueue method throws FullError and
the dequeue method throws EmptyError. Since we don't
want to define an exception handler for everything, we
simply write a handler each method individually.
simply write a handler for each method individually.
Note: the *::enqueue syntax means that we simply define
the handler for any class with this method defined.
*/
/*
First we need to 'disable' the default swig throw mechanism for the
FullError class. We do this by rethrowing the exception.
Note that this is necessary since the class appears in a throw
declaration:
void enqueue(T x) throw(FullError);
hence, swig recognizes it as an exception class and it will generate
the necessary code to catch it and rethrow it to the python side.
*/
%typemap(throws) FullError "(void)$1; throw;";
%exception *::enqueue {
try {
$action
@ -76,15 +59,15 @@
*/
/*
Now, the EmpytError doesn't appear in a throw declaration, and hence
we need to 'mark' it as an exception class. In python, classes that
are used as exception are 'special', and need to be wrapped as
'classic' ones.
This is a python issue, and if you don't mark the class, you will
see 'interesting' behaviours at the python side.
Python classes that are used as exceptions need to be subclasses of the
"Exception" class, and so SWIG needs to know which wrapped classes may be
used in this way. You can explicitly tell SWIG this by using
%exceptionclass. SWIG will implicitly set this feature for classes which
appear in a throw declaration, but it's not a problem to explicitly
mark such classes as well.
This is a Python requirement - if you fail to mark such classes with
%exceptionclass you may see 'interesting' behaviour on the Python side.
*/
%exceptionclass EmptyError;
%exceptionclass FullError;

View file

@ -18,7 +18,7 @@ class CEO(example.Manager):
# 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")
# the director wrappers to call CEO.getPosition.
e = CEO("Alice")
print e.getName(), "is a", e.getPosition()

View file

@ -65,7 +65,7 @@ Here are some files that illustrate this with a simple example:
<li><a href="example.c">example.c</a>
<li><a href="example.h">example.h</a>
<li><a href="example.i">example.i</a> (SWIG interface)
<li><a href="example.py">example.py</a> (Sample script)
<li><a href="runme.py">runme.py</a> (Sample script)
</ul>
<h2>Notes</h2>

View file

@ -8,11 +8,12 @@ import_packages_subdirs = \
from_init1 \
from_init2 \
from_init3 \
module_is_init \
relativeimport1 \
relativeimport2 \
relativeimport3 \
split_modules \
namespace_pkg
namespace_pkg \
check: build
@ -21,19 +22,19 @@ check: build
mkdir -p `dirname $$file`; \
cp "${SRCDIR}$$file" "$$file" || exit 1; \
done; \
fi; \
fi
for s in $(import_packages_subdirs); do \
(cd $$s && $(MAKE) check); \
(cd $$s && $(MAKE) check) || exit 1; \
done
build:
for s in $(import_packages_subdirs); do \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build) || exit 1; \
done
static:
for s in $(import_packages_subdirs); do \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static) || exit 1; \
done
clean:
@ -42,7 +43,7 @@ clean:
for file in `cd $(SRCDIR) && find . -type f -name "*.py"`; do \
rm -f "$$file" || exit 1; \
done; \
fi; \
fi
for s in $(import_packages_subdirs); do \
(cd $$s && $(MAKE) clean); \
(cd $$s && $(MAKE) clean) || exit 1; \
done

View file

@ -1,13 +1,35 @@
import sys
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

View file

@ -1,13 +1,31 @@
import sys
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

View file

@ -1,13 +1,31 @@
import sys
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

View file

@ -0,0 +1,15 @@
TOP = ../../..
LIBS =
check: build
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run
build:
cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build
static:
cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static
clean:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean
cd pkg1 && $(MAKE) clean

View file

@ -0,0 +1,18 @@
This example tests renaming the generated SWIG pure Python module to __init__.py
to turn the module into a Python package.
Use 'python runme.py' to run the test.
Overview:
---------
SWIG generates a pure Python module foo.py from the input interface file foo.i.
The foo.py file is generated within the pkg1 directory and is then renamed __init__.py.
This results in everything in the SWIG generated module being available in the Python
pkg1 package.
This approach of turning the SWIG generated module into a package worked in versions
of SWIG up to swig-3.0.8, but stopped working from swig-3.0.9 until it was
re-instated in swig-4.0.0. However, Python 2.7 or 3.3 and later are needed to
work out of the box. Python 3.2 does not work as this version of Python does
not set __package__ in __init__.py.

View file

@ -0,0 +1,20 @@
TOP = ../../../..
SWIGEXE = $(TOP)/../swig
SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
SWIGOPT =
LIBS =
build:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \
SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp
mv foo.py __init__.py
static:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \
SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static
clean:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean
rm -f __init__.py

View file

@ -0,0 +1,10 @@
int foofunction(int i) {
return i *= 10;
}
struct FooClass {
int foomethod(int i) {
return i += 5;
}
};

View file

@ -0,0 +1,5 @@
%module foo
%{
#include "./foo.hpp"
%}
%include "./foo.hpp"

View file

@ -0,0 +1,26 @@
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"

View file

@ -1,5 +1,22 @@
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")
assert(robin.run() == "AWAY!")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m robin"
run_except_on_windows(commandline)

View file

@ -1,7 +1,23 @@
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')
sys.path.insert(0, "path1")
from brave import robin
print(" Finished from brave import robin")
assert(robin.run() == "AWAY!")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m brave.robin"
run_except_on_windows(commandline, env = {"PYTHONPATH": "path1"})

View file

@ -1,11 +1,17 @@
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']
dirs = ["path1", "path2", "path3"]
# Clean out any old package paths
for d in dirs:
@ -14,20 +20,20 @@ def copyMods():
for d in dirs:
os.mkdir(d)
os.mkdir(os.path.join(d, 'brave'))
os.mkdir(os.path.join(d, "brave"))
shutil.copy('robin.py', os.path.join('path1', 'brave'))
os.system('cp _robin.* ' + os.path.join('path1', 'brave'))
shutil.copy("robin.py", os.path.join("path1", "brave"))
subprocess.check_call("cp _robin.* " + os.path.join("path1", "brave"), shell=True)
shutil.copy('robin.py', os.path.join('path2', 'brave'))
os.system('cp _robin.* ' + os.path.join('path3', 'brave'))
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.writestr("brave/", b"")
zf.write("robin.py", "brave/robin.py")
zf.close()
@ -35,10 +41,10 @@ def main():
copyMods()
# Run each test with a separate interpreter
os.system(sys.executable + " nonpkg.py")
os.system(sys.executable + " normal.py")
os.system(sys.executable + " split.py")
os.system(sys.executable + " zipsplit.py")
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__":

View file

@ -1,7 +1,8 @@
# These examples rely on namespace packages. Don't
# run them for old python interpreters.
import sys
import os.path
import subprocess
import sys
testname = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
print "Testing " + testname + " - namespace packages"

View file

@ -1,9 +1,25 @@
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')
sys.path.insert(0, "path2")
sys.path.insert(0, "path3")
from brave import robin
print(" Finished from brave import robin")
assert(robin.run() == "AWAY!")
if not(robin.run() == "AWAY!"):
raise RuntimeError("test failed")
commandline = sys.executable + " -m brave.robin"
run_except_on_windows(commandline , env = {"PYTHONPATH": "path2:path3"})

View file

@ -1,9 +1,25 @@
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')
sys.path.insert(0, "path4.zip")
sys.path.insert(0, "path3")
from brave import robin
print(" Finished from brave import robin")
assert(robin.run() == "AWAY!")
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"})

View file

@ -1,13 +1,32 @@
import sys
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)

View file

@ -1,13 +1,32 @@
import sys
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)

View file

@ -1,13 +1,32 @@
import sys
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)

View file

@ -1,4 +1,12 @@
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__)))
@ -10,10 +18,9 @@ print " Finished importing pkg2.foo"
var2 = pkg2.foo.Pkg2_Foo()
classname = str(type(var2))
# Check for an old-style class if swig was run in -classic mode
if classname == "<type 'instance'>":
classname = str(var2.__class__)
if classname.find("pkg2.foo.Pkg2_Foo") == -1:
raise RuntimeError("failed type checking: " + classname)
print " Successfully created object pkg2.foo.Pkg2_Foo"
commandline = sys.executable + " -m pkg2.foo"
run_except_on_windows(commandline)

View file

@ -1,4 +1,12 @@
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"
@ -9,10 +17,9 @@ print " Finished importing pkg1.pkg2.foo"
var2 = pkg1.pkg2.foo.Pkg2_Foo()
classname = str(type(var2))
# Check for an old-style class if swig was run in -classic mode
if classname == "<type 'instance'>":
classname = str(var2.__class__)
if classname.find("pkg1.pkg2.foo.Pkg2_Foo") == -1:
raise RuntimeError("failed type checking: " + classname)
print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo"
commandline = sys.executable + " -m pkg1.pkg2.foo"
run_except_on_windows(commandline)

View file

@ -6,21 +6,21 @@ subdirs = vanilla vanilla_split
check: build
for s in $(subdirs); do \
(cd $$s && $(MAKE) check); \
(cd $$s && $(MAKE) check) || exit 1; \
done
build:
for s in $(subdirs); do \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build) || exit 1; \
done
static:
for s in $(subdirs); do \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \
(cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static) || exit 1; \
done
clean:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean
for s in $(subdirs); do \
(cd $$s && $(MAKE) clean); \
(cd $$s && $(MAKE) clean) || exit 1; \
done

View file

@ -2,6 +2,9 @@
between two packages. Specifically the pure python part is part of a package
and the C/C++ part is not in any package at all. Historically SWIG has
supported this sort of thing.
From SWIG 4.0.0 onwards, split modules are not supported by default.
The %module directive needs to be customised with the moduleimport attribute
in order to import the a global C/C++ module.
vanilla # "plane Jane" module both halves in pkg1
vanilla_split # python 1/2 in pkg1 C 1/2 in global namespace

View file

@ -1,4 +1,12 @@
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"
@ -7,4 +15,8 @@ import pkg1.foo
print " Finished importing pkg1.foo"
assert(pkg1.foo.count() == 3)
if not(pkg1.foo.count() == 3):
raise RuntimeError("test failed")
commandline = sys.executable + " -m pkg1.foo"
run_except_on_windows(commandline)

View file

@ -19,4 +19,6 @@ static:
clean:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean
cd pkg1 && $(MAKE) -f $(TOP)/../Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean
if test -d pkg1; then \
cd pkg1 && $(MAKE) -f $(TOP)/../Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean; \
fi

View file

@ -1,4 +1,9 @@
%module(package="pkg1") foo
#if defined(SWIGPYTHON_BUILTIN) /* defined when using -builtin */
%module(package="pkg1", moduleimport="from $module import *") foo
#else
%module(package="pkg1", moduleimport="import $module") foo
#endif
%{
static unsigned count(void)
{

View file

@ -1,4 +1,12 @@
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"
@ -7,4 +15,8 @@ import pkg1.foo
print " Finished importing pkg1.foo"
assert(pkg1.foo.count() == 3)
if not(pkg1.foo.count() == 3):
raise RuntimeError("test failed")
commandline = sys.executable + " -m pkg1.foo"
run_except_on_windows(commandline)

View file

@ -1,29 +0,0 @@
public class Example {
public int mPublicInt;
public Example() {
mPublicInt = 0;
}
public Example(int IntVal) {
mPublicInt = IntVal;
}
public int Add(int a, int b) {
return (a+b);
}
public float Add(float a, float b) {
return (a+b);
}
public String Add(String a, String b) {
return (a+b);
}
public Example Add(Example a, Example b) {
return new Example(a.mPublicInt + b.mPublicInt);
}
}

View file

@ -1,25 +0,0 @@
TOP = ../..
SWIGEXE = $(TOP)/../swig
SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
CXXSRCS =
TARGET = example
INTERFACE = example.i
LIBS = -lm
check: build
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run
build: Example.class Example.h
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \
SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
CXXSHARED="gcj -fpic -shared Example.class" DEFS='' LIBS="-lstdc++" python_cpp
clean:
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean
rm -f $(TARGET).py
rm -f *.class Example.h
Example.class Example.h: $(SRCDIR)Example.java
gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java
gcjh Example.class

View file

@ -1,13 +0,0 @@
%module example
%include <cni.i>
%{
#include "Example.h"
%}
%include Example.h
%extend Example {
~Example() {}
}

View file

@ -1,16 +0,0 @@
from example import *
JvCreateJavaVM(None)
JvAttachCurrentThread(None, None)
e1 = Example(1)
e2 = Example(2)
print e1.Add(1, 2)
print e1.Add(1.0, 2.0)
e3 = e1.Add(e1, e2)
print e3.mPublicInt
print e1.Add("1", "2")
JvDetachCurrentThread()

View file

@ -20,7 +20,7 @@
PyObject *o = PyTuple_GetItem(varargs,i);
if (!PyString_Check(o)) {
PyErr_SetString(PyExc_ValueError,"Expected a string");
return NULL;
SWIG_fail;
}
argv[i] = PyString_AsString(o);
}
@ -58,11 +58,11 @@
&ffi_type_uint, types) == FFI_OK) {
ffi_call(&cif, (void (*)()) execlp, &result, values);
} else {
PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
free(types);
free(values);
free(arg3);
return NULL;
PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
SWIG_fail;
}
free(types);
free(values);
@ -107,9 +107,9 @@ int execlp(const char *path, const char *arg1, ...);
argv[i].type = VT_POINTER;
argv[i].val.pvalue = (void *) PyString_AsString(o);
} else {
PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
free(argv);
return NULL;
PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
SWIG_fail;
}
}
@ -157,11 +157,11 @@ int execlp(const char *path, const char *arg1, ...);
&ffi_type_uint, types) == FFI_OK) {
ffi_call(&cif, (void (*)()) printf, &result, values);
} else {
PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
free(types);
free(values);
free(args);
return NULL;
PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
SWIG_fail;
}
free(types);
free(values);

View file

@ -39,7 +39,11 @@ extern int gcd(int x, int y);
%#if PY_VERSION_HEX >= 0x03000000
{
PyObject *utf8str = PyUnicode_AsUTF8String(s);
const char *cstr = PyBytes_AsString(utf8str);
const char *cstr;
if (!utf8str) {
SWIG_fail;
}
cstr = PyBytes_AsString(utf8str);
$2[i] = strdup(cstr);
Py_DECREF(utf8str);
}
@ -69,9 +73,12 @@ extern int gcdmain(int argc, char *argv[]);
PyObject *utf8str;
if (!PyUnicode_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a string");
return NULL;
SWIG_fail;
}
utf8str = PyUnicode_AsUTF8String($input);
if (!utf8str) {
SWIG_fail;
}
PyBytes_AsStringAndSize(utf8str, &cstr, &len);
$1 = strncpy((char *)malloc(len+1), cstr, (size_t)len);
$2 = (int)len;
@ -79,7 +86,7 @@ extern int gcdmain(int argc, char *argv[]);
%#else
if (!PyString_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a string");
return NULL;
SWIG_fail;
}
$1 = PyString_AsString($input);
$2 = (int)PyString_Size($input);
@ -105,6 +112,9 @@ extern int count(char *bytes, int len, char c);
char *cstr;
Py_ssize_t len;
PyObject *utf8str = PyUnicode_AsUTF8String($input);
if (!utf8str) {
SWIG_fail;
}
PyBytes_AsStringAndSize(utf8str, &cstr, &len);
$1 = strncpy((char *)malloc(len+1), cstr, (size_t)len);
$2 = (int)len;

View file

@ -17,6 +17,7 @@
%include "example.h"
/* An output method that turns a complex into a short string */
%feature("python:slot", "tp_str", functype="reprfunc") Complex::__str__; // For -builtin option to use __str__ in the tp_str slot
%extend Complex {
char *__str__() {
static char temp[512];

View file

@ -1,5 +1,5 @@
import sys
sys.path.append('..')
sys.path.append("..")
import harness

View file

@ -1,5 +1,5 @@
import sys
sys.path.append('..')
sys.path.append("..")
import harness

View file

@ -17,16 +17,16 @@ def run(proc):
except IndexError:
proc = Popen(
[sys.executable, 'runme.py', 'Simple_baseline'], stdout=PIPE)
[sys.executable, "runme.py", "Simple_baseline"], stdout=PIPE)
(stdout, stderr) = proc.communicate()
print stdout
proc = Popen(
[sys.executable, 'runme.py', 'Simple_optimized'], stdout=PIPE)
[sys.executable, "runme.py", "Simple_optimized"], stdout=PIPE)
(stdout, stderr) = proc.communicate()
print stdout
proc = Popen(
[sys.executable, 'runme.py', 'Simple_builtin'], stdout=PIPE)
[sys.executable, "runme.py", "Simple_builtin"], stdout=PIPE)
(stdout, stderr) = proc.communicate()
print stdout

View file

@ -1,5 +1,5 @@
import sys
sys.path.append('..')
sys.path.append("..")
import harness

View file

@ -1,5 +1,5 @@
import sys
sys.path.append('..')
sys.path.append("..")
import harness

View file

@ -1,5 +1,5 @@
import sys
sys.path.append('..')
sys.path.append("..")
import harness

View file

@ -145,7 +145,7 @@ extraction.
<ul>
<li> <a href="example.c">example.c</a> (C Source)
<li> <a href="example.i">example.i</a> (SWIG interface)
<li> <a href="example.py">example.py</a> (Python Script)
<li> <a href="runme.py">runme.py</a> (Python Script)
</ul>
<h2>Notes</h2>

View file

@ -121,7 +121,7 @@ Click <a href="example.i">here</a> to see a SWIG interface file with these addit
<h2>Sample Python script</h2>
Click <a href="example.py">here</a> to see a script that manipulates some C++ references.
Click <a href="runme.py">here</a> to see a script that manipulates some C++ references.
<h2>Notes:</h2>

View file

@ -65,7 +65,7 @@ to create the extension <tt>examplemodule.so</tt>.
<h2>Using the extension</h2>
Click <a href="example.py">here</a> to see a script that calls our C functions from Python.
Click <a href="runme.py">here</a> to see a script that calls our C functions from Python.
<h2>Key points</h2>

View file

@ -17,9 +17,8 @@ std::vector<double> half(const std::vector<double>& v) {
}
void halve_in_place(std::vector<double>& v) {
// would you believe this is the same as the above?
std::transform(v.begin(),v.end(),v.begin(),
std::bind2nd(std::divides<double>(),2.0));
for (std::vector<double>::iterator it = v.begin(); it != v.end(); ++it)
*it /= 2.0;
}

View file

@ -48,7 +48,7 @@ double foo;
</blockquote>
it will be accessed in the Python module as <tt>cvar.foo</tt>. Click
<a href="example.py">here</a> to see a script that updates and prints
<a href="runme.py">here</a> to see a script that updates and prints
out the values of the variables using this technique.
<h2>Key points</h2>

View file

@ -48,18 +48,18 @@ example.print_vars()
print "\nNow I'm going to try and modify some read only variables"
print " Tring to set 'path'"
print " Trying to set 'path'"
try:
example.cvar.path = "Whoa!"
print "Hey, what's going on?!?! This shouldn't work"
except:
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:
except Exception:
print "Good."