diff --git a/INSTALL b/INSTALL index 5672f02c1351..81f8939c48bb 100644 --- a/INSTALL +++ b/INSTALL @@ -257,12 +257,8 @@ Required libraries that ship with matplotlib agg template source statically, so it will not affect anything on your system outside of matplotlib. -`PyCXX` 6.2.4 - A library for writing Python extensions in C++. - `qhull` 2012.1 - A library for computing convex hulls. Used for computing triangulation - and meshes. + A library for computing Delaunay triangulations. `ttconv` truetype font utility diff --git a/doc/devel/coding_guide.rst b/doc/devel/coding_guide.rst index cd12a126942a..e9fe99d2c4a4 100644 --- a/doc/devel/coding_guide.rst +++ b/doc/devel/coding_guide.rst @@ -152,10 +152,11 @@ C/C++ extensions address C++, but most of its admonitions still apply). * Interfacing with Python may be done either with the raw Python/C API - or Cython. Use of PyCXX is discouraged for new code. + or Cython. * Python/C interface code should be kept separate from the core C/C++ - code. The interface code should be named `FOO_wrap.cpp`. + code. The interface code should be named `FOO_wrap.cpp` or + `FOO_wrapper.cpp`. * Header file documentation (aka docstrings) should be in Numpydoc format. We don't plan on using automated tools for these diff --git a/extern/CXX/Config.hxx b/extern/CXX/Config.hxx deleted file mode 100644 index 536e7c88201f..000000000000 --- a/extern/CXX/Config.hxx +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "CXX/Python2/Config.hxx" -#else -#include "CXX/Python3/Config.hxx" -#endif diff --git a/extern/CXX/Exception.hxx b/extern/CXX/Exception.hxx deleted file mode 100644 index d4ab4ec76980..000000000000 --- a/extern/CXX/Exception.hxx +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "CXX/Python2/Exception.hxx" -#else -#include "CXX/Python3/Exception.hxx" -#endif diff --git a/extern/CXX/Extensions.hxx b/extern/CXX/Extensions.hxx deleted file mode 100644 index a4cd2669a2db..000000000000 --- a/extern/CXX/Extensions.hxx +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "CXX/Python2/Extensions.hxx" -#else -#include "CXX/Python3/Extensions.hxx" -#endif diff --git a/extern/CXX/IndirectPythonInterface.cxx b/extern/CXX/IndirectPythonInterface.cxx deleted file mode 100644 index 256bd7ebda80..000000000000 --- a/extern/CXX/IndirectPythonInterface.cxx +++ /dev/null @@ -1,557 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#include "CXX/IndirectPythonInterface.hxx" - -namespace Py -{ -bool _CFunction_Check( PyObject *op ) { return op->ob_type == _CFunction_Type(); } -bool _Complex_Check( PyObject *op ) { return op->ob_type == _Complex_Type(); } -bool _Dict_Check( PyObject *op ) { return op->ob_type == _Dict_Type(); } -bool _Float_Check( PyObject *op ) { return op->ob_type == _Float_Type(); } -bool _Function_Check( PyObject *op ) { return op->ob_type == _Function_Type(); } -bool _Boolean_Check( PyObject *op ) { return op->ob_type == _Bool_Type(); } -bool _List_Check( PyObject *op ) { return op->ob_type == _List_Type(); } -bool _Long_Check( PyObject *op ) { return op->ob_type == _Long_Type(); } -bool _Method_Check( PyObject *op ) { return op->ob_type == _Method_Type(); } -bool _Module_Check( PyObject *op ) { return op->ob_type == _Module_Type(); } -bool _Range_Check( PyObject *op ) { return op->ob_type == _Range_Type(); } -bool _Slice_Check( PyObject *op ) { return op->ob_type == _Slice_Type(); } -bool _TraceBack_Check( PyObject *op ) { return op->ob_type == _TraceBack_Type(); } -bool _Tuple_Check( PyObject *op ) { return op->ob_type == _Tuple_Type(); } -bool _Type_Check( PyObject *op ) { return op->ob_type == _Type_Type(); } -bool _Unicode_Check( PyObject *op ) { return op->ob_type == _Unicode_Type(); } -#if PY_MAJOR_VERSION == 2 -bool _String_Check( PyObject *op ) { return op->ob_type == _String_Type(); } -bool _Int_Check( PyObject *op ) { return op->ob_type == _Int_Type(); } -bool _CObject_Check( PyObject *op ) { return op->ob_type == _CObject_Type(); } -#endif -#if PY_MAJOR_VERSION >= 3 -bool _Bytes_Check( PyObject *op ) { return op->ob_type == _Bytes_Type(); } -#endif - -#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL) - -#if defined(MS_WINDOWS) -#include - - -static HMODULE python_dll; - -static PyObject *ptr__Exc_ArithmeticError = NULL; -static PyObject *ptr__Exc_AssertionError = NULL; -static PyObject *ptr__Exc_AttributeError = NULL; -static PyObject *ptr__Exc_EnvironmentError = NULL; -static PyObject *ptr__Exc_EOFError = NULL; -static PyObject *ptr__Exc_Exception = NULL; -static PyObject *ptr__Exc_FloatingPointError = NULL; -static PyObject *ptr__Exc_ImportError = NULL; -static PyObject *ptr__Exc_IndexError = NULL; -static PyObject *ptr__Exc_IOError = NULL; -static PyObject *ptr__Exc_KeyboardInterrupt = NULL; -static PyObject *ptr__Exc_KeyError = NULL; -static PyObject *ptr__Exc_LookupError = NULL; -static PyObject *ptr__Exc_MemoryError = NULL; -static PyObject *ptr__Exc_NameError = NULL; -static PyObject *ptr__Exc_NotImplementedError = NULL; -static PyObject *ptr__Exc_OSError = NULL; -static PyObject *ptr__Exc_OverflowError = NULL; -static PyObject *ptr__Exc_RuntimeError = NULL; -static PyObject *ptr__Exc_StandardError = NULL; -static PyObject *ptr__Exc_SyntaxError = NULL; -static PyObject *ptr__Exc_SystemError = NULL; -static PyObject *ptr__Exc_SystemExit = NULL; -static PyObject *ptr__Exc_TypeError = NULL; -static PyObject *ptr__Exc_ValueError = NULL; -static PyObject *ptr__Exc_ZeroDivisionError = NULL; - -#ifdef MS_WINDOWS -static PyObject *ptr__Exc_WindowsError = NULL; -#endif - -static PyObject *ptr__Exc_IndentationError = NULL; -static PyObject *ptr__Exc_TabError = NULL; -static PyObject *ptr__Exc_UnboundLocalError = NULL; -static PyObject *ptr__Exc_UnicodeError = NULL; -static PyObject *ptr__PyNone = NULL; -static PyObject *ptr__PyFalse = NULL; -static PyObject *ptr__PyTrue = NULL; -static PyTypeObject *ptr__CFunction_Type = NULL; -static PyTypeObject *ptr__Complex_Type = NULL; -static PyTypeObject *ptr__Dict_Type = NULL; -static PyTypeObject *ptr__Float_Type = NULL; -static PyTypeObject *ptr__Function_Type = NULL; -static PyTypeObject *ptr__Bool_Type = NULL; -static PyTypeObject *ptr__List_Type = NULL; -static PyTypeObject *ptr__Long_Type = NULL; -static PyTypeObject *ptr__Method_Type = NULL; -static PyTypeObject *ptr__Module_Type = NULL; -static PyTypeObject *ptr__Range_Type = NULL; -static PyTypeObject *ptr__Slice_Type = NULL; -static PyTypeObject *ptr__TraceBack_Type = NULL; -static PyTypeObject *ptr__Tuple_Type = NULL; -static PyTypeObject *ptr__Type_Type = NULL; -#if PY_MAJOR_VERSION == 2 -static PyTypeObject *ptr__Int_Type = NULL; -static PyTypeObject *ptr__String_Type = NULL; -static PyTypeObject *ptr__CObject_Type = NULL; -#endif -#if PY_MAJOR_VERSION >= 3 -static PyTypeObject *ptr__Bytes_Type = NULL; -#endif - - -static int *ptr_Py_DebugFlag = NULL; -static int *ptr_Py_InteractiveFlag = NULL; -static int *ptr_Py_OptimizeFlag = NULL; -static int *ptr_Py_NoSiteFlag = NULL; -static int *ptr_Py_VerboseFlag = NULL; - -static char **ptr__Py_PackageContext = NULL; - -#ifdef Py_REF_DEBUG -int *ptr_Py_RefTotal; -#endif - - -//-------------------------------------------------------------------------------- -class GetAddressException -{ -public: - GetAddressException( const char *_name ) - : name( _name ) - {} - virtual ~GetAddressException() {} - const char *name; -}; - - -//-------------------------------------------------------------------------------- -static PyObject *GetPyObjectPointer_As_PyObjectPointer( const char *name ) -{ - FARPROC addr = GetProcAddress( python_dll, name ); - if( addr == NULL ) - throw GetAddressException( name ); - - return *(PyObject **)addr; -} - -static PyObject *GetPyObject_As_PyObjectPointer( const char *name ) -{ - FARPROC addr = GetProcAddress( python_dll, name ); - if( addr == NULL ) - throw GetAddressException( name ); - - return (PyObject *)addr; -} - -static PyTypeObject *GetPyTypeObjectPointer_As_PyTypeObjectPointer( const char *name ) -{ - FARPROC addr = GetProcAddress( python_dll, name ); - if( addr == NULL ) - throw GetAddressException( name ); - - return *(PyTypeObject **)addr; -} - -static PyTypeObject *GetPyTypeObject_As_PyTypeObjectPointer( const char *name ) -{ - FARPROC addr = GetProcAddress( python_dll, name ); - if( addr == NULL ) - throw GetAddressException( name ); - - return (PyTypeObject *)addr; -} - -static int *GetInt_as_IntPointer( const char *name ) -{ - FARPROC addr = GetProcAddress( python_dll, name ); - if( addr == NULL ) - throw GetAddressException( name ); - - return (int *)addr; -} - -static char **GetCharPointer_as_CharPointerPointer( const char *name ) -{ - FARPROC addr = GetProcAddress( python_dll, name ); - if( addr == NULL ) - throw GetAddressException( name ); - - return (char **)addr; -} - - -#ifdef _DEBUG -static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d_D.DLL"; -#else -static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d.DLL"; -#endif - -//-------------------------------------------------------------------------------- -bool InitialisePythonIndirectInterface() -{ - char python_dll_name[sizeof(python_dll_name_format)]; - - _snprintf( python_dll_name, sizeof(python_dll_name_format) / sizeof(char) - 1, python_dll_name_format, PY_MAJOR_VERSION, PY_MINOR_VERSION ); - - python_dll = LoadLibraryA( python_dll_name ); - if( python_dll == NULL ) - return false; - - try - { -#ifdef Py_REF_DEBUG - ptr_Py_RefTotal = GetInt_as_IntPointer( "_Py_RefTotal" ); -#endif - ptr_Py_DebugFlag = GetInt_as_IntPointer( "Py_DebugFlag" ); - ptr_Py_InteractiveFlag = GetInt_as_IntPointer( "Py_InteractiveFlag" ); - ptr_Py_OptimizeFlag = GetInt_as_IntPointer( "Py_OptimizeFlag" ); - ptr_Py_NoSiteFlag = GetInt_as_IntPointer( "Py_NoSiteFlag" ); - ptr_Py_VerboseFlag = GetInt_as_IntPointer( "Py_VerboseFlag" ); - ptr__Py_PackageContext = GetCharPointer_as_CharPointerPointer( "_Py_PackageContext" ); - - ptr__Exc_ArithmeticError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ArithmeticError" ); - ptr__Exc_AssertionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AssertionError" ); - ptr__Exc_AttributeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AttributeError" ); - ptr__Exc_EnvironmentError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EnvironmentError" ); - ptr__Exc_EOFError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EOFError" ); - ptr__Exc_Exception = GetPyObjectPointer_As_PyObjectPointer( "PyExc_Exception" ); - ptr__Exc_FloatingPointError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_FloatingPointError" ); - ptr__Exc_ImportError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ImportError" ); - ptr__Exc_IndexError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndexError" ); - ptr__Exc_IOError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IOError" ); - ptr__Exc_KeyboardInterrupt = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyboardInterrupt" ); - ptr__Exc_KeyError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyError" ); - ptr__Exc_LookupError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_LookupError" ); - ptr__Exc_MemoryError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_MemoryError" ); - ptr__Exc_NameError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_NameError" ); - ptr__Exc_NotImplementedError= GetPyObjectPointer_As_PyObjectPointer( "PyExc_NotImplementedError" ); - ptr__Exc_OSError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OSError" ); - ptr__Exc_OverflowError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OverflowError" ); - ptr__Exc_RuntimeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_RuntimeError" ); - ptr__Exc_StandardError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_StandardError" ); - ptr__Exc_SyntaxError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SyntaxError" ); - ptr__Exc_SystemError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemError" ); - ptr__Exc_SystemExit = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemExit" ); - ptr__Exc_TypeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TypeError" ); - ptr__Exc_ValueError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ValueError" ); -#ifdef MS_WINDOWS - ptr__Exc_WindowsError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_WindowsError" ); -#endif - ptr__Exc_ZeroDivisionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ZeroDivisionError" ); - ptr__Exc_IndentationError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndentationError" ); - ptr__Exc_TabError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TabError" ); - ptr__Exc_UnboundLocalError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnboundLocalError" ); - ptr__Exc_UnicodeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnicodeError" ); - ptr__PyNone = GetPyObject_As_PyObjectPointer( "_Py_NoneStruct" ); - - ptr__PyFalse = GetPyObject_As_PyObjectPointer( "_Py_ZeroStruct" ); - ptr__PyTrue = GetPyObject_As_PyObjectPointer( "_Py_TrueStruct" ); - - ptr__CFunction_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCFunction_Type" ); - ptr__Complex_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyComplex_Type" ); - ptr__Dict_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyDict_Type" ); - ptr__Float_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFloat_Type" ); - ptr__Function_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFunction_Type" ); - ptr__Bool_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyBool_Type" ); - ptr__List_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyList_Type" ); - ptr__Long_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyLong_Type" ); - ptr__Method_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyMethod_Type" ); - ptr__Module_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyModule_Type" ); - ptr__Range_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyRange_Type" ); - ptr__Slice_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PySlice_Type" ); - ptr__TraceBack_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTraceBack_Type" ); - ptr__Tuple_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTuple_Type" ); - ptr__Type_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyType_Type" ); - ptr__Unicode_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyUnicode_Type" ); -#if PY_MAJOR_VERSION == 2 - ptr__String_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyString_Type" ); - ptr__Int_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyInt_Type" ); - ptr__CObject_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCObject_Type" ); -#endif -#if PY_MAJOR_VERSION >= 3 - ptr__Bytes_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyBytes_Type" ); -#endif - } - catch( GetAddressException &e ) - { - OutputDebugStringA( python_dll_name ); - OutputDebugStringA( " does not contain symbol " ); - OutputDebugStringA( e.name ); - OutputDebugStringA( "\n" ); - - return false; - } - - return true; -} - -// -// Wrap variables as function calls -// -PyObject *_Exc_ArithmeticError() { return ptr__Exc_ArithmeticError; } -PyObject *_Exc_AssertionError() { return ptr__Exc_AssertionError; } -PyObject *_Exc_AttributeError() { return ptr__Exc_AttributeError; } -PyObject *_Exc_EnvironmentError() { return ptr__Exc_EnvironmentError; } -PyObject *_Exc_EOFError() { return ptr__Exc_EOFError; } -PyObject *_Exc_Exception() { return ptr__Exc_Exception; } -PyObject *_Exc_FloatingPointError() { return ptr__Exc_FloatingPointError; } -PyObject *_Exc_ImportError() { return ptr__Exc_ImportError; } -PyObject *_Exc_IndexError() { return ptr__Exc_IndexError; } -PyObject *_Exc_IOError() { return ptr__Exc_IOError; } -PyObject *_Exc_KeyboardInterrupt() { return ptr__Exc_KeyboardInterrupt; } -PyObject *_Exc_KeyError() { return ptr__Exc_KeyError; } -PyObject *_Exc_LookupError() { return ptr__Exc_LookupError; } -PyObject *_Exc_MemoryError() { return ptr__Exc_MemoryError; } -PyObject *_Exc_NameError() { return ptr__Exc_NameError; } -PyObject *_Exc_NotImplementedError() { return ptr__Exc_NotImplementedError; } -PyObject *_Exc_OSError() { return ptr__Exc_OSError; } -PyObject *_Exc_OverflowError() { return ptr__Exc_OverflowError; } -PyObject *_Exc_RuntimeError() { return ptr__Exc_RuntimeError; } -PyObject *_Exc_StandardError() { return ptr__Exc_StandardError; } -PyObject *_Exc_SyntaxError() { return ptr__Exc_SyntaxError; } -PyObject *_Exc_SystemError() { return ptr__Exc_SystemError; } -PyObject *_Exc_SystemExit() { return ptr__Exc_SystemExit; } -PyObject *_Exc_TypeError() { return ptr__Exc_TypeError; } -PyObject *_Exc_ValueError() { return ptr__Exc_ValueError; } -#ifdef MS_WINDOWS -PyObject *_Exc_WindowsError() { return ptr__Exc_WindowsError; } -#endif -PyObject *_Exc_ZeroDivisionError() { return ptr__Exc_ZeroDivisionError; } -PyObject *_Exc_IndentationError() { return ptr__Exc_IndentationError; } -PyObject *_Exc_TabError() { return ptr__Exc_TabError; } -PyObject *_Exc_UnboundLocalError() { return ptr__Exc_UnboundLocalError; } -PyObject *_Exc_UnicodeError() { return ptr__Exc_UnicodeError; } - -// -// wrap items in Object.h -// -PyObject *_None() { return ptr__PyNone; } - -PyObject *_False() { return ptr__PyFalse; } -PyObject *_True() { return ptr__PyTrue; } - -PyTypeObject *_CFunction_Type() { return ptr__CFunction_Type; } -PyTypeObject *_Complex_Type() { return ptr__Complex_Type; } -PyTypeObject *_Dict_Type() { return ptr__Dict_Type; } -PyTypeObject *_Float_Type() { return ptr__Float_Type; } -PyTypeObject *_Function_Type() { return ptr__Function_Type; } -PyTypeObject *_Bool_Type() { return ptr__Bool_Type; } -PyTypeObject *_List_Type() { return ptr__List_Type; } -PyTypeObject *_Long_Type() { return ptr__Long_Type; } -PyTypeObject *_Method_Type() { return ptr__Method_Type; } -PyTypeObject *_Module_Type() { return ptr__Module_Type; } -PyTypeObject *_Range_Type() { return ptr__Range_Type; } -PyTypeObject *_Slice_Type() { return ptr__Slice_Type; } -PyTypeObject *_TraceBack_Type() { return ptr__TraceBack_Type; } -PyTypeObject *_Tuple_Type() { return ptr__Tuple_Type; } -PyTypeObject *_Type_Type() { return ptr__Type_Type; } -PyTypeObject *_Unicode_Type() { return ptr__Unicode_Type; } -#if PY_MAJOR_VERSION == 2 -PyTypeObject *_String_Type() { return ptr__String_Type; } -PyTypeObject *_Int_Type() { return ptr__Int_Type; } -PyTypeObject *_CObject_Type() { return ptr__CObject_Type; } -#endif -#if PY_MAJOR_VERSION >= 3 -PyTypeObject *_Bytes_Type() { return ptr__Bytes_Type; } -#endif - -char *__Py_PackageContext() { return *ptr__Py_PackageContext; } - - -// -// wrap the Python Flag variables -// -int &_Py_DebugFlag() { return *ptr_Py_DebugFlag; } -int &_Py_InteractiveFlag() { return *ptr_Py_InteractiveFlag; } -int &_Py_OptimizeFlag() { return *ptr_Py_OptimizeFlag; } -int &_Py_NoSiteFlag() { return *ptr_Py_NoSiteFlag; } -int &_Py_VerboseFlag() { return *ptr_Py_VerboseFlag; } - -#if 0 -#define Py_INCREF(op) ( \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - ((PyObject*)(op))->ob_refcnt++) - -#define Py_DECREF(op) \ - if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ - --((PyObject*)(op))->ob_refcnt != 0) \ - _Py_CHECK_REFCNT(op) \ - else \ - _Py_Dealloc((PyObject *)(op)) -#endif - -void _XINCREF( PyObject *op ) -{ - // This function must match the contents of Py_XINCREF(op) - if( op == NULL ) - return; - -#ifdef Py_REF_DEBUG - (*ptr_Py_RefTotal)++; -#endif - (op)->ob_refcnt++; - -} - -void _XDECREF( PyObject *op ) -{ - // This function must match the contents of Py_XDECREF(op); - if( op == NULL ) - return; - -#ifdef Py_REF_DEBUG - (*ptr_Py_RefTotal)--; -#endif - - if (--(op)->ob_refcnt == 0) - _Py_Dealloc((PyObject *)(op)); -} - - -#else -#error "Can only delay load under Win32" -#endif - -#else - -//================================================================================ -// -// Map onto Macros -// -//================================================================================ - -// -// Wrap variables as function calls -// - -PyObject *_Exc_ArithmeticError() { return ::PyExc_ArithmeticError; } -PyObject *_Exc_AssertionError() { return ::PyExc_AssertionError; } -PyObject *_Exc_AttributeError() { return ::PyExc_AttributeError; } -PyObject *_Exc_EnvironmentError() { return ::PyExc_EnvironmentError; } -PyObject *_Exc_EOFError() { return ::PyExc_EOFError; } -PyObject *_Exc_Exception() { return ::PyExc_Exception; } -PyObject *_Exc_FloatingPointError() { return ::PyExc_FloatingPointError; } -PyObject *_Exc_ImportError() { return ::PyExc_ImportError; } -PyObject *_Exc_IndexError() { return ::PyExc_IndexError; } -PyObject *_Exc_IOError() { return ::PyExc_IOError; } -PyObject *_Exc_KeyboardInterrupt() { return ::PyExc_KeyboardInterrupt; } -PyObject *_Exc_KeyError() { return ::PyExc_KeyError; } -PyObject *_Exc_LookupError() { return ::PyExc_LookupError; } -PyObject *_Exc_MemoryError() { return ::PyExc_MemoryError; } -PyObject *_Exc_NameError() { return ::PyExc_NameError; } -PyObject *_Exc_NotImplementedError() { return ::PyExc_NotImplementedError; } -PyObject *_Exc_OSError() { return ::PyExc_OSError; } -PyObject *_Exc_OverflowError() { return ::PyExc_OverflowError; } -PyObject *_Exc_RuntimeError() { return ::PyExc_RuntimeError; } -PyObject *_Exc_SyntaxError() { return ::PyExc_SyntaxError; } -PyObject *_Exc_SystemError() { return ::PyExc_SystemError; } -PyObject *_Exc_SystemExit() { return ::PyExc_SystemExit; } -PyObject *_Exc_TypeError() { return ::PyExc_TypeError; } -PyObject *_Exc_ValueError() { return ::PyExc_ValueError; } -PyObject *_Exc_ZeroDivisionError() { return ::PyExc_ZeroDivisionError; } -PyObject *_Exc_IndentationError() { return ::PyExc_IndentationError; } -PyObject *_Exc_TabError() { return ::PyExc_TabError; } -PyObject *_Exc_UnboundLocalError() { return ::PyExc_UnboundLocalError; } -PyObject *_Exc_UnicodeError() { return ::PyExc_UnicodeError; } - -#ifdef MS_WINDOWS -PyObject *_Exc_WindowsError() { return ::PyExc_WindowsError; } -#endif - - - - -// -// wrap items in Object.h -// -PyObject *_None() { return &::_Py_NoneStruct; } - -PyObject *_False() { return Py_False; } -PyObject *_True() { return Py_True; } - -PyTypeObject *_CFunction_Type() { return &PyCFunction_Type; } -PyTypeObject *_Complex_Type() { return &PyComplex_Type; } -PyTypeObject *_Dict_Type() { return &PyDict_Type; } -PyTypeObject *_Float_Type() { return &PyFloat_Type; } -PyTypeObject *_Function_Type() { return &PyFunction_Type; } -PyTypeObject *_Bool_Type() { return &PyBool_Type; } -PyTypeObject *_List_Type() { return &PyList_Type; } -PyTypeObject *_Long_Type() { return &PyLong_Type; } -PyTypeObject *_Method_Type() { return &PyMethod_Type; } -PyTypeObject *_Module_Type() { return &PyModule_Type; } -PyTypeObject *_Range_Type() { return &PyRange_Type; } -PyTypeObject *_Slice_Type() { return &PySlice_Type; } -PyTypeObject *_TraceBack_Type() { return &PyTraceBack_Type; } -PyTypeObject *_Tuple_Type() { return &PyTuple_Type; } -PyTypeObject *_Type_Type() { return &PyType_Type; } -PyTypeObject *_Unicode_Type() { return &PyUnicode_Type; } -#if PY_MAJOR_VERSION == 2 -PyTypeObject *_String_Type() { return &PyString_Type; } -PyTypeObject *_Int_Type() { return &PyInt_Type; } -PyTypeObject *_CObject_Type() { return &PyCObject_Type; } -#endif -#if PY_MAJOR_VERSION >= 3 -PyTypeObject *_Bytes_Type() { return &PyBytes_Type; } -#endif - -// -// wrap flags -// -int &_Py_DebugFlag() { return Py_DebugFlag; } -int &_Py_InteractiveFlag() { return Py_InteractiveFlag; } -int &_Py_OptimizeFlag() { return Py_OptimizeFlag; } -int &_Py_NoSiteFlag() { return Py_NoSiteFlag; } -int &_Py_VerboseFlag() { return Py_VerboseFlag; } -char *__Py_PackageContext() { return _Py_PackageContext; } - -// -// Needed to keep the abstactions for delayload interface -// -void _XINCREF( PyObject *op ) -{ - Py_XINCREF( op ); -} - -void _XDECREF( PyObject *op ) -{ - Py_XDECREF( op ); -} - -#endif -} diff --git a/extern/CXX/IndirectPythonInterface.hxx b/extern/CXX/IndirectPythonInterface.hxx deleted file mode 100644 index 26cd2d2989fd..000000000000 --- a/extern/CXX/IndirectPythonInterface.hxx +++ /dev/null @@ -1,7 +0,0 @@ -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "CXX/Python2/IndirectPythonInterface.hxx" -#else -#include "CXX/Python3/IndirectPythonInterface.hxx" -#endif diff --git a/extern/CXX/Objects.hxx b/extern/CXX/Objects.hxx deleted file mode 100644 index cb0294dec434..000000000000 --- a/extern/CXX/Objects.hxx +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "CXX/Python2/Objects.hxx" -#else -#include "CXX/Python3/Objects.hxx" -#endif diff --git a/extern/CXX/Python2/Config.hxx b/extern/CXX/Python2/Config.hxx deleted file mode 100644 index b27f9ba28275..000000000000 --- a/extern/CXX/Python2/Config.hxx +++ /dev/null @@ -1,118 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __PyCXX_config_hh__ -#define __PyCXX_config_hh__ - -// -// Microsoft VC++ 6.0 has no traits -// -#if defined( _MSC_VER ) - -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 1 - -#elif defined( __GNUC__ ) -# if __GNUC__ >= 3 -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 1 -# else -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 0 -#endif - -// -// Assume all other compilers do -// -#else - -// Macros to deal with deficiencies in compilers -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 1 -#endif - -#if STANDARD_LIBRARY_HAS_ITERATOR_TRAITS -# define random_access_iterator_parent(itemtype) std::iterator -#else -# define random_access_iterator_parent(itemtype) std::random_access_iterator -#endif - -// -// Which C++ standard is in use? -// -#if defined( _MSC_VER ) -# if _MSC_VER <= 1200 -// MSVC++ 6.0 -# define PYCXX_ISO_CPP_LIB 0 -# define STR_STREAM -# define TEMPLATE_TYPENAME class -# else -# define PYCXX_ISO_CPP_LIB 1 -# define STR_STREAM -# define TEMPLATE_TYPENAME typename -# endif -#elif defined( __GNUC__ ) -# if __GNUC__ >= 3 -# define PYCXX_ISO_CPP_LIB 1 -# define STR_STREAM -# define TEMPLATE_TYPENAME typename -# else -# define PYCXX_ISO_CPP_LIB 0 -# define STR_STREAM -# define TEMPLATE_TYPENAME class -# endif -#endif - -#if PYCXX_ISO_CPP_LIB -# define STR_STREAM -# define OSTRSTREAM ostringstream -# define EXPLICIT_TYPENAME typename -# define EXPLICIT_CLASS class -# define TEMPLATE_TYPENAME typename -#else -# define STR_STREAM -# define OSTRSTREAM ostrstream -# define EXPLICIT_TYPENAME -# define EXPLICIT_CLASS -# define TEMPLATE_TYPENAME class -#endif - -// before 2.5 Py_ssize_t was missing -#ifndef PY_MAJOR_VERSION -#error not defined PY_MAJOR_VERSION -#endif -#if PY_MAJOR_VERSION < 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5) -typedef int Py_ssize_t; -#endif - -#endif // __PyCXX_config_hh__ diff --git a/extern/CXX/Python2/CxxDebug.hxx b/extern/CXX/Python2/CxxDebug.hxx deleted file mode 100644 index b646ffdd9afa..000000000000 --- a/extern/CXX/Python2/CxxDebug.hxx +++ /dev/null @@ -1,17 +0,0 @@ -// -// CxxDebug.hxx -// -// Copyright (c) 2008 Barry A. Scott -// -#ifndef __CXX_Debug_hxx -#define __CXX_Debug_hxx - -// -// Functions useful when debugging PyCXX -// -#ifdef PYCXX_DEBUG -extern void bpt(); -extern void printRefCount( PyObject *obj ); -#endif - -#endif diff --git a/extern/CXX/Python2/Exception.hxx b/extern/CXX/Python2/Exception.hxx deleted file mode 100644 index 3acc0ae4182a..000000000000 --- a/extern/CXX/Python2/Exception.hxx +++ /dev/null @@ -1,259 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_Exception_h -#define __CXX_Exception_h - -#include "CXX/WrapPython.h" -#include "CXX/Version.hxx" -#include "CXX/Config.hxx" -#include "CXX/IndirectPythonInterface.hxx" - -#include -#include - -// This mimics the Python structure, in order to minimize confusion -namespace Py -{ - class ExtensionExceptionType; - - class Object; - - class Exception - { - public: - Exception( ExtensionExceptionType &exception, const std::string& reason ); - Exception( ExtensionExceptionType &exception, Object &reason ); - - explicit Exception () - {} - - Exception (const std::string& reason) - { - PyErr_SetString (Py::_Exc_RuntimeError(), reason.c_str()); - } - - Exception (PyObject* exception, const std::string& reason) - { - PyErr_SetString (exception, reason.c_str()); - } - - Exception (PyObject* exception, Object &reason); - - void clear() // clear the error - // technically but not philosophically const - { - PyErr_Clear(); - } - }; - - - // Abstract - class StandardError: public Exception - { - protected: - explicit StandardError() - {} - }; - - class LookupError: public StandardError - { - protected: - explicit LookupError() - {} - }; - - class ArithmeticError: public StandardError - { - protected: - explicit ArithmeticError() - {} - }; - - class EnvironmentError: public StandardError - { - protected: - explicit EnvironmentError() - {} - }; - - // Concrete - - class TypeError: public StandardError - { - public: - TypeError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_TypeError(),reason.c_str()); - } - }; - - class IndexError: public LookupError - { - public: - IndexError (const std::string& reason) - : LookupError() - { - PyErr_SetString (Py::_Exc_IndexError(), reason.c_str()); - } - }; - - class AttributeError: public StandardError - { - public: - AttributeError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_AttributeError(), reason.c_str()); - } - }; - - class NameError: public StandardError - { - public: - NameError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_NameError(), reason.c_str()); - } - }; - - class RuntimeError: public StandardError - { - public: - RuntimeError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_RuntimeError(), reason.c_str()); - } - }; - - class NotImplementedError: public StandardError - { - public: - NotImplementedError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_NotImplementedError(), reason.c_str()); - } - }; - - class SystemError: public StandardError - { - public: - SystemError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_SystemError(),reason.c_str()); - } - }; - - class KeyError: public LookupError - { - public: - KeyError (const std::string& reason) - : LookupError() - { - PyErr_SetString (Py::_Exc_KeyError(),reason.c_str()); - } - }; - - - class ValueError: public StandardError - { - public: - ValueError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_ValueError(), reason.c_str()); - } - }; - - class OverflowError: public ArithmeticError - { - public: - OverflowError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString (Py::_Exc_OverflowError(), reason.c_str()); - } - }; - - class ZeroDivisionError: public ArithmeticError - { - public: - ZeroDivisionError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString (Py::_Exc_ZeroDivisionError(), reason.c_str()); - } - }; - - class FloatingPointError: public ArithmeticError - { - public: - FloatingPointError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString (Py::_Exc_FloatingPointError(), reason.c_str()); - } - }; - - class MemoryError: public StandardError - { - public: - MemoryError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_MemoryError(), reason.c_str()); - } - }; - - class SystemExit: public StandardError - { - public: - SystemExit (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_SystemExit(),reason.c_str()); - } - }; - -}// Py - -#endif diff --git a/extern/CXX/Python2/ExtensionModule.hxx b/extern/CXX/Python2/ExtensionModule.hxx deleted file mode 100644 index 3eb436d00048..000000000000 --- a/extern/CXX/Python2/ExtensionModule.hxx +++ /dev/null @@ -1,205 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionModule__h -#define __CXX_ExtensionModule__h - -namespace Py -{ - class ExtensionModuleBase - { - public: - ExtensionModuleBase( const char *name ); - virtual ~ExtensionModuleBase(); - - Module module( void ) const; // only valid after initialize() has been called - Dict moduleDictionary( void ) const; // only valid after initialize() has been called - - virtual Object invoke_method_noargs( void *method_def ) = 0; - virtual Object invoke_method_keyword( void *method_def, const Tuple &_args, const Dict &_keywords ) = 0; - virtual Object invoke_method_varargs( void *method_def, const Tuple &_args ) = 0; - - const std::string &name() const; - const std::string &fullName() const; - - // what is returned from PyInit_ function - Object moduleObject( void ) const; - - protected: - // Initialize the module - void initialize( const char *module_doc ); - - const std::string m_module_name; - const std::string m_full_module_name; - MethodTable m_method_table; - PyObject *m_module; - - private: - // - // prevent the compiler generating these unwanted functions - // - ExtensionModuleBase( const ExtensionModuleBase & ); //unimplemented - void operator=( const ExtensionModuleBase & ); //unimplemented - }; - - // Note: Python calls noargs as varargs buts args==NULL - extern "C" PyObject *method_noargs_call_handler( PyObject *_self_and_name_tuple, PyObject * ); - extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ); - extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ); - - extern "C" void do_not_dealloc( void * ); - - template - class ExtensionModule : public ExtensionModuleBase - { - public: - ExtensionModule( const char *name ) - : ExtensionModuleBase( name ) - {} - virtual ~ExtensionModule() - {} - - protected: - typedef Object (T::*method_noargs_function_t)(); - typedef Object (T::*method_varargs_function_t)( const Tuple &args ); - typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - typedef std::map *> method_map_t; - - static void add_noargs_method( const char *name, method_noargs_function_t function, const char *doc="" ) - { - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_noargs_call_handler, doc ); - } - - static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" ) - { - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_varargs_call_handler, doc ); - } - - static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" ) - { - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_keyword_call_handler, doc ); - } - - void initialize( const char *module_doc="" ) - { - ExtensionModuleBase::initialize( module_doc ); - Dict dict( moduleDictionary() ); - - // - // put each of the methods into the modules dictionary - // so that we get called back at the function in T. - // - method_map_t &mm = methods(); - EXPLICIT_TYPENAME method_map_t::const_iterator i = mm.begin(); - EXPLICIT_TYPENAME method_map_t::const_iterator i_end = mm.end(); - for ( ; i != i_end; ++i ) - { - MethodDefExt *method_def = (*i).second; - - static PyObject *self = PyCObject_FromVoidPtr( this, do_not_dealloc ); - - Tuple args( 2 ); - args[0] = Object( self, true ); - args[1] = Object( PyCObject_FromVoidPtr( method_def, do_not_dealloc ), true ); - - PyObject *func = PyCFunction_New - ( - &method_def->ext_meth_def, - new_reference_to( args ) - ); - - method_def->py_method = Object( func, true ); - - dict[ (*i).first ] = method_def->py_method; - } - } - - protected: // Tom Malcolmson reports that derived classes need access to these - static method_map_t &methods( void ) - { - static method_map_t *map_of_methods = NULL; - if( map_of_methods == NULL ) - map_of_methods = new method_map_t; - - return *map_of_methods; - } - - // this invoke function must be called from within a try catch block - virtual Object invoke_method_noargs( void *method_def ) - { - // cast up to the derived class, method_def and call - T *self = static_cast( this ); - MethodDefExt *meth_def = reinterpret_cast *>( method_def ); - - return (self->*meth_def->ext_noargs_function)(); - } - - // this invoke function must be called from within a try catch block - virtual Object invoke_method_varargs( void *method_def, const Tuple &args ) - { - // cast up to the derived class, method_def and call - T *self = static_cast( this ); - MethodDefExt *meth_def = reinterpret_cast *>( method_def ); - - return (self->*meth_def->ext_varargs_function)( args ); - } - - // this invoke function must be called from within a try catch block - virtual Object invoke_method_keyword( void *method_def, const Tuple &args, const Dict &keywords ) - { - // cast up to the derived class, method_def and call - T *self = static_cast( this ); - MethodDefExt *meth_def = reinterpret_cast *>( method_def ); - - return (self->*meth_def->ext_keyword_function)( args, keywords ); - } - - private: - // - // prevent the compiler generating these unwanted functions - // - ExtensionModule( const ExtensionModule & ); //unimplemented - void operator=( const ExtensionModule & ); //unimplemented - }; -} // Namespace Py - - -// End of __CXX_ExtensionModule__h -#endif diff --git a/extern/CXX/Python2/ExtensionOldType.hxx b/extern/CXX/Python2/ExtensionOldType.hxx deleted file mode 100644 index cfd2fbe6a578..000000000000 --- a/extern/CXX/Python2/ExtensionOldType.hxx +++ /dev/null @@ -1,397 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionOldType__h -#define __CXX_ExtensionOldType__h - -namespace Py -{ - template class PythonExtension - : public PythonExtensionBase - { - public: - static PyTypeObject *type_object() - { - return behaviors().type_object(); - } - - static bool check( PyObject *p ) - { - // is p like me? - return p->ob_type == type_object(); - } - - static bool check( const Object &ob ) - { - return check( ob.ptr() ); - } - - // - // every object needs getattr implemented - // to support methods - // - virtual Object getattr( const char *name ) - { - return getattr_methods( name ); - } - - PyObject *selfPtr() - { - return this; - } - - Object self() - { - return asObject( this ); - } - - protected: - explicit PythonExtension() - : PythonExtensionBase() - { - PyObject_Init( this, type_object() ); - - // every object must support getattr - behaviors().supportGetattr(); - } - - virtual ~PythonExtension() - {} - - static PythonType &behaviors() - { - static PythonType* p; - if( p == NULL ) - { -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - const char *default_name =( typeid( T ) ).name(); -#else - const char *default_name = "unknown"; -#endif - p = new PythonType( sizeof( T ), 0, default_name ); - p->set_tp_dealloc( extension_object_deallocator ); - } - - return *p; - } - - typedef Object (T::*method_noargs_function_t)(); - typedef Object (T::*method_varargs_function_t)( const Tuple &args ); - typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - typedef std::map *> method_map_t; - - // support the default attributes, __name__, __doc__ and methods - virtual Object getattr_default( const char *_name ) - { - std::string name( _name ); - - if( name == "__name__" && type_object()->tp_name != NULL ) - { - return Py::String( type_object()->tp_name ); - } - - if( name == "__doc__" && type_object()->tp_doc != NULL ) - { - return Py::String( type_object()->tp_doc ); - } - -// trying to fake out being a class for help() -// else if( name == "__bases__" ) -// { -// return Py::Tuple( 0 ); -// } -// else if( name == "__module__" ) -// { -// return Py::Nothing(); -// } -// else if( name == "__dict__" ) -// { -// return Py::Dict(); -// } - - return getattr_methods( _name ); - } - - // turn a name into function object - virtual Object getattr_methods( const char *_name ) - { - std::string name( _name ); - - method_map_t &mm = methods(); - - // see if name exists and get entry with method - EXPLICIT_TYPENAME method_map_t::const_iterator i = mm.find( name ); - if( i == mm.end() ) - { - if( name == "__methods__" ) - { - List methods; - - i = mm.begin(); - EXPLICIT_TYPENAME method_map_t::const_iterator i_end = mm.end(); - - for( ; i != i_end; ++i ) - methods.append( String( (*i).first ) ); - - return methods; - } - - throw AttributeError( name ); - } - - MethodDefExt *method_def = i->second; - - Tuple self( 2 ); - - self[0] = Object( this ); - self[1] = Object( PyCObject_FromVoidPtr( method_def, do_not_dealloc ), true ); - - PyObject *func = PyCFunction_New( &method_def->ext_meth_def, self.ptr() ); - - return Object(func, true); - } - - // check that all methods added are unique - static void check_unique_method_name( const char *name ) - { - method_map_t &mm = methods(); - EXPLICIT_TYPENAME method_map_t::const_iterator i; - i = mm.find( name ); - if( i != mm.end() ) - throw AttributeError( name ); - } - - static void add_noargs_method( const char *name, method_noargs_function_t function, const char *doc="" ) - { - check_unique_method_name( name ); - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_noargs_call_handler, doc ); - } - - static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" ) - { - check_unique_method_name( name ); - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_varargs_call_handler, doc ); - } - - static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" ) - { - check_unique_method_name( name ); - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_keyword_call_handler, doc ); - } - - private: - static method_map_t &methods( void ) - { - static method_map_t *map_of_methods = NULL; - if( map_of_methods == NULL ) - map_of_methods = new method_map_t; - - return *map_of_methods; - } - - // Note: Python calls noargs as varargs buts args==NULL - static PyObject *method_noargs_call_handler( PyObject *_self_and_name_tuple, PyObject * ) - { - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - T *self = static_cast( self_in_cobject ); - MethodDefExt *meth_def = reinterpret_cast *>( - PyCObject_AsVoidPtr( self_and_name_tuple[1].ptr() ) ); - Object result; - - // Adding try & catch in case of STL debug-mode exceptions. - #ifdef _STLP_DEBUG - try - { - result = (self->*meth_def->ext_noargs_function)(); - } - catch( std::__stl_debug_exception ) - { - // throw cxx::RuntimeError( sErrMsg ); - throw RuntimeError( "Error message not set yet." ); - } - #else - result = (self->*meth_def->ext_noargs_function)(); - #endif // _STLP_DEBUG - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } - } - - static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ) - { - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - T *self = static_cast( self_in_cobject ); - - MethodDefExt *meth_def = reinterpret_cast *>( - PyCObject_AsVoidPtr( self_and_name_tuple[1].ptr() ) ); - Tuple args( _args ); - - Object result; - - // Adding try & catch in case of STL debug-mode exceptions. - #ifdef _STLP_DEBUG - try - { - result = (self->*meth_def->ext_varargs_function)( args ); - } - catch( std::__stl_debug_exception ) - { - throw RuntimeError( "Error message not set yet." ); - } - #else - result = (self->*meth_def->ext_varargs_function)( args ); - #endif // _STLP_DEBUG - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } - } - - static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ) - { - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - T *self = static_cast( self_in_cobject ); - - MethodDefExt *meth_def = reinterpret_cast *>( - PyCObject_AsVoidPtr( self_and_name_tuple[1].ptr() ) ); - - Tuple args( _args ); - - // _keywords may be NULL so be careful about the way the dict is created - Dict keywords; - if( _keywords != NULL ) - keywords = Dict( _keywords ); - - Object result( ( self->*meth_def->ext_keyword_function )( args, keywords ) ); - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } - } - - static void extension_object_deallocator( PyObject* t ) - { - delete (T *)( t ); - } - - // - // prevent the compiler generating these unwanted functions - // - explicit PythonExtension( const PythonExtension &other ); - void operator=( const PythonExtension &rhs ); - }; - - // - // ExtensionObject is an Object that will accept only T's. - // - template - class ExtensionObject: public Object - { - public: - - explicit ExtensionObject( PyObject *pyob ) - : Object( pyob ) - { - validate(); - } - - ExtensionObject( const ExtensionObject &other ) - : Object( *other ) - { - validate(); - } - - ExtensionObject( const Object &other ) - : Object( *other ) - { - validate(); - } - - ExtensionObject &operator=( const Object &rhs ) - { - return( *this = *rhs ); - } - - ExtensionObject &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - virtual bool accepts( PyObject *pyob ) const - { - return( pyob && T::check( pyob ) ); - } - - // - // Obtain a pointer to the PythonExtension object - // - T *extensionObject( void ) - { - return static_cast( ptr() ); - } - }; -} // Namespace Py - -// End of __CXX_ExtensionOldType__h -#endif diff --git a/extern/CXX/Python2/ExtensionType.hxx b/extern/CXX/Python2/ExtensionType.hxx deleted file mode 100644 index 4128960eea2a..000000000000 --- a/extern/CXX/Python2/ExtensionType.hxx +++ /dev/null @@ -1,403 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionClass__h -#define __CXX_ExtensionClass__h - -#define PYCXX_NOARGS_METHOD_NAME( NAME ) _callNoArgsMethod__##NAME -#define PYCXX_VARARGS_METHOD_NAME( NAME ) _callVarArgsMethod__##NAME -#define PYCXX_KEYWORDS_METHOD_NAME( NAME ) _callKeywordsMethod__##NAME - -#define PYCXX_NOARGS_METHOD_DECL( CLS, NAME ) \ - static PyObject *PYCXX_NOARGS_METHOD_NAME( NAME )( PyObject *_self, PyObject *, PyObject * ) \ - { \ - try \ - { \ - Py::PythonClassInstance *self_python = reinterpret_cast< Py::PythonClassInstance * >( _self ); \ - CLS *self = reinterpret_cast< CLS * >( self_python->m_pycxx_object ); \ - Py::Object r( (self->NAME)() ); \ - return Py::new_reference_to( r.ptr() ); \ - } \ - catch( Py::Exception & ) \ - { \ - return 0; \ - } \ - } -#define PYCXX_VARARGS_METHOD_DECL( CLS, NAME ) \ - static PyObject *PYCXX_VARARGS_METHOD_NAME( NAME )( PyObject *_self, PyObject *_a, PyObject * ) \ - { \ - try \ - { \ - Py::PythonClassInstance *self_python = reinterpret_cast< Py::PythonClassInstance * >( _self ); \ - CLS *self = reinterpret_cast< CLS * >( self_python->m_pycxx_object ); \ - Py::Tuple a( _a ); \ - Py::Object r( (self->NAME)( a ) ); \ - return Py::new_reference_to( r.ptr() ); \ - } \ - catch( Py::Exception & ) \ - { \ - return 0; \ - } \ - } -#define PYCXX_KEYWORDS_METHOD_DECL( CLS, NAME ) \ - static PyObject *PYCXX_KEYWORDS_METHOD_NAME( NAME )( PyObject *_self, PyObject *_a, PyObject *_k ) \ - { \ - try \ - { \ - Py::PythonClassInstance *self_python = reinterpret_cast< Py::PythonClassInstance * >( _self ); \ - CLS *self = reinterpret_cast< CLS * >( self_python->m_pycxx_object ); \ - Py::Tuple a( _a ); \ - Py::Dict k; \ - if( _k != NULL ) \ - k = _k; \ - Py::Object r( (self->NAME)( a, k ) ); \ - return Py::new_reference_to( r.ptr() ); \ - } \ - catch( Py::Exception & ) \ - { \ - return 0; \ - } \ - } - -// need to support METH_STATIC and METH_CLASS - -#define PYCXX_ADD_NOARGS_METHOD( PYNAME, NAME, docs ) \ - add_method( #PYNAME, (PyCFunction)PYCXX_NOARGS_METHOD_NAME( NAME ), METH_NOARGS, docs ) -#define PYCXX_ADD_VARARGS_METHOD( PYNAME, NAME, docs ) \ - add_method( #PYNAME, (PyCFunction)PYCXX_VARARGS_METHOD_NAME( NAME ), METH_VARARGS, docs ) -#define PYCXX_ADD_KEYWORDS_METHOD( PYNAME, NAME, docs ) \ - add_method( #PYNAME, (PyCFunction)PYCXX_KEYWORDS_METHOD_NAME( NAME ), METH_VARARGS | METH_KEYWORDS, docs ) - -namespace Py -{ - extern PythonExtensionBase *getPythonExtensionBase( PyObject *self ); - - struct PythonClassInstance - { - PyObject_HEAD - PythonExtensionBase *m_pycxx_object; - }; - - - class ExtensionClassMethodsTable - { - public: - ExtensionClassMethodsTable() - : m_methods_table( new PyMethodDef[ METHOD_TABLE_SIZE_INCREMENT ] ) - , m_methods_used( 0 ) - , m_methods_size( METHOD_TABLE_SIZE_INCREMENT ) - { - } - - ~ExtensionClassMethodsTable() - { - delete m_methods_table; - } - - // check that all methods added are unique - void check_unique_method_name( const char *_name ) - { - std::string name( _name ); - for( int i=0; iml_name = const_cast( name ); - p->ml_meth = function; - p->ml_flags = flags; - p->ml_doc = const_cast( doc ); - - m_methods_used++; - p++; - - // add the sentinel marking the table end - p->ml_name = NULL; - p->ml_meth = NULL; - p->ml_flags = 0; - p->ml_doc = NULL; - - return m_methods_table; - } - - private: - enum {METHOD_TABLE_SIZE_INCREMENT = 1}; - PyMethodDef *m_methods_table; - int m_methods_used; - int m_methods_size; - }; - - template class PythonClass - : public PythonExtensionBase - { - protected: - explicit PythonClass( PythonClassInstance *self, Tuple &args, Dict &kwds ) - : PythonExtensionBase() - , m_class_instance( self ) - { - } - - virtual ~PythonClass() - {} - - static ExtensionClassMethodsTable &methodTable() - { - static ExtensionClassMethodsTable *method_table; - if( method_table == NULL ) - method_table = new ExtensionClassMethodsTable; - return *method_table; - } - - static void add_method( const char *name, PyCFunction function, int flags, const char *doc=NULL ) - { - behaviors().set_methods( methodTable().add_method( name, function, flags, doc ) ); - } - - static PythonType &behaviors() - { - static PythonType *p; - if( p == NULL ) - { -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - const char *default_name = (typeid( T )).name(); -#else - const char *default_name = "unknown"; -#endif - p = new PythonType( sizeof( T ), 0, default_name ); - p->set_tp_new( extension_object_new ); - p->set_tp_init( extension_object_init ); - p->set_tp_dealloc( extension_object_deallocator ); - // we are a class - p->supportClass(); - - // always support get and set attr - p->supportGetattro(); - p->supportSetattro(); - } - - return *p; - } - - static PyObject *extension_object_new( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) - { -#ifdef PYCXX_DEBUG - std::cout << "extension_object_new()" << std::endl; -#endif - PythonClassInstance *o = reinterpret_cast( subtype->tp_alloc( subtype, 0 ) ); - if( o == NULL ) - return NULL; - - o->m_pycxx_object = NULL; - - PyObject *self = reinterpret_cast( o ); -#ifdef PYCXX_DEBUG - std::cout << "extension_object_new() => self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << std::endl; -#endif - return self; - } - - static int extension_object_init( PyObject *_self, PyObject *args_, PyObject *kwds_ ) - { - try - { - Py::Tuple args( args_ ); - Py::Dict kwds; - if( kwds_ != NULL ) - kwds = kwds_; - - PythonClassInstance *self = reinterpret_cast( _self ); -#ifdef PYCXX_DEBUG - std::cout << "extension_object_init( self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << " )" << std::endl; - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - - if( self->m_pycxx_object == NULL ) - { - self->m_pycxx_object = new T( self, args, kwds ); -#ifdef PYCXX_DEBUG - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - } - else - { -#ifdef PYCXX_DEBUG - std::cout << " reinit - self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - self->m_pycxx_object->reinit( args, kwds ); - } - } - catch( Exception & ) - { - return -1; - } - return 0; - } - - static void extension_object_deallocator( PyObject *_self ) - { - PythonClassInstance *self = reinterpret_cast< PythonClassInstance * >( _self ); -#ifdef PYCXX_DEBUG - std::cout << "extension_object_deallocator( self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << " )" << std::endl; - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - delete self->m_pycxx_object; - _self->ob_type->tp_free( _self ); - } - - public: - static PyTypeObject *type_object() - { - return behaviors().type_object(); - } - - static Object type() - { - return Object( reinterpret_cast( behaviors().type_object() ) ); - } - - static bool check( PyObject *p ) - { - // is p like me? - return p->ob_type == type_object(); - } - - static bool check( const Object &ob ) - { - return check( ob.ptr() ); - } - - virtual PyObject *selfPtr() - { - return reinterpret_cast( m_class_instance ); - } - - virtual Object self() - { - return Object( reinterpret_cast( m_class_instance ) ); - } - - protected: - private: - PythonClassInstance *m_class_instance; - - private: - // - // prevent the compiler generating these unwanted functions - // - explicit PythonClass( const PythonClass &other ); - void operator=( const PythonClass &rhs ); - }; - - // - // ExtensionObject is an Object that will accept only T's. - // - template - class PythonClassObject: public Object - { - public: - - explicit PythonClassObject( PyObject *pyob ) - : Object( pyob ) - { - validate(); - } - - PythonClassObject( const PythonClassObject &other ) - : Object( *other ) - { - validate(); - } - - PythonClassObject( const Object &other ) - : Object( *other ) - { - validate(); - } - - PythonClassObject &operator=( const Object &rhs ) - { - *this = *rhs; - return *this; - } - - PythonClassObject &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - virtual bool accepts( PyObject *pyob ) const - { - return( pyob && T::check( pyob ) ); - } - - // - // Obtain a pointer to the PythonExtension object - // - T *getCxxObject( void ) - { - return dynamic_cast< T * >( getPythonExtensionBase( ptr() ) ); - } - }; -} // Namespace Py - -// End of __CXX_ExtensionClass__h -#endif diff --git a/extern/CXX/Python2/ExtensionTypeBase.hxx b/extern/CXX/Python2/ExtensionTypeBase.hxx deleted file mode 100644 index 1dfe4243619a..000000000000 --- a/extern/CXX/Python2/ExtensionTypeBase.hxx +++ /dev/null @@ -1,175 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionTypeBase__h -#define __CXX_ExtensionTypeBase__h - -namespace Py -{ - // Class PythonExtension is what you inherit from to create - // a new Python extension type. You give your class itself - // as the template paramter. - - // There are two ways that extension objects can get destroyed. - // 1. Their reference count goes to zero - // 2. Someone does an explicit delete on a pointer. - // In(1) the problem is to get the destructor called - // We register a special deallocator in the Python type object - // (see behaviors()) to do this. - // In(2) there is no problem, the dtor gets called. - - // PythonExtension does not use the usual Python heap allocator, - // instead using new/delete. We do the setting of the type object - // and reference count, usually done by PyObject_New, in the - // base class ctor. - - // This special deallocator does a delete on the pointer. - - class PythonExtensionBase : public PyObject - { - public: - PythonExtensionBase(); - virtual ~PythonExtensionBase(); - - public: - // object - virtual void reinit( Tuple &args, Dict &kwds ); - - // object basics - virtual int print( FILE *, int ); - virtual Object getattr( const char * ); - virtual int setattr( const char *, const Object & ); - virtual Object getattro( const String & ); - Object genericGetAttro( const String & ); - virtual int setattro( const String &, const Object & ); - int genericSetAttro( const String &, const Object & ); - virtual int compare( const Object & ); - virtual Object rich_compare( const Object &, int ); - virtual Object repr(); - virtual Object str(); - virtual long hash(); - virtual Object call( const Object &, const Object & ); - virtual Object iter(); - virtual PyObject *iternext(); - - // Sequence methods - virtual int sequence_length(); - virtual Object sequence_concat( const Object & ); - virtual Object sequence_repeat( Py_ssize_t ); - virtual Object sequence_item( Py_ssize_t ); - virtual Object sequence_slice( Py_ssize_t, Py_ssize_t ); - virtual int sequence_ass_item( Py_ssize_t, const Object & ); - virtual int sequence_ass_slice( Py_ssize_t, Py_ssize_t, const Object & ); - - // Mapping - virtual int mapping_length(); - virtual Object mapping_subscript( const Object & ); - virtual int mapping_ass_subscript( const Object &, const Object & ); - - // Number - virtual int number_nonzero(); - virtual Object number_negative(); - virtual Object number_positive(); - virtual Object number_absolute(); - virtual Object number_invert(); - virtual Object number_int(); - virtual Object number_float(); - virtual Object number_long(); - virtual Object number_oct(); - virtual Object number_hex(); - virtual Object number_add( const Object & ); - virtual Object number_subtract( const Object & ); - virtual Object number_multiply( const Object & ); - virtual Object number_divide( const Object & ); - virtual Object number_remainder( const Object & ); - virtual Object number_divmod( const Object & ); - virtual Object number_lshift( const Object & ); - virtual Object number_rshift( const Object & ); - virtual Object number_and( const Object & ); - virtual Object number_xor( const Object & ); - virtual Object number_or( const Object & ); - virtual Object number_power( const Object &, const Object & ); - - // Buffer - virtual Py_ssize_t buffer_getreadbuffer( Py_ssize_t, void** ); - virtual Py_ssize_t buffer_getwritebuffer( Py_ssize_t, void** ); - virtual Py_ssize_t buffer_getsegcount( Py_ssize_t* ); - - public: - // helper functions to call function fn_name with 0 to 9 args - Object callOnSelf( const std::string &fn_name ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6, - const Object &arg7 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6, - const Object &arg7, const Object &arg8 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6, - const Object &arg7, const Object &arg8, const Object &arg9 ); - - public: - virtual PyObject *selfPtr() = 0; - virtual Object self() = 0; - - private: - void missing_method( void ); - static PyObject *method_call_handler( PyObject *self, PyObject *args ); - }; - -} // Namespace Py - -// End of __CXX_ExtensionTypeBase__h -#endif diff --git a/extern/CXX/Python2/Extensions.hxx b/extern/CXX/Python2/Extensions.hxx deleted file mode 100644 index c4324b30a0d2..000000000000 --- a/extern/CXX/Python2/Extensions.hxx +++ /dev/null @@ -1,189 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_Extensions__h -#define __CXX_Extensions__h - - -#ifdef _MSC_VER -// disable warning C4786: symbol greater than 255 character, -// okay to ignore -#pragma warning( disable: 4786 ) -#endif - -#include "CXX/WrapPython.h" -#include "CXX/Version.hxx" -#include "CXX/Python2/Config.hxx" -#include "CXX/Python2/CxxDebug.hxx" -#include "CXX/Python2/Objects.hxx" - -extern "C" { extern PyObject py_object_initializer; } - -#include -#include - -// ---------------------------------------------------------------------- - -namespace Py -{ - class ExtensionModuleBase; - - // Make an Exception Type for use in raising custom exceptions - class ExtensionExceptionType : public Object - { - public: - ExtensionExceptionType(); - virtual ~ExtensionExceptionType(); - - // call init to create the type - void init( ExtensionModuleBase &module, const std::string &name, ExtensionExceptionType &parent ); - void init( ExtensionModuleBase &module, const std::string &name ); - }; - - class MethodTable - { - public: - MethodTable(); - virtual ~MethodTable(); - - void add( const char *method_name, PyCFunction f, const char *doc="", int flag=1 ); - PyMethodDef *table(); - - protected: - std::vector t; // accumulator of PyMethodDef's - PyMethodDef *mt; // Actual method table produced when full - - static PyMethodDef method( const char* method_name, PyCFunction f, int flags=1, const char* doc="" ); - - private: - // - // prevent the compiler generating these unwanted functions - // - MethodTable( const MethodTable &m ); //unimplemented - void operator=( const MethodTable &m ); //unimplemented - - }; // end class MethodTable - - // Note: Python calls noargs as varargs buts args==NULL - extern "C" typedef PyObject *(*method_noargs_call_handler_t)( PyObject *_self, PyObject * ); - extern "C" typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args ); - extern "C" typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict ); - - template - class MethodDefExt : public PyMethodDef - { - public: - typedef Object (T::*method_noargs_function_t)(); - typedef Object (T::*method_varargs_function_t)( const Tuple &args ); - typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - - // NOARGS - MethodDefExt - ( - const char *_name, - method_noargs_function_t _function, - method_noargs_call_handler_t _handler, - const char *_doc - ) - { - ext_meth_def.ml_name = const_cast( _name ); - ext_meth_def.ml_meth = reinterpret_cast( _handler ); - ext_meth_def.ml_flags = METH_NOARGS; - ext_meth_def.ml_doc = const_cast( _doc ); - - ext_noargs_function = _function; - ext_varargs_function = NULL; - ext_keyword_function = NULL; - } - - // VARARGS - MethodDefExt - ( - const char *_name, - method_varargs_function_t _function, - method_varargs_call_handler_t _handler, - const char *_doc - ) - { - ext_meth_def.ml_name = const_cast( _name ); - ext_meth_def.ml_meth = reinterpret_cast( _handler ); - ext_meth_def.ml_flags = METH_VARARGS; - ext_meth_def.ml_doc = const_cast( _doc ); - - ext_noargs_function = NULL; - ext_varargs_function = _function; - ext_keyword_function = NULL; - } - - // VARARGS + KEYWORD - MethodDefExt - ( - const char *_name, - method_keyword_function_t _function, - method_keyword_call_handler_t _handler, - const char *_doc - ) - { - ext_meth_def.ml_name = const_cast( _name ); - ext_meth_def.ml_meth = reinterpret_cast( _handler ); - ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS; - ext_meth_def.ml_doc = const_cast( _doc ); - - ext_noargs_function = NULL; - ext_varargs_function = NULL; - ext_keyword_function = _function; - } - - ~MethodDefExt() - {} - - PyMethodDef ext_meth_def; - method_noargs_function_t ext_noargs_function; - method_varargs_function_t ext_varargs_function; - method_keyword_function_t ext_keyword_function; - Object py_method; - }; -} // Namespace Py - -#include "CXX/Python2/ExtensionModule.hxx" -#include "CXX/Python2/PythonType.hxx" -#include "CXX/Python2/ExtensionTypeBase.hxx" -#include "CXX/Python2/ExtensionOldType.hxx" -#include "CXX/Python2/ExtensionType.hxx" - -// End of CXX_Extensions.h -#endif diff --git a/extern/CXX/Python2/IndirectPythonInterface.hxx b/extern/CXX/Python2/IndirectPythonInterface.hxx deleted file mode 100644 index a29a394c6c6a..000000000000 --- a/extern/CXX/Python2/IndirectPythonInterface.hxx +++ /dev/null @@ -1,198 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ -#define __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ - -#include "CXX/WrapPython.h" - -namespace Py -{ -bool InitialisePythonIndirectInterface(); - -// -// Wrap Exception variables as function calls -// -PyObject * _Exc_Exception(); -PyObject * _Exc_StandardError(); -PyObject * _Exc_ArithmeticError(); -PyObject * _Exc_LookupError(); - -PyObject * _Exc_AssertionError(); -PyObject * _Exc_AttributeError(); -PyObject * _Exc_EOFError(); -PyObject * _Exc_FloatingPointError(); -PyObject * _Exc_EnvironmentError(); -PyObject * _Exc_IOError(); -PyObject * _Exc_OSError(); -PyObject * _Exc_ImportError(); -PyObject * _Exc_IndexError(); -PyObject * _Exc_KeyError(); -PyObject * _Exc_KeyboardInterrupt(); -PyObject * _Exc_MemoryError(); -PyObject * _Exc_NameError(); -PyObject * _Exc_OverflowError(); -PyObject * _Exc_RuntimeError(); -PyObject * _Exc_NotImplementedError(); -PyObject * _Exc_SyntaxError(); -PyObject * _Exc_SystemError(); -PyObject * _Exc_SystemExit(); -PyObject * _Exc_TypeError(); -PyObject * _Exc_ValueError(); -PyObject * _Exc_ZeroDivisionError(); -#ifdef MS_WINDOWS -PyObject * _Exc_WindowsError(); -#endif - -PyObject * _Exc_MemoryErrorInst(); - -#if PY_MAJOR_VERSION >= 2 -PyObject * _Exc_IndentationError(); -PyObject * _Exc_TabError(); -PyObject * _Exc_UnboundLocalError(); -PyObject * _Exc_UnicodeError(); -#endif - -// -// Wrap Object variables as function calls -// -PyObject * _None(); - -PyObject * _False(); -PyObject * _True(); - -// -// Wrap Type variables as function calls -// -PyTypeObject * _List_Type(); -bool _List_Check( PyObject *o ); - -PyTypeObject * _Buffer_Type(); -bool _Buffer_Check( PyObject *op ); - -PyTypeObject * _Class_Type(); -bool _Class_Check( PyObject *op ); - -PyTypeObject * _Instance_Type(); -bool _Instance_Check( PyObject *op ); - -PyTypeObject * _Method_Type(); -bool _Method_Check( PyObject *op ); - -PyTypeObject * _CObject_Type(); -bool _CObject_Check( PyObject *op ); - -PyTypeObject * _Complex_Type(); -bool _Complex_Check( PyObject *op ); - -PyTypeObject * _Dict_Type(); -bool _Dict_Check( PyObject *op ); - -PyTypeObject * _File_Type(); -bool _File_Check( PyObject *op ); - -PyTypeObject * _Float_Type(); -bool _Float_Check( PyObject *op ); - -PyTypeObject * _Frame_Type(); -bool _Frame_Check( PyObject *op ); - -PyTypeObject * _Function_Type(); -bool _Function_Check( PyObject *op ); - -PyTypeObject * _Bool_Type(); -bool _Boolean_Check( PyObject *op ); - -PyTypeObject * _Int_Type(); -bool _Int_Check( PyObject *op ); - -PyTypeObject * _List_Type(); -bool _List_Check( PyObject *op ); - -PyTypeObject * _Long_Type(); -bool _Long_Check( PyObject *op ); - -PyTypeObject * _CFunction_Type(); -bool _CFunction_Check( PyObject *op ); - -PyTypeObject * _Module_Type(); -bool _Module_Check( PyObject *op ); - -PyTypeObject * _Type_Type(); -bool _Type_Check( PyObject *op ); - -PyTypeObject * _Range_Type(); -bool _Range_Check( PyObject *op ); - -PyTypeObject * _Slice_Type(); -bool _Slice_Check( PyObject *op ); - -PyTypeObject * _String_Type(); -bool _String_Check( PyObject *op ); - -PyTypeObject * _Unicode_Type(); -bool _Unicode_Check( PyObject *op ); - -PyTypeObject * _TraceBack_Type(); -bool _TraceBack_Check( PyObject *v ); - -PyTypeObject * _Tuple_Type(); -bool _Tuple_Check( PyObject *op ); - -#if PY_MAJOR_VERSION >= 2 -PyTypeObject * _Unicode_Type(); -bool _Unicode_Check( PyObject *op ); -#endif - -int &_Py_DebugFlag(); -int &_Py_InteractiveFlag(); -int &_Py_OptimizeFlag(); -int &_Py_NoSiteFlag(); -int &_Py_TabcheckFlag(); -int &_Py_VerboseFlag(); - -#if PY_MAJOR_VERSION >= 2 -int &_Py_UnicodeFlag(); -#endif - -void _XINCREF( PyObject *op ); -void _XDECREF( PyObject *op ); - -char *__Py_PackageContext(); -} - -#endif // __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ diff --git a/extern/CXX/Python2/Objects.hxx b/extern/CXX/Python2/Objects.hxx deleted file mode 100644 index 286293ead71a..000000000000 --- a/extern/CXX/Python2/Objects.hxx +++ /dev/null @@ -1,3466 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_Objects__h -#define __CXX_Objects__h - -#include "CXX/WrapPython.h" -#include "CXX/Version.hxx" -#include "CXX/Config.hxx" -#include "CXX/Exception.hxx" - -#include -#include STR_STREAM -#include -#include -#include -#include - -namespace Py -{ - typedef int sequence_index_type; // type of an index into a sequence - - // Forward declarations - class Object; - class Type; - template class SeqBase; - class String; - class List; - template class MapBase; - class Tuple; - class Dict; - - // new_reference_to also overloaded below on Object - inline PyObject* new_reference_to(PyObject* p) - { - Py::_XINCREF(p); - return p; - } - - // returning Null() from an extension method triggers a - // Python exception - inline PyObject* Null() - { - return (static_cast(0)); - } - - //===========================================================================// - // class Object - // The purpose of this class is to serve as the most general kind of - // Python object, for the purpose of writing C++ extensions in Python - // Objects hold a PyObject* which they own. This pointer is always a - // valid pointer to a Python object. In children we must maintain this behavior. - // - // Instructions on how to make your own class MyType descended from Object: - // (0) Pick a base class, either Object or perhaps SeqBase or MapBase. - // This example assumes Object. - - // (1) Write a routine int MyType_Check (PyObject *) modeled after PyInt_Check, - // PyFloat_Check, etc. - - // (2) Add method accepts: - // virtual bool accepts (PyObject *pyob) const { - // return pyob && MyType_Check (pyob); - // } - - // (3) Include the following constructor and copy constructor - // - /* - explicit MyType (PyObject *pyob): Object(pyob) { - validate(); -} - - MyType(const Object& other): Object(other.ptr()) { - validate(); -} - */ - - // Alernate version for the constructor to allow for construction from owned pointers: - /* - explicit MyType (PyObject *pyob): Object(pyob) { - validate(); -} - */ - - // You may wish to add other constructors; see the classes below for examples. - // Each constructor must use "set" to set the pointer - // and end by validating the pointer you have created. - - // (4) Each class needs at least these two assignment operators: - /* - MyType& operator= (const Object& rhs) { - return (*this = *rhs); -} - - Mytype& operator= (PyObject* rhsp) { - if(ptr() == rhsp) return *this; - set(rhsp); - return *this; -} - */ - // Note on accepts: constructors call the base class - // version of a virtual when calling the base class constructor, - // so the test has to be done explicitly in a descendent. - - // If you are inheriting from PythonExtension to define an object - // note that it contains PythonExtension::check - // which you can use in accepts when writing a wrapper class. - // See Demo/range.h and Demo/range.cxx for an example. - - class Object - { - private: - // the pointer to the Python object - // Only Object sets this directly. - // The default constructor for Object sets it to Py_None and - // child classes must use "set" to set it - // - PyObject* p; - - protected: - - void set (PyObject* pyob, bool owned = false) - { - release(); - p = pyob; - if (!owned) - { - Py::_XINCREF (p); - } - validate(); - } - - void release () - { - Py::_XDECREF (p); - p = 0; - } - - void validate(); - - public: - // Constructor acquires new ownership of pointer unless explicitly told not to. - explicit Object (PyObject* pyob=Py::_None(), bool owned = false): p (pyob) - { - if(!owned) - { - Py::_XINCREF (p); - } - validate(); - } - - // Copy constructor acquires new ownership of pointer - Object (const Object& ob): p(ob.p) - { - Py::_XINCREF (p); - validate(); - } - - // Assignment acquires new ownership of pointer - Object& operator= (const Object& rhs) - { - set(rhs.p); - return *this; - } - - Object& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - - // Destructor - virtual ~Object () - { - release (); - } - - // Loaning the pointer to others, retain ownership - PyObject* operator* () const - { - return p; - } - - // Explicit reference_counting changes - void increment_reference_count() - { - Py::_XINCREF(p); - } - - void decrement_reference_count() - { - // not allowed to commit suicide, however - if(reference_count() == 1) - throw RuntimeError("Object::decrement_reference_count error."); - Py::_XDECREF(p); - } - // Would like to call this pointer() but messes up STL in SeqBase - PyObject* ptr () const - { - return p; - } - - // - // Queries - // - - // Can pyob be used in this object's constructor? - virtual bool accepts (PyObject *pyob) const - { - return (pyob != 0); - } - - Py_ssize_t reference_count () const - { // the reference count - return p ? p->ob_refcnt : 0; - } - - Type type () const; // the type object associated with this one - - String str () const; // the str() representation - - std::string as_string() const; - - String repr () const; // the repr () representation - - List dir () const; // the dir() list - - bool hasAttr (const std::string& s) const - { - return PyObject_HasAttrString (p, const_cast(s.c_str())) ? true: false; - } - - Object getAttr (const std::string& s) const - { - return Object (PyObject_GetAttrString (p, const_cast(s.c_str())), true); - } - - Object callMemberFunction( const std::string &function_name ) const; - Object callMemberFunction( const std::string &function_name, const Tuple &args ) const; - Object callMemberFunction( const std::string &function_name, const Tuple &args, const Dict &kw ) const; - - Object getItem (const Object& key) const - { - return Object (PyObject_GetItem(p, *key), true); - } - - long hashValue () const - { - return PyObject_Hash (p); - } - - // - // int print (FILE* fp, int flags=Py_Print_RAW) - //{ - // return PyObject_Print (p, fp, flags); - //} - // - bool is(PyObject *pother) const - { // identity test - return p == pother; - } - - bool is(const Object& other) const - { // identity test - return p == other.p; - } - - bool isNone() const - { - return p == _None(); - } - - bool isCallable () const - { - return PyCallable_Check (p) != 0; - } - - bool isInstance () const - { - return PyInstance_Check (p) != 0; - } - - bool isDict () const - { - return Py::_Dict_Check (p); - } - - bool isList () const - { - return Py::_List_Check (p); - } - - bool isMapping () const - { - return PyMapping_Check (p) != 0; - } - - bool isNumeric () const - { - return PyNumber_Check (p) != 0; - } - - bool isSequence () const - { - return PySequence_Check (p) != 0; - } - - bool isTrue () const - { - return PyObject_IsTrue (p) != 0; - } - - bool isType (const Type& t) const; - - bool isTuple() const - { - return Py::_Tuple_Check(p); - } - - bool isString() const - { - return Py::_String_Check(p) || Py::_Unicode_Check(p); - } - - bool isUnicode() const - { - return Py::_Unicode_Check( p ); - } - - bool isBoolean() const - { - return Py::_Boolean_Check( p ); - } - - // Commands - void setAttr (const std::string& s, const Object& value) - { - if(PyObject_SetAttrString (p, const_cast(s.c_str()), *value) == -1) - throw AttributeError ("getAttr failed."); - } - - void delAttr (const std::string& s) - { - if(PyObject_DelAttrString (p, const_cast(s.c_str())) == -1) - throw AttributeError ("delAttr failed."); - } - - // PyObject_SetItem is too weird to be using from C++ - // so it is intentionally omitted. - - void delItem (const Object& key) - { - //if(PyObject_DelItem(p, *key) == -1) - // failed to link on Windows? - throw KeyError("delItem failed."); - } - - // Equality and comparison use PyObject_RichCompareBool - - bool operator==(const Object& o2) const - { - int k = PyObject_RichCompareBool (p, *o2, Py_EQ); - if (PyErr_Occurred()) throw Exception(); - return k != 0; - } - - bool operator!=(const Object& o2) const - { - int k = PyObject_RichCompareBool (p, *o2, Py_NE); - if (PyErr_Occurred()) throw Exception(); - return k != 0; - - } - - bool operator>=(const Object& o2) const - { - int k = PyObject_RichCompareBool (p, *o2, Py_GE); - if (PyErr_Occurred()) throw Exception(); - return k != 0; - } - - bool operator<=(const Object& o2) const - { - int k = PyObject_RichCompareBool (p, *o2, Py_LE); - if (PyErr_Occurred()) throw Exception(); - return k != 0; - } - - bool operator<(const Object& o2) const - { - int k = PyObject_RichCompareBool (p, *o2, Py_LT); - if (PyErr_Occurred()) throw Exception(); - return k != 0; - } - - bool operator>(const Object& o2) const - { - int k = PyObject_RichCompareBool (p, *o2, Py_GT); - if (PyErr_Occurred()) throw Exception(); - return k != 0; - } - }; - // End of class Object - inline PyObject* new_reference_to(const Object& g) - { - PyObject* p = g.ptr(); - Py::_XINCREF(p); - return p; - } - - // Nothing() is what an extension method returns if - // there is no other return value. - inline Object Nothing() - { - return Object(Py::_None()); - } - - // Python special None value - inline Object None() - { - return Object(Py::_None()); - } - - // Python special Boolean values - inline Object False() - { - return Object(Py::_False()); - } - - inline Object True() - { - return Object(Py::_True()); - } - - // TMM: 31May'01 - Added the #ifndef so I can exlude iostreams. -#ifndef CXX_NO_IOSTREAMS - std::ostream& operator<< (std::ostream& os, const Object& ob); -#endif - - // Class Type - class Type: public Object - { - public: - explicit Type (PyObject* pyob, bool owned = false): Object(pyob, owned) - { - validate(); - } - - Type (const Object& ob): Object(*ob) - { - validate(); - } - - Type(const Type& t): Object(t) - { - validate(); - } - - Type& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Type& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Type_Check (pyob); - } - }; - - - // - // Convert an owned Python pointer into a CXX Object - // - inline Object asObject (PyObject *p) - { - return Object(p, true); - } - - // =============================================== - // class boolean - class Boolean: public Object - { - public: - // Constructor - Boolean (PyObject *pyob, bool owned = false) - : Object (pyob, owned) - { - validate(); - } - - Boolean (const Boolean& ob): Object(*ob) - { - validate(); - } - - // create from bool - Boolean (bool v=false) - { - set(PyBool_FromLong(v ? 1 : 0), true); - validate(); - } - - explicit Boolean (const Object& ob) - : Object( *ob ) - { - validate(); - } - - // Assignment increases reference count on pointer - - Boolean& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Boolean& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && PyObject_IsTrue(pyob) != -1; - } - - // convert to long - operator bool() const - { - return PyObject_IsTrue (ptr()) != 0; - } - - Boolean& operator= (bool v) - { - set (PyBool_FromLong (v ? 1 : 0), true); - return *this; - } - }; - - // =============================================== - // class Int - class Int: public Object - { - public: - // Constructor - Int (PyObject *pyob, bool owned = false): Object (pyob, owned) - { - validate(); - } - - Int (const Int& ob): Object(*ob) - { - validate(); - } - - // create from long - Int (long v = 0L): Object(PyInt_FromLong(v), true) - { - validate(); - } - - // create from int - Int (int v) - { - long w = v; - set(PyInt_FromLong(w), true); - validate(); - } - - // create from bool - Int (bool v) - { - long w = v ? 1 : 0; - set(PyInt_FromLong(w), true); - validate(); - } - - explicit Int (const Object& ob) - { - set(PyNumber_Int(*ob), true); - validate(); - } - - // Assignment acquires new ownership of pointer - - Int& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Int& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (PyNumber_Int(rhsp), true); - return *this; - } - - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Int_Check (pyob); - } - - // convert to long - operator long() const - { - return PyInt_AsLong (ptr()); - } - -#ifdef HAVE_LONG_LONG - // convert to long long - PY_LONG_LONG asLongLong() const - { - return PyLong_AsLongLong (ptr()); - } - // convert to unsigned long long - unsigned PY_LONG_LONG asUnsignedLongLong() const - { - return PyLong_AsUnsignedLongLong (ptr()); - } -#endif - - // assign from an int - Int& operator= (int v) - { - set (PyInt_FromLong (long(v)), true); - return *this; - } - - // assign from long - Int& operator= (long v) - { - set (PyInt_FromLong (v), true); - return *this; - } - -#ifdef HAVE_LONG_LONG - // assign from long long - Int& operator= (PY_LONG_LONG v) - { - set (PyLong_FromLongLong (v), true); - return *this; - } - // assign from unsigned long long - Int& operator= (unsigned PY_LONG_LONG v) - { - set (PyLong_FromUnsignedLongLong (v), true); - return *this; - } -#endif - }; - - // =============================================== - // class Long - class Long: public Object - { - public: - // Constructor - explicit Long (PyObject *pyob, bool owned = false): Object (pyob, owned) - { - validate(); - } - - Long (const Long& ob): Object(ob.ptr()) - { - validate(); - } - - // create from long - explicit Long (long v = 0L) - : Object(PyLong_FromLong(v), true) - { - validate(); - } - // create from unsigned long - explicit Long (unsigned long v) - : Object(PyLong_FromUnsignedLong(v), true) - { - validate(); - } - // create from int - explicit Long (int v) - : Object(PyLong_FromLong(static_cast(v)), true) - { - validate(); - } - - // try to create from any object - Long (const Object& ob) - : Object(PyNumber_Long(*ob), true) - { - validate(); - } - - // Assignment acquires new ownership of pointer - - Long& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Long& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (PyNumber_Long(rhsp), true); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Long_Check (pyob); - } - - // convert to long - long as_long() const - { - return PyLong_AsLong( ptr() ); - } - - // convert to long - operator long() const - { - return as_long(); - } - - // convert to unsigned - operator unsigned long() const - { - return PyLong_AsUnsignedLong (ptr()); - } - operator double() const - { - return PyLong_AsDouble (ptr()); - } - // assign from an int - Long& operator= (int v) - { - set(PyLong_FromLong (long(v)), true); - return *this; - } - // assign from long - Long& operator= (long v) - { - set(PyLong_FromLong (v), true); - return *this; - } - // assign from unsigned long - Long& operator= (unsigned long v) - { - set(PyLong_FromUnsignedLong (v), true); - return *this; - } - }; - -#ifdef HAVE_LONG_LONG - // =============================================== - // class LongLong - class LongLong: public Object - { - public: - // Constructor - explicit LongLong (PyObject *pyob, bool owned = false): Object (pyob, owned) - { - validate(); - } - - LongLong (const LongLong& ob): Object(ob.ptr()) - { - validate(); - } - // create from long long - explicit LongLong (PY_LONG_LONG v = 0L) - : Object(PyLong_FromLongLong(v), true) - { - validate(); - } - // create from unsigned long long - explicit LongLong (unsigned PY_LONG_LONG v) - : Object(PyLong_FromUnsignedLongLong(v), true) - { - validate(); - } - // create from long - explicit LongLong (long v) - : Object(PyLong_FromLongLong(v), true) - { - validate(); - } - // create from unsigned long - explicit LongLong (unsigned long v) - : Object(PyLong_FromUnsignedLongLong(v), true) - { - validate(); - } - // create from int - explicit LongLong (int v) - : Object(PyLong_FromLongLong(static_cast(v)), true) - { - validate(); - } - - // try to create from any object - LongLong (const Object& ob) - : Object(PyNumber_Long(*ob), true) - { - validate(); - } - - // Assignment acquires new ownership of pointer - - LongLong& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - LongLong& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (PyNumber_Long(rhsp), true); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Long_Check (pyob); - } - // convert to long long - operator PY_LONG_LONG() const - { - return PyLong_AsLongLong (ptr()); - } - // convert to unsigned long - operator unsigned PY_LONG_LONG() const - { - return PyLong_AsUnsignedLongLong (ptr()); - } - // convert to long - operator long() const - { - return PyLong_AsLong (ptr()); - } - // convert to unsigned - operator unsigned long() const - { - return PyLong_AsUnsignedLong (ptr()); - } - operator double() const - { - return PyLong_AsDouble (ptr()); - } - // assign from an int - LongLong& operator= (int v) - { - set(PyLong_FromLongLong (long(v)), true); - return *this; - } - // assign from long long - LongLong& operator= (PY_LONG_LONG v) - { - set(PyLong_FromLongLong (v), true); - return *this; - } - // assign from unsigned long long - LongLong& operator= (unsigned PY_LONG_LONG v) - { - set(PyLong_FromUnsignedLongLong (v), true); - return *this; - } - // assign from long - LongLong& operator= (long v) - { - set(PyLong_FromLongLong (v), true); - return *this; - } - // assign from unsigned long - LongLong& operator= (unsigned long v) - { - set(PyLong_FromUnsignedLongLong (v), true); - return *this; - } - }; -#endif - - // =============================================== - // class Float - // - class Float: public Object - { - public: - // Constructor - explicit Float (PyObject *pyob, bool owned = false): Object(pyob, owned) - { - validate(); - } - - Float (const Float& f): Object(f) - { - validate(); - } - - // make from double - explicit Float (double v=0.0) - : Object(PyFloat_FromDouble (v), true) - { - validate(); - } - - // try to make from any object - Float (const Object& ob) - : Object(PyNumber_Float(*ob), true) - { - validate(); - } - - Float& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Float& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (PyNumber_Float(rhsp), true); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Float_Check (pyob); - } - // convert to double - operator double () const - { - return PyFloat_AsDouble (ptr()); - } - // assign from a double - Float& operator= (double v) - { - set(PyFloat_FromDouble (v), true); - return *this; - } - // assign from an int - Float& operator= (int v) - { - set(PyFloat_FromDouble (double(v)), true); - return *this; - } - // assign from long - Float& operator= (long v) - { - set(PyFloat_FromDouble (double(v)), true); - return *this; - } - // assign from an Int - Float& operator= (const Int& iob) - { - set(PyFloat_FromDouble (double(long(iob))), true); - return *this; - } - }; - - // =============================================== - // class Complex - class Complex: public Object - { - public: - // Constructor - explicit Complex (PyObject *pyob, bool owned = false): Object(pyob, owned) - { - validate(); - } - - Complex (const Complex& f): Object(f) - { - validate(); - } - - // make from double - explicit Complex (double v=0.0, double w=0.0) - :Object(PyComplex_FromDoubles (v, w), true) - { - validate(); - } - - Complex& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Complex& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Complex_Check (pyob); - } - // convert to Py_complex - operator Py_complex () const - { - return PyComplex_AsCComplex (ptr()); - } - // assign from a Py_complex - Complex& operator= (const Py_complex& v) - { - set(PyComplex_FromCComplex (v), true); - return *this; - } - // assign from a double - Complex& operator= (double v) - { - set(PyComplex_FromDoubles (v, 0.0), true); - return *this; - } - // assign from an int - Complex& operator= (int v) - { - set(PyComplex_FromDoubles (double(v), 0.0), true); - return *this; - } - // assign from long - Complex& operator= (long v) - { - set(PyComplex_FromDoubles (double(v), 0.0), true); - return *this; - } - // assign from an Int - Complex& operator= (const Int& iob) - { - set(PyComplex_FromDoubles (double(long(iob)), 0.0), true); - return *this; - } - - double real() const - { - return PyComplex_RealAsDouble(ptr()); - } - - double imag() const - { - return PyComplex_ImagAsDouble(ptr()); - } - }; - // Sequences - // Sequences are here represented as sequences of items of type T. - // The base class SeqBase represents that. - // In basic Python T is always "Object". - - // seqref is what you get if you get elements from a non-const SeqBase. - // Note: seqref could probably be a nested class in SeqBase but that might stress - // some compilers needlessly. Simlarly for mapref later. - - // While this class is not intended for enduser use, it needs some public - // constructors for the benefit of the STL. - - // See Scott Meyer's More Essential C++ for a description of proxies. - // This application is even more complicated. We are doing an unusual thing - // in having a double proxy. If we want the STL to work - // properly we have to compromise by storing the rvalue inside. The - // entire Object API is repeated so that things like s[i].isList() will - // work properly. - - // Still, once in a while a weird compiler message may occur using expressions like x[i] - // Changing them to Object(x[i]) helps the compiler to understand that the - // conversion of a seqref to an Object is wanted. - - template - class seqref - { - protected: - SeqBase& s; // the sequence - int offset; // item number - T the_item; // lvalue - public: - - seqref (SeqBase& seq, sequence_index_type j) - : s(seq), offset(j), the_item (s.getItem(j)) - {} - - seqref (const seqref& range) - : s(range.s), offset(range.offset), the_item(range.the_item) - {} - - // TMM: added this seqref ctor for use with STL algorithms - seqref (Object& obj) - : s(dynamic_cast< SeqBase&>(obj)) - , offset( NULL ) - , the_item(s.getItem(offset)) - {} - ~seqref() - {} - - operator T() const - { // rvalue - return the_item; - } - - seqref& operator=(const seqref& rhs) - { //used as lvalue - the_item = rhs.the_item; - s.setItem(offset, the_item); - return *this; - } - - seqref& operator=(const T& ob) - { // used as lvalue - the_item = ob; - s.setItem(offset, ob); - return *this; - } - - // forward everything else to the item - PyObject* ptr () const - { - return the_item.ptr(); - } - - int reference_count () const - { // the reference count - return the_item.reference_count(); - } - - Type type () const - { - return the_item.type(); - } - - String str () const; - - String repr () const; - - bool hasAttr (const std::string& attr_name) const - { - return the_item.hasAttr(attr_name); - } - - Object getAttr (const std::string& attr_name) const - { - return the_item.getAttr(attr_name); - } - - Object getItem (const Object& key) const - { - return the_item.getItem(key); - } - - long hashValue () const - { - return the_item.hashValue(); - } - - bool isCallable () const - { - return the_item.isCallable(); - } - - bool isInstance () const - { - return the_item.isInstance(); - } - - bool isDict () const - { - return the_item.isDict(); - } - - bool isList () const - { - return the_item.isList(); - } - - bool isMapping () const - { - return the_item.isMapping(); - } - - bool isNumeric () const - { - return the_item.isNumeric(); - } - - bool isSequence () const - { - return the_item.isSequence(); - } - - bool isTrue () const - { - return the_item.isTrue(); - } - - bool isType (const Type& t) const - { - return the_item.isType (t); - } - - bool isTuple() const - { - return the_item.isTuple(); - } - - bool isString() const - { - return the_item.isString(); - } - // Commands - void setAttr (const std::string& attr_name, const Object& value) - { - the_item.setAttr(attr_name, value); - } - - void delAttr (const std::string& attr_name) - { - the_item.delAttr(attr_name); - } - - void delItem (const Object& key) - { - the_item.delItem(key); - } - - bool operator==(const Object& o2) const - { - return the_item == o2; - } - - bool operator!=(const Object& o2) const - { - return the_item != o2; - } - - bool operator>=(const Object& o2) const - { - return the_item >= o2; - } - - bool operator<=(const Object& o2) const - { - return the_item <= o2; - } - - bool operator<(const Object& o2) const - { - return the_item < o2; - } - - bool operator>(const Object& o2) const - { - return the_item > o2; - } - }; // end of seqref - - - // class SeqBase - // ...the base class for all sequence types - - template - class SeqBase: public Object - { - public: - // STL definitions - typedef size_t size_type; - typedef seqref reference; - typedef T const_reference; - typedef seqref* pointer; - typedef int difference_type; - typedef T value_type; // TMM: 26Jun'01 - - virtual size_type max_size() const - { - return std::string::npos; // ? - } - - virtual size_type capacity() const - { - return size(); - } - - virtual void swap(SeqBase& c) - { - SeqBase temp = c; - c = ptr(); - set(temp.ptr()); - } - - virtual size_type size () const - { - return PySequence_Length (ptr()); - } - - explicit SeqBase () - :Object(PyTuple_New(0), true) - { - validate(); - } - - explicit SeqBase (PyObject* pyob, bool owned=false) - : Object(pyob, owned) - { - validate(); - } - - SeqBase (const Object& ob): Object(ob) - { - validate(); - } - - // Assignment acquires new ownership of pointer - - SeqBase& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - SeqBase& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - - virtual bool accepts (PyObject *pyob) const - { - return pyob && PySequence_Check (pyob); - } - - size_type length () const - { - return PySequence_Length (ptr()); - } - - // Element access - const T operator[](sequence_index_type index) const - { - return getItem(index); - } - - seqref operator[](sequence_index_type index) - { - return seqref(*this, index); - } - - virtual T getItem (sequence_index_type i) const - { - return T(asObject(PySequence_GetItem (ptr(), i))); - } - - virtual void setItem (sequence_index_type i, const T& ob) - { - if (PySequence_SetItem (ptr(), i, *ob) == -1) - { - throw Exception(); - } - } - - SeqBase repeat (int count) const - { - return SeqBase (PySequence_Repeat (ptr(), count), true); - } - - SeqBase concat (const SeqBase& other) const - { - return SeqBase (PySequence_Concat(ptr(), *other), true); - } - - // more STL compatability - const T front () const - { - return getItem(0); - } - - seqref front() - { - return seqref(*this, 0); - } - - const T back() const - { - return getItem(size()-1); - } - - seqref back() - { - return seqref(*this, size()-1); - } - - void verify_length(size_type required_size) const - { - if (size() != required_size) - throw IndexError ("Unexpected SeqBase length."); - } - - void verify_length(size_type min_size, size_type max_size) const - { - size_type n = size(); - if (n < min_size || n > max_size) - throw IndexError ("Unexpected SeqBase length."); - } - - class iterator - : public random_access_iterator_parent(seqref) - { - protected: - friend class SeqBase; - SeqBase* seq; - int count; - - public: - ~iterator () - {} - - iterator () - : seq( 0 ) - , count( 0 ) - {} - - iterator (SeqBase* s, int where) - : seq( s ) - , count( where ) - {} - - iterator (const iterator& other) - : seq( other.seq ) - , count( other.count ) - {} - - bool eql (const iterator& other) const - { - return (seq->ptr() == other.seq->ptr()) && (count == other.count); - } - - bool neq (const iterator& other) const - { - return (seq->ptr() != other.seq->ptr()) || (count != other.count); - } - - bool lss (const iterator& other) const - { - return (count < other.count); - } - - bool gtr (const iterator& other) const - { - return (count > other.count); - } - - bool leq (const iterator& other) const - { - return (count <= other.count); - } - - bool geq (const iterator& other) const - { - return (count >= other.count); - } - - seqref operator*() - { - return seqref(*seq, count); - } - - seqref operator[] (sequence_index_type i) - { - return seqref(*seq, count + i); - } - - iterator& operator=(const iterator& other) - { - if (this == &other) return *this; - seq = other.seq; - count = other.count; - return *this; - } - - iterator operator+(int n) const - { - return iterator(seq, count + n); - } - - iterator operator-(int n) const - { - return iterator(seq, count - n); - } - - iterator& operator+=(int n) - { - count = count + n; - return *this; - } - - iterator& operator-=(int n) - { - count = count - n; - return *this; - } - - int operator-(const iterator& other) const - { - if (*seq != *other.seq) - throw RuntimeError ("SeqBase::iterator comparison error"); - return count - other.count; - } - - // prefix ++ - iterator& operator++ () - { count++; return *this;} - // postfix ++ - iterator operator++ (int) - { return iterator(seq, count++);} - // prefix -- - iterator& operator-- () - { count--; return *this;} - // postfix -- - iterator operator-- (int) - { return iterator(seq, count--);} - - std::string diagnose() const - { - std::OSTRSTREAM oss; - oss << "iterator diagnosis " << seq << ", " << count << std::ends; - return std::string(oss.str()); - } - }; // end of class SeqBase::iterator - - iterator begin () - { - return iterator(this, 0); - } - - iterator end () - { - return iterator(this, length()); - } - - class const_iterator - : public random_access_iterator_parent(const Object) - { - protected: - friend class SeqBase; - const SeqBase* seq; - sequence_index_type count; - - private: - const_iterator (const SeqBase* s, int where) - : seq( s ) - , count( where ) - {} - - public: - ~const_iterator () - {} - - const_iterator () - : seq( 0 ) - , count( 0 ) - {} - - const_iterator(const const_iterator& other) - : seq( other.seq ) - , count( other.count ) - {} - - const T operator*() const - { - return seq->getItem(count); - } - - const T operator[] (sequence_index_type i) const - { - return seq->getItem(count + i); - } - - const_iterator& operator=(const const_iterator& other) - { - if (this == &other) return *this; - seq = other.seq; - count = other.count; - return *this; - } - - const_iterator operator+(int n) const - { - return const_iterator(seq, count + n); - } - - bool eql (const const_iterator& other) const - { - return (seq->ptr() == other.seq->ptr()) && (count == other.count); - } - - bool neq (const const_iterator& other) const - { - return (seq->ptr() != other.seq->ptr()) || (count != other.count); - } - - bool lss (const const_iterator& other) const - { - return (count < other.count); - } - - bool gtr (const const_iterator& other) const - { - return (count > other.count); - } - - bool leq (const const_iterator& other) const - { - return (count <= other.count); - } - - bool geq (const const_iterator& other) const - { - return (count >= other.count); - } - - const_iterator operator-(int n) - { - return const_iterator(seq, count - n); - } - - const_iterator& operator+=(int n) - { - count = count + n; - return *this; - } - - const_iterator& operator-=(int n) - { - count = count - n; - return *this; - } - - int operator-(const const_iterator& other) const - { - if (*seq != *other.seq) - throw RuntimeError ("SeqBase::const_iterator::- error"); - return count - other.count; - } - // prefix ++ - const_iterator& operator++ () - { count++; return *this;} - // postfix ++ - const_iterator operator++ (int) - { return const_iterator(seq, count++);} - // prefix -- - const_iterator& operator-- () - { count--; return *this;} - // postfix -- - const_iterator operator-- (int) - { return const_iterator(seq, count--);} - }; // end of class SeqBase::const_iterator - - const_iterator begin () const - { - return const_iterator(this, 0); - } - - const_iterator end () const - { - return const_iterator(this, length()); - } - }; - - // Here's an important typedef you might miss if reading too fast... - typedef SeqBase Sequence; - - template bool operator==(const EXPLICIT_TYPENAME SeqBase::iterator& left, const EXPLICIT_TYPENAME SeqBase::iterator& right); - template bool operator!=(const EXPLICIT_TYPENAME SeqBase::iterator& left, const EXPLICIT_TYPENAME SeqBase::iterator& right); - template bool operator< (const EXPLICIT_TYPENAME SeqBase::iterator& left, const EXPLICIT_TYPENAME SeqBase::iterator& right); - template bool operator> (const EXPLICIT_TYPENAME SeqBase::iterator& left, const EXPLICIT_TYPENAME SeqBase::iterator& right); - template bool operator<=(const EXPLICIT_TYPENAME SeqBase::iterator& left, const EXPLICIT_TYPENAME SeqBase::iterator& right); - template bool operator>=(const EXPLICIT_TYPENAME SeqBase::iterator& left, const EXPLICIT_TYPENAME SeqBase::iterator& right); - - template bool operator==(const EXPLICIT_TYPENAME SeqBase::const_iterator& left, const EXPLICIT_TYPENAME SeqBase::const_iterator& right); - template bool operator!=(const EXPLICIT_TYPENAME SeqBase::const_iterator& left, const EXPLICIT_TYPENAME SeqBase::const_iterator& right); - template bool operator< (const EXPLICIT_TYPENAME SeqBase::const_iterator& left, const EXPLICIT_TYPENAME SeqBase::const_iterator& right); - template bool operator> (const EXPLICIT_TYPENAME SeqBase::const_iterator& left, const EXPLICIT_TYPENAME SeqBase::const_iterator& right); - template bool operator<=(const EXPLICIT_TYPENAME SeqBase::const_iterator& left, const EXPLICIT_TYPENAME SeqBase::const_iterator& right); - template bool operator>=(const EXPLICIT_TYPENAME SeqBase::const_iterator& left, const EXPLICIT_TYPENAME SeqBase::const_iterator& right); - - extern bool operator==(const Sequence::iterator& left, const Sequence::iterator& right); - extern bool operator!=(const Sequence::iterator& left, const Sequence::iterator& right); - extern bool operator< (const Sequence::iterator& left, const Sequence::iterator& right); - extern bool operator> (const Sequence::iterator& left, const Sequence::iterator& right); - extern bool operator<=(const Sequence::iterator& left, const Sequence::iterator& right); - extern bool operator>=(const Sequence::iterator& left, const Sequence::iterator& right); - - extern bool operator==(const Sequence::const_iterator& left, const Sequence::const_iterator& right); - extern bool operator!=(const Sequence::const_iterator& left, const Sequence::const_iterator& right); - extern bool operator< (const Sequence::const_iterator& left, const Sequence::const_iterator& right); - extern bool operator> (const Sequence::const_iterator& left, const Sequence::const_iterator& right); - extern bool operator<=(const Sequence::const_iterator& left, const Sequence::const_iterator& right); - extern bool operator>=(const Sequence::const_iterator& left, const Sequence::const_iterator& right); - - // ================================================== - // class Char - // Python strings return strings as individual elements. - // I'll try having a class Char which is a String of length 1 - // - typedef std::basic_string unicodestring; - extern Py_UNICODE unicode_null_string[1]; - - class Char: public Object - { - public: - explicit Char (PyObject *pyob, bool owned = false): Object(pyob, owned) - { - validate(); - } - - Char (const Object& ob): Object(ob) - { - validate(); - } - - Char (const std::string& v = "") - :Object(PyString_FromStringAndSize (const_cast(v.c_str()),1), true) - { - validate(); - } - - Char (char v) - : Object(PyString_FromStringAndSize (&v, 1), true) - { - validate(); - } - - Char (Py_UNICODE v) - : Object(PyUnicode_FromUnicode (&v, 1), true) - { - validate(); - } - // Assignment acquires new ownership of pointer - Char& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Char& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob)) && PySequence_Length (pyob) == 1; - } - - // Assignment from C string - Char& operator= (const std::string& v) - { - set(PyString_FromStringAndSize (const_cast(v.c_str()),1), true); - return *this; - } - - Char& operator= (char v) - { - set(PyString_FromStringAndSize (&v, 1), true); - return *this; - } - - Char& operator= (const unicodestring& v) - { - set(PyUnicode_FromUnicode (const_cast(v.data()),1), true); - return *this; - } - - Char& operator= (Py_UNICODE v) - { - set(PyUnicode_FromUnicode (&v, 1), true); - return *this; - } - - // Conversion - operator String() const; - - operator std::string () const - { - return std::string(PyString_AsString (ptr())); - } - }; - -#ifdef PYCXX_PYTHON_2TO3 - // String and Bytes compatible with Python3 version in 6.0.0 PyCXX - class Bytes; - - class String: public SeqBase - { - public: - virtual size_type capacity() const - { - return max_size(); - } - - explicit String( PyObject *pyob, bool owned = false) - : SeqBase( pyob, owned ) - { - validate(); - } - - String( const Object& ob): SeqBase(ob) - { - validate(); - } - - String() - : SeqBase( PyString_FromStringAndSize( "", 0 ), true ) - { - validate(); - } - - String( const std::string& v ) - : SeqBase( PyString_FromStringAndSize( const_cast(v.data()), - static_cast( v.length() ) ), true ) - { - validate(); - } - - String( const Py_UNICODE *s, int length ) - : SeqBase( PyUnicode_FromUnicode( s, length ), true ) - { - validate(); - } - - String( const char *s, const char *encoding, const char *error="strict" ) - : SeqBase( PyUnicode_Decode( s, strlen( s ), encoding, error ), true ) - { - validate(); - } - - String( const char *s, int len, const char *encoding, const char *error="strict" ) - : SeqBase( PyUnicode_Decode( s, len, encoding, error ), true ) - { - validate(); - } - - String( const std::string &s, const char *encoding, const char *error="strict" ) - : SeqBase( PyUnicode_Decode( s.c_str(), s.length(), encoding, error ), true ) - { - validate(); - } - - String( const char *v, int vsize ) - : SeqBase(PyString_FromStringAndSize( const_cast(v), vsize ), true ) - { - validate(); - } - - String( const char *v ) - : SeqBase( PyString_FromString( v ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - String &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - String& operator= (PyObject *rhsp) - { - if( ptr() == rhsp ) - return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob)); - } - - // Assignment from C string - String& operator=( const std::string &v ) - { - set( PyString_FromStringAndSize( const_cast( v.data() ), - static_cast( v.length() ) ), true ); - return *this; - } - String& operator=( const unicodestring &v ) - { - set( PyUnicode_FromUnicode( const_cast( v.data() ), - static_cast( v.length() ) ), true ); - return *this; - } - - // Encode - Bytes encode( const char *encoding, const char *error="strict" ) const; - - // Queries - virtual size_type size() const - { - if( isUnicode() ) - { - return static_cast( PyUnicode_GET_SIZE (ptr()) ); - } - else - { - return static_cast( PyString_Size (ptr()) ); - } - } - - operator std::string() const - { - return as_std_string( "utf-8" ); - } - - std::string as_std_string( const char *encoding, const char *error="strict" ) const; - - unicodestring as_unicodestring() const - { - if( isUnicode() ) - { - return unicodestring( PyUnicode_AS_UNICODE( ptr() ), - static_cast( PyUnicode_GET_SIZE( ptr() ) ) ); - } - else - { - throw TypeError("can only return unicodestring from Unicode object"); - } - } - - const Py_UNICODE *unicode_data() const - { - if( isUnicode() ) - { - return PyUnicode_AS_UNICODE( ptr() ); - } - else - { - throw TypeError("can only return unicode_data from Unicode object"); - } - } - }; - class Bytes: public SeqBase - { - public: - virtual size_type capacity() const - { - return max_size(); - } - - explicit Bytes (PyObject *pyob, bool owned = false): SeqBase(pyob, owned) - { - validate(); - } - - Bytes (const Object& ob): SeqBase(ob) - { - validate(); - } - - Bytes() - : SeqBase( PyString_FromStringAndSize( "", 0 ), true ) - { - validate(); - } - - Bytes( const std::string& v ) - : SeqBase( PyString_FromStringAndSize( const_cast(v.data()), static_cast( v.length() ) ), true ) - { - validate(); - } - - Bytes( const char *v, int vsize ) - : SeqBase(PyString_FromStringAndSize( const_cast(v), vsize ), true ) - { - validate(); - } - - Bytes( const char *v ) - : SeqBase( PyString_FromString( v ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - Bytes &operator= ( const Object& rhs ) - { - return *this = *rhs; - } - - Bytes &operator= (PyObject *rhsp) - { - if( ptr() == rhsp ) - return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && (Py::_String_Check( pyob ) || Py::_Unicode_Check( pyob )); - } - - // Assignment from C string - Bytes &operator= (const std::string& v) - { - set( PyString_FromStringAndSize( const_cast( v.data() ), - static_cast( v.length() ) ), true ); - return *this; - } - Bytes &operator= (const unicodestring& v) - { - set( PyUnicode_FromUnicode( const_cast( v.data() ), - static_cast( v.length() ) ), true ); - return *this; - } - - String decode( const char *encoding, const char *error="strict" ) - { - return Object( PyString_AsDecodedObject( ptr(), encoding, error ), true ); - } - - // Queries - virtual size_type size () const - { - if( isUnicode() ) - { - return static_cast( PyUnicode_GET_SIZE (ptr()) ); - } - else - { - return static_cast( PyString_Size (ptr()) ); - } - } - - operator std::string () const - { - return as_std_string(); - } - - std::string as_std_string() const - { - if( isUnicode() ) - { - throw TypeError("cannot return std::string from Unicode object"); - } - else - { - return std::string( PyString_AsString( ptr() ), static_cast( PyString_Size( ptr() ) ) ); - } - } - - unicodestring as_unicodestring() const - { - if( isUnicode() ) - { - return unicodestring( PyUnicode_AS_UNICODE( ptr() ), - static_cast( PyUnicode_GET_SIZE( ptr() ) ) ); - } - else - { - throw TypeError("can only return unicodestring from Unicode object"); - } - } - }; - -#else - // original PyCXX 5.4.x version of String - class String: public SeqBase - { - public: - virtual size_type capacity() const - { - return max_size(); - } - - explicit String (PyObject *pyob, bool owned = false): SeqBase(pyob, owned) - { - validate(); - } - - String (const Object& ob): SeqBase(ob) - { - validate(); - } - - String() - : SeqBase( PyString_FromStringAndSize( "", 0 ), true ) - { - validate(); - } - - String( const std::string& v ) - : SeqBase( PyString_FromStringAndSize( const_cast(v.data()), - static_cast( v.length() ) ), true ) - { - validate(); - } - - String( const char *s, const char *encoding, const char *error="strict" ) - : SeqBase( PyUnicode_Decode( s, strlen( s ), encoding, error ), true ) - { - validate(); - } - - String( const char *s, int len, const char *encoding, const char *error="strict" ) - : SeqBase( PyUnicode_Decode( s, len, encoding, error ), true ) - { - validate(); - } - - String( const std::string &s, const char *encoding, const char *error="strict" ) - : SeqBase( PyUnicode_Decode( s.c_str(), s.length(), encoding, error ), true ) - { - validate(); - } - - String( const char *v, int vsize ) - : SeqBase(PyString_FromStringAndSize( const_cast(v), vsize ), true ) - { - validate(); - } - - String( const char* v ) - : SeqBase( PyString_FromString( v ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - String& operator= ( const Object& rhs ) - { - return *this = *rhs; - } - - String& operator= (PyObject* rhsp) - { - if( ptr() == rhsp ) - return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob)); - } - - // Assignment from C string - String& operator= (const std::string& v) - { - set( PyString_FromStringAndSize( const_cast( v.data() ), - static_cast( v.length() ) ), true ); - return *this; - } - String& operator= (const unicodestring& v) - { - set( PyUnicode_FromUnicode( const_cast( v.data() ), - static_cast( v.length() ) ), true ); - return *this; - } - - - // Encode - String encode( const char *encoding, const char *error="strict" ) const - { - if( isUnicode() ) - { - return String( PyUnicode_AsEncodedString( ptr(), encoding, error ), true ); - } - else - { - return String( PyString_AsEncodedObject( ptr(), encoding, error ), true ); - } - } - - String decode( const char *encoding, const char *error="strict" ) - { - return Object( PyString_AsDecodedObject( ptr(), encoding, error ), true ); - } - - // Queries - virtual size_type size () const - { - if( isUnicode() ) - { - return static_cast( PyUnicode_GET_SIZE (ptr()) ); - } - else - { - return static_cast( PyString_Size (ptr()) ); - } - } - - operator std::string () const - { - return as_std_string(); - } - - std::string as_std_string() const - { - if( isUnicode() ) - { - throw TypeError("cannot return std::string from Unicode object"); - } - else - { - return std::string( PyString_AsString( ptr() ), static_cast( PyString_Size( ptr() ) ) ); - } - } - - std::string as_std_string( const char *encoding, const char *error="strict" ) const; - - unicodestring as_unicodestring() const - { - if( isUnicode() ) - { - return unicodestring( PyUnicode_AS_UNICODE( ptr() ), - static_cast( PyUnicode_GET_SIZE( ptr() ) ) ); - } - else - { - throw TypeError("can only return unicodestring from Unicode object"); - } - } - }; -#endif - - // ================================================== - // class Tuple - class Tuple: public Sequence - { - public: - virtual void setItem (sequence_index_type offset, const Object&ob) - { - // note PyTuple_SetItem is a thief... - if(PyTuple_SetItem (ptr(), offset, new_reference_to(ob)) == -1) - { - throw Exception(); - } - } - - // Constructor - explicit Tuple (PyObject *pyob, bool owned = false): Sequence (pyob, owned) - { - validate(); - } - - Tuple (const Object& ob): Sequence(ob) - { - validate(); - } - - // New tuple of a given size - explicit Tuple (int size = 0) - { - set(PyTuple_New (size), true); - validate (); - for (sequence_index_type i=0; i < size; i++) - { - if(PyTuple_SetItem (ptr(), i, new_reference_to(Py::_None())) == -1) - { - throw Exception(); - } - } - } - // Tuple from any sequence - explicit Tuple (const Sequence& s) - { - sequence_index_type limit( sequence_index_type( s.length() ) ); - - set(PyTuple_New (limit), true); - validate(); - - for(sequence_index_type i=0; i < limit; i++) - { - if(PyTuple_SetItem (ptr(), i, new_reference_to(s[i])) == -1) - { - throw Exception(); - } - } - } - // Assignment acquires new ownership of pointer - - Tuple& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Tuple& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Tuple_Check (pyob); - } - - Tuple getSlice (int i, int j) const - { - return Tuple (PySequence_GetSlice (ptr(), i, j), true); - } - - }; - - class TupleN: public Tuple - { - public: - TupleN() - : Tuple( 0 ) - { - } - - TupleN( const Object &obj1 ) - : Tuple( 1 ) - { - setItem( 0, obj1 ); - } - - TupleN( const Object &obj1, const Object &obj2 ) - : Tuple( 2 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3 ) - : Tuple( 3 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4 ) - : Tuple( 4 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5 ) - : Tuple( 5 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6 ) - : Tuple( 6 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6, - const Object &obj7 ) - : Tuple( 7 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - setItem( 6, obj7 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6, - const Object &obj7, const Object &obj8 ) - : Tuple( 8 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - setItem( 6, obj7 ); - setItem( 7, obj8 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6, - const Object &obj7, const Object &obj8, const Object &obj9 ) - : Tuple( 9 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - setItem( 6, obj7 ); - setItem( 7, obj8 ); - setItem( 8, obj9 ); - } - - virtual ~TupleN() - { } - }; - - - // ================================================== - // class List - - class List: public Sequence - { - public: - // Constructor - explicit List (PyObject *pyob, bool owned = false): Sequence(pyob, owned) - { - validate(); - } - List (const Object& ob): Sequence(ob) - { - validate(); - } - // Creation at a fixed size - List (int size = 0) - { - set(PyList_New (size), true); - validate(); - for (sequence_index_type i=0; i < size; i++) - { - if(PyList_SetItem (ptr(), i, new_reference_to(Py::_None())) == -1) - { - throw Exception(); - } - } - } - - // List from a sequence - List (const Sequence& s): Sequence() - { - int n = (int)s.length(); - set(PyList_New (n), true); - validate(); - for (sequence_index_type i=0; i < n; i++) - { - if(PyList_SetItem (ptr(), i, new_reference_to(s[i])) == -1) - { - throw Exception(); - } - } - } - - virtual size_type capacity() const - { - return max_size(); - } - // Assignment acquires new ownership of pointer - - List& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - List& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_List_Check (pyob); - } - - List getSlice (int i, int j) const - { - return List (PyList_GetSlice (ptr(), i, j), true); - } - - void setSlice (int i, int j, const Object& v) - { - if(PyList_SetSlice (ptr(), i, j, *v) == -1) - { - throw Exception(); - } - } - - void append (const Object& ob) - { - if(PyList_Append (ptr(), *ob) == -1) - { - throw Exception(); - } - } - - void insert (int i, const Object& ob) - { - if(PyList_Insert (ptr(), i, *ob) == -1) - { - throw Exception(); - } - } - - void sort () - { - if(PyList_Sort(ptr()) == -1) - { - throw Exception(); - } - } - - void reverse () - { - if(PyList_Reverse(ptr()) == -1) - { - throw Exception(); - } - } - }; - - - // Mappings - // ================================================== - template - class mapref - { - protected: - MapBase& s; // the map - Object key; // item key - T the_item; - - public: - mapref (MapBase& map, const std::string& k) - : s(map), the_item() - { - key = String(k); - if(map.hasKey(key)) the_item = map.getItem(key); - } - - mapref (MapBase& map, const Object& k) - : s(map), key(k), the_item() - { - if(map.hasKey(key)) the_item = map.getItem(key); - } - - virtual ~mapref() - {} - - // MapBase stuff - // lvalue - mapref& operator=(const mapref& other) - { - if(this == &other) return *this; - the_item = other.the_item; - s.setItem(key, other.the_item); - return *this; - } - - mapref& operator= (const T& ob) - { - the_item = ob; - s.setItem (key, ob); - return *this; - } - - // rvalue - operator T() const - { - return the_item; - } - - // forward everything else to the_item - PyObject* ptr () const - { - return the_item.ptr(); - } - - int reference_count () const - { // the mapref count - return the_item.reference_count(); - } - - Type type () const - { - return the_item.type(); - } - - String str () const - { - return the_item.str(); - } - - String repr () const - { - return the_item.repr(); - } - - bool hasAttr (const std::string& attr_name) const - { - return the_item.hasAttr(attr_name); - } - - Object getAttr (const std::string& attr_name) const - { - return the_item.getAttr(attr_name); - } - - Object getItem (const Object& k) const - { - return the_item.getItem(k); - } - - long hashValue () const - { - return the_item.hashValue(); - } - - bool isCallable () const - { - return the_item.isCallable(); - } - - bool isInstance () const - { - return the_item.isInstance(); - } - - bool isList () const - { - return the_item.isList(); - } - - bool isMapping () const - { - return the_item.isMapping(); - } - - bool isNumeric () const - { - return the_item.isNumeric(); - } - - bool isSequence () const - { - return the_item.isSequence(); - } - - bool isTrue () const - { - return the_item.isTrue(); - } - - bool isType (const Type& t) const - { - return the_item.isType (t); - } - - bool isTuple() const - { - return the_item.isTuple(); - } - - bool isString() const - { - return the_item.isString(); - } - - // Commands - void setAttr (const std::string& attr_name, const Object& value) - { - the_item.setAttr(attr_name, value); - } - - void delAttr (const std::string& attr_name) - { - the_item.delAttr(attr_name); - } - - void delItem (const Object& k) - { - the_item.delItem(k); - } - }; // end of mapref - - // TMM: now for mapref - template< class T > - bool operator==(const mapref& left, const mapref& right) - { - return true; // NOT completed. - } - - template< class T > - bool operator!=(const mapref& left, const mapref& right) - { - return true; // not completed. - } - - template - class MapBase: public Object - { - protected: - explicit MapBase() - {} - public: - // reference: proxy class for implementing [] - // TMM: 26Jun'01 - the types - // If you assume that Python mapping is a hash_map... - // hash_map::value_type is not assignable, but - // (*it).second = data must be a valid expression - typedef size_t size_type; - typedef Object key_type; - typedef mapref data_type; - typedef std::pair< const T, T > value_type; - typedef std::pair< const T, mapref > reference; - typedef const std::pair< const T, const T > const_reference; - typedef std::pair< const T, mapref > pointer; - - // Constructor - explicit MapBase (PyObject *pyob, bool owned = false): Object(pyob, owned) - { - validate(); - } - - // TMM: 02Jul'01 - changed MapBase to Object in next line - MapBase (const Object& ob): Object(ob) - { - validate(); - } - - // Assignment acquires new ownership of pointer - MapBase& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - MapBase& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && PyMapping_Check(pyob); - } - - // Clear -- PyMapping Clear is missing - // - - void clear () - { - List k = keys(); - for(List::iterator i = k.begin(); i != k.end(); i++) - { - delItem(*i); - } - } - - virtual size_type size() const - { - return PyMapping_Length (ptr()); - } - - // Element Access - T operator[](const std::string& key) const - { - return getItem(key); - } - - T operator[](const Object& key) const - { - return getItem(key); - } - - mapref operator[](const std::string& key) - { - return mapref(*this, key); - } - - mapref operator[](const Object& key) - { - return mapref(*this, key); - } - - int length () const - { - return PyMapping_Length (ptr()); - } - - bool hasKey (const std::string& s) const - { - return PyMapping_HasKeyString (ptr(),const_cast(s.c_str())) != 0; - } - - bool hasKey (const Object& s) const - { - return PyMapping_HasKey (ptr(), s.ptr()) != 0; - } - - T getItem (const std::string& s) const - { - return T( - asObject(PyMapping_GetItemString (ptr(),const_cast(s.c_str()))) - ); - } - - T getItem (const Object& s) const - { - return T( - asObject(PyObject_GetItem (ptr(), s.ptr())) - ); - } - - virtual void setItem (const char *s, const Object& ob) - { - if (PyMapping_SetItemString (ptr(), const_cast(s), *ob) == -1) - { - throw Exception(); - } - } - - virtual void setItem (const std::string& s, const Object& ob) - { - if (PyMapping_SetItemString (ptr(), const_cast(s.c_str()), *ob) == -1) - { - throw Exception(); - } - } - - virtual void setItem (const Object& s, const Object& ob) - { - if (PyObject_SetItem (ptr(), s.ptr(), ob.ptr()) == -1) - { - throw Exception(); - } - } - - void delItem (const std::string& s) - { - if (PyMapping_DelItemString (ptr(), const_cast(s.c_str())) == -1) - { - throw Exception(); - } - } - - void delItem (const Object& s) - { - if (PyMapping_DelItem (ptr(), *s) == -1) - { - throw Exception(); - } - } - // Queries - List keys () const - { - return List(PyMapping_Keys(ptr()), true); - } - - List values () const - { // each returned item is a (key, value) pair - return List(PyMapping_Values(ptr()), true); - } - - List items () const - { - return List(PyMapping_Items(ptr()), true); - } - - class iterator - { - // : public forward_iterator_parent( std::pair ) { - protected: - typedef std::forward_iterator_tag iterator_category; - typedef std::pair< const T, T > value_type; - typedef int difference_type; - typedef std::pair< const T, mapref > pointer; - typedef std::pair< const T, mapref > reference; - - friend class MapBase; - // - MapBase* map; - List keys; // for iterating over the map - int pos; // index into the keys - - private: - iterator( MapBase* m, List k, int p ) - : map( m ) - , keys( k ) - , pos( p ) - {} - - public: - ~iterator () - {} - - iterator () - : map( 0 ) - , keys() - , pos() - {} - - iterator (MapBase* m, bool end = false ) - : map( m ) - , keys( m->keys() ) - , pos( end ? keys.length() : 0 ) - {} - - iterator (const iterator& other) - : map( other.map ) - , keys( other.keys ) - , pos( other.pos ) - {} - - reference operator*() - { - Object key = keys[ pos ]; - return std::make_pair(key, mapref(*map,key)); - } - - iterator& operator=(const iterator& other) - { - if (this == &other) - return *this; - map = other.map; - keys = other.keys; - pos = other.pos; - return *this; - } - - bool eql(const iterator& right) const - { - return map->ptr() == right.map->ptr() && pos == right.pos; - } - bool neq( const iterator& right ) const - { - return map->ptr() != right.map->ptr() || pos != right.pos; - } - - // pointer operator->() { - // return ; - // } - - // prefix ++ - iterator& operator++ () - { pos++; return *this;} - // postfix ++ - iterator operator++ (int) - { return iterator(map, keys, pos++);} - // prefix -- - iterator& operator-- () - { pos--; return *this;} - // postfix -- - iterator operator-- (int) - { return iterator(map, keys, pos--);} - - std::string diagnose() const - { - std::OSTRSTREAM oss; - oss << "iterator diagnosis " << map << ", " << pos << std::ends; - return std::string(oss.str()); - } - }; // end of class MapBase::iterator - - iterator begin () - { - return iterator(this); - } - - iterator end () - { - return iterator(this, true); - } - - class const_iterator - { - protected: - typedef std::forward_iterator_tag iterator_category; - typedef const std::pair< const T, T > value_type; - typedef int difference_type; - typedef const std::pair< const T, T > pointer; - typedef const std::pair< const T, T > reference; - - friend class MapBase; - const MapBase* map; - List keys; // for iterating over the map - int pos; // index into the keys - - private: - const_iterator( const MapBase* m, List k, int p ) - : map( m ) - , keys( k ) - , pos( p ) - {} - - public: - ~const_iterator () - {} - - const_iterator () - : map( 0 ) - , keys() - , pos() - {} - - const_iterator (const MapBase* m, bool end = false ) - : map( m ) - , keys( m->keys() ) - , pos( end ? keys.length() : 0 ) - {} - - const_iterator(const const_iterator& other) - : map( other.map ) - , keys( other.keys ) - , pos( other.pos ) - {} - - bool eql(const const_iterator& right) const - { - return map->ptr() == right.map->ptr() && pos == right.pos; - } - - bool neq( const const_iterator& right ) const - { - return map->ptr() != right.map->ptr() || pos != right.pos; - } - - const_reference operator*() - { - Object key = keys[ pos ]; - return std::make_pair( key, mapref( *map, key ) ); - } - - const_iterator& operator=(const const_iterator& other) - { - if (this == &other) return *this; - map = other.map; - keys = other.keys; - pos = other.pos; - return *this; - } - - // prefix ++ - const_iterator& operator++ () - { pos++; return *this;} - // postfix ++ - const_iterator operator++ (int) - { return const_iterator(map, keys, pos++);} - // prefix -- - const_iterator& operator-- () - { pos--; return *this;} - // postfix -- - const_iterator operator-- (int) - { return const_iterator(map, keys, pos--);} - }; // end of class MapBase::const_iterator - - const_iterator begin () const - { - return const_iterator(this); - } - - const_iterator end () const - { - return const_iterator(this, true); - } - - }; // end of MapBase - - typedef MapBase Mapping; - - template bool operator==(const EXPLICIT_TYPENAME MapBase::iterator& left, const EXPLICIT_TYPENAME MapBase::iterator& right); - template bool operator!=(const EXPLICIT_TYPENAME MapBase::iterator& left, const EXPLICIT_TYPENAME MapBase::iterator& right); - template bool operator==(const EXPLICIT_TYPENAME MapBase::const_iterator& left, const EXPLICIT_TYPENAME MapBase::const_iterator& right); - template bool operator!=(const EXPLICIT_TYPENAME MapBase::const_iterator& left, const EXPLICIT_TYPENAME MapBase::const_iterator& right); - - extern bool operator==(const Mapping::iterator& left, const Mapping::iterator& right); - extern bool operator!=(const Mapping::iterator& left, const Mapping::iterator& right); - extern bool operator==(const Mapping::const_iterator& left, const Mapping::const_iterator& right); - extern bool operator!=(const Mapping::const_iterator& left, const Mapping::const_iterator& right); - - - // ================================================== - // class Dict - class Dict: public Mapping - { - public: - // Constructor - explicit Dict (PyObject *pyob, bool owned=false): Mapping (pyob, owned) - { - validate(); - } - Dict (const Object& ob): Mapping(ob) - { - validate(); - } - // Creation - Dict () - { - set(PyDict_New (), true); - validate(); - } - // Assignment acquires new ownership of pointer - - Dict& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Dict& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set(rhsp); - return *this; - } - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && Py::_Dict_Check (pyob); - } - }; - - class Callable: public Object - { - public: - // Constructor - explicit Callable (): Object() {} - explicit Callable (PyObject *pyob, bool owned = false): Object (pyob, owned) - { - validate(); - } - - Callable (const Object& ob): Object(ob) - { - validate(); - } - - // Assignment acquires new ownership of pointer - - Callable& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Callable& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set (rhsp); - return *this; - } - - // Membership - virtual bool accepts (PyObject *pyob) const - { - return pyob && PyCallable_Check (pyob); - } - - // Call - Object apply(const Tuple& args) const - { - return asObject(PyObject_CallObject(ptr(), args.ptr())); - } - - // Call with keywords - Object apply(const Tuple& args, const Dict& kw) const - { - return asObject( PyEval_CallObjectWithKeywords( ptr(), args.ptr(), kw.ptr() ) ); - } - - Object apply(PyObject* pargs = 0) const - { - return apply (Tuple(pargs)); - } - }; - - class Module: public Object - { - public: - explicit Module (PyObject* pyob, bool owned = false): Object (pyob, owned) - { - validate(); - } - - // Construct from module name - explicit Module (const std::string&s): Object() - { - PyObject *m = PyImport_AddModule( const_cast(s.c_str()) ); - set( m, false ); - validate (); - } - - // Copy constructor acquires new ownership of pointer - Module (const Module& ob): Object(*ob) - { - validate(); - } - - Module& operator= (const Object& rhs) - { - return (*this = *rhs); - } - - Module& operator= (PyObject* rhsp) - { - if(ptr() == rhsp) return *this; - set(rhsp); - return *this; - } - - Dict getDict() - { - return Dict(PyModule_GetDict(ptr())); - // Caution -- PyModule_GetDict returns borrowed reference! - } - }; - - // Call function helper - inline Object Object::callMemberFunction( const std::string &function_name ) const - { - Callable target( getAttr( function_name ) ); - Tuple args( 0 ); - return target.apply( args ); - } - - inline Object Object::callMemberFunction( const std::string &function_name, const Tuple &args ) const - { - Callable target( getAttr( function_name ) ); - return target.apply( args ); - } - - inline Object Object::callMemberFunction( const std::string &function_name, const Tuple &args, const Dict &kw ) const - { - Callable target( getAttr( function_name ) ); - return target.apply( args, kw ); - } - - // Numeric interface - inline Object operator+ (const Object& a) - { - return asObject(PyNumber_Positive(*a)); - } - inline Object operator- (const Object& a) - { - return asObject(PyNumber_Negative(*a)); - } - - inline Object abs(const Object& a) - { - return asObject(PyNumber_Absolute(*a)); - } - - inline std::pair coerce(const Object& a, const Object& b) - { - PyObject *p1, *p2; - p1 = *a; - p2 = *b; - if(PyNumber_Coerce(&p1,&p2) == -1) - { - throw Exception(); - } - return std::pair(asObject(p1), asObject(p2)); - } - - inline Object operator+ (const Object& a, const Object& b) - { - return asObject(PyNumber_Add(*a, *b)); - } - inline Object operator+ (const Object& a, int j) - { - return asObject(PyNumber_Add(*a, *Int(j))); - } - inline Object operator+ (const Object& a, double v) - { - return asObject(PyNumber_Add(*a, *Float(v))); - } - inline Object operator+ (int j, const Object& b) - { - return asObject(PyNumber_Add(*Int(j), *b)); - } - inline Object operator+ (double v, const Object& b) - { - return asObject(PyNumber_Add(*Float(v), *b)); - } - - inline Object operator- (const Object& a, const Object& b) - { - return asObject(PyNumber_Subtract(*a, *b)); - } - inline Object operator- (const Object& a, int j) - { - return asObject(PyNumber_Subtract(*a, *Int(j))); - } - inline Object operator- (const Object& a, double v) - { - return asObject(PyNumber_Subtract(*a, *Float(v))); - } - inline Object operator- (int j, const Object& b) - { - return asObject(PyNumber_Subtract(*Int(j), *b)); - } - inline Object operator- (double v, const Object& b) - { - return asObject(PyNumber_Subtract(*Float(v), *b)); - } - - inline Object operator* (const Object& a, const Object& b) - { - return asObject(PyNumber_Multiply(*a, *b)); - } - inline Object operator* (const Object& a, int j) - { - return asObject(PyNumber_Multiply(*a, *Int(j))); - } - inline Object operator* (const Object& a, double v) - { - return asObject(PyNumber_Multiply(*a, *Float(v))); - } - inline Object operator* (int j, const Object& b) - { - return asObject(PyNumber_Multiply(*Int(j), *b)); - } - inline Object operator* (double v, const Object& b) - { - return asObject(PyNumber_Multiply(*Float(v), *b)); - } - - inline Object operator/ (const Object& a, const Object& b) - { - return asObject(PyNumber_Divide(*a, *b)); - } - inline Object operator/ (const Object& a, int j) - { - return asObject(PyNumber_Divide(*a, *Int(j))); - } - inline Object operator/ (const Object& a, double v) - { - return asObject(PyNumber_Divide(*a, *Float(v))); - } - inline Object operator/ (int j, const Object& b) - { - return asObject(PyNumber_Divide(*Int(j), *b)); - } - inline Object operator/ (double v, const Object& b) - { - return asObject(PyNumber_Divide(*Float(v), *b)); - } - - inline Object operator% (const Object& a, const Object& b) - { - return asObject(PyNumber_Remainder(*a, *b)); - } - inline Object operator% (const Object& a, int j) - { - return asObject(PyNumber_Remainder(*a, *Int(j))); - } - inline Object operator% (const Object& a, double v) - { - return asObject(PyNumber_Remainder(*a, *Float(v))); - } - inline Object operator% (int j, const Object& b) - { - return asObject(PyNumber_Remainder(*Int(j), *b)); - } - inline Object operator% (double v, const Object& b) - { - return asObject(PyNumber_Remainder(*Float(v), *b)); - } - - inline Object type(const Exception&) // return the type of the error - { - PyObject *ptype, *pvalue, *ptrace; - PyErr_Fetch(&ptype, &pvalue, &ptrace); - Object result; - if(ptype) result = ptype; - PyErr_Restore(ptype, pvalue, ptrace); - return result; - } - - inline Object value(const Exception&) // return the value of the error - { - PyObject *ptype, *pvalue, *ptrace; - PyErr_Fetch(&ptype, &pvalue, &ptrace); - Object result; - if(pvalue) result = pvalue; - PyErr_Restore(ptype, pvalue, ptrace); - return result; - } - - inline Object trace(const Exception&) // return the traceback of the error - { - PyObject *ptype, *pvalue, *ptrace; - PyErr_Fetch(&ptype, &pvalue, &ptrace); - Object result; - if(ptrace) result = ptrace; - PyErr_Restore(ptype, pvalue, ptrace); - return result; - } - -template -String seqref::str () const -{ - return the_item.str(); -} - -template -String seqref::repr () const -{ - return the_item.repr(); -} - -} // namespace Py -#endif // __CXX_Objects__h diff --git a/extern/CXX/Python2/PythonType.hxx b/extern/CXX/Python2/PythonType.hxx deleted file mode 100644 index fc45a4bc6c5e..000000000000 --- a/extern/CXX/Python2/PythonType.hxx +++ /dev/null @@ -1,115 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_PythonType__h -#define __CXX_PythonType__h - -namespace Py -{ - class PythonType - { - public: - // if you define one sequence method you must define - // all of them except the assigns - - PythonType( size_t base_size, int itemsize, const char *default_name ); - virtual ~PythonType(); - - const char *getName() const; - const char *getDoc() const; - - PyTypeObject *type_object() const; - PythonType &name( const char *nam ); - PythonType &doc( const char *d ); - - PythonType &supportClass( void ); - PythonType &dealloc( void (*f)( PyObject* ) ); -#if defined( PYCXX_PYTHON_2TO3 ) - PythonType &supportPrint( void ); -#endif - PythonType &supportGetattr( void ); - PythonType &supportSetattr( void ); - PythonType &supportGetattro( void ); - PythonType &supportSetattro( void ); -#if defined( PYCXX_PYTHON_2TO3 ) - PythonType &supportCompare( void ); -#endif - PythonType &supportRichCompare( void ); - PythonType &supportRepr( void ); - PythonType &supportStr( void ); - PythonType &supportHash( void ); - PythonType &supportCall( void ); - PythonType &supportIter( void ); - - PythonType &supportSequenceType( void ); - PythonType &supportMappingType( void ); - PythonType &supportNumberType( void ); - PythonType &supportBufferType( void ); - - PythonType &set_tp_dealloc( void (*tp_dealloc)( PyObject * ) ); - PythonType &set_tp_init( int (*tp_init)( PyObject *self, PyObject *args, PyObject *kwds ) ); - PythonType &set_tp_new( PyObject *(*tp_new)( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) ); - PythonType &set_methods( PyMethodDef *methods ); - - // call once all support functions have been called to ready the type - bool readyType(); - - protected: - void init_sequence(); - void init_mapping(); - void init_number(); - void init_buffer(); - - PyTypeObject *table; - PySequenceMethods *sequence_table; - PyMappingMethods *mapping_table; - PyNumberMethods *number_table; - PyBufferProcs *buffer_table; - - private: - // - // prevent the compiler generating these unwanted functions - // - PythonType( const PythonType &tb ); // unimplemented - void operator=( const PythonType &t ); // unimplemented - - }; - -} // Namespace Py - -// End of __CXX_PythonType__h -#endif diff --git a/extern/CXX/Python2/cxx_extensions.cxx b/extern/CXX/Python2/cxx_extensions.cxx deleted file mode 100644 index 611a335d1164..000000000000 --- a/extern/CXX/Python2/cxx_extensions.cxx +++ /dev/null @@ -1,1841 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/Extensions.hxx" -#include "CXX/Exception.hxx" -#include - -#ifdef PYCXX_DEBUG -// -// Functions useful when debugging PyCXX -// -void bpt( void ) -{ -} - -void printRefCount( PyObject *obj ) -{ - std::cout << "RefCount of 0x" << std::hex << reinterpret_cast< unsigned int >( obj ) << std::dec << " is " << Py_REFCNT( obj ) << std::endl; -} -#endif - -namespace Py -{ -#ifdef PYCXX_PYTHON_2TO3 -std::string String::as_std_string( const char *encoding, const char *error ) const -{ - if( isUnicode() ) - { - Bytes encoded( encode( encoding, error ) ); - return encoded.as_std_string(); - } - else - { - return std::string( PyString_AsString( ptr() ), static_cast( PyString_Size( ptr() ) ) ); - } -} - -Bytes String::encode( const char *encoding, const char *error ) const -{ - if( isUnicode() ) - { - return Bytes( PyUnicode_AsEncodedString( ptr(), encoding, error ) ); - } - else - { - return Bytes( PyString_AsEncodedObject( ptr(), encoding, error ) ); - } -} - -#else -std::string String::as_std_string( const char *encoding, const char *error ) const -{ - if( isUnicode() ) - { - String encoded( encode( encoding, error ) ); - return encoded.as_std_string(); - } - else - { - return std::string( PyString_AsString( ptr() ), static_cast( PyString_Size( ptr() ) ) ); - } -} -#endif - -void Object::validate() -{ - // release pointer if not the right type - if( !accepts( p ) ) - { -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - std::string s( "PyCXX: Error creating object of type " ); - s += (typeid( *this )).name(); - - if( p != NULL ) - { - String from_repr = repr(); - s += " from "; - s += from_repr.as_std_string( "utf-8" ); - } - else - { - s += " from (nil)"; - } -#endif - release(); - if( PyErr_Occurred() ) - { // Error message already set - throw Exception(); - } - // Better error message if RTTI available -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - throw TypeError( s ); -#else - throw TypeError( "PyCXX: type error." ); -#endif - } -} - -//================================================================================ -// -// Implementation of MethodTable -// -//================================================================================ -PyMethodDef MethodTable::method( const char *method_name, PyCFunction f, int flags, const char *doc ) -{ - PyMethodDef m; - m.ml_name = const_cast( method_name ); - m.ml_meth = f; - m.ml_flags = flags; - m.ml_doc = const_cast( doc ); - return m; -} - -MethodTable::MethodTable() -{ - t.push_back( method( 0, 0, 0, 0 ) ); - mt = NULL; -} - -MethodTable::~MethodTable() -{ - delete [] mt; -} - -void MethodTable::add( const char *method_name, PyCFunction f, const char *doc, int flag ) -{ - if( !mt ) - { - t.insert( t.end()-1, method( method_name, f, flag, doc ) ); - } - else - { - throw RuntimeError( "Too late to add a module method!" ); - } -} - -PyMethodDef *MethodTable::table() -{ - if( !mt ) - { - Py_ssize_t t1size = t.size(); - mt = new PyMethodDef[ t1size ]; - int j = 0; - for( std::vector::iterator i = t.begin(); i != t.end(); i++ ) - { - mt[ j++ ] = *i; - } - } - return mt; -} - -//================================================================================ -// -// Implementation of ExtensionModule -// -//================================================================================ -ExtensionModuleBase::ExtensionModuleBase( const char *name ) -: m_module_name( name ) -, m_full_module_name( __Py_PackageContext() != NULL ? std::string( __Py_PackageContext() ) : m_module_name ) -, m_method_table() -{} - -ExtensionModuleBase::~ExtensionModuleBase() -{} - -const std::string &ExtensionModuleBase::name() const -{ - return m_module_name; -} - -const std::string &ExtensionModuleBase::fullName() const -{ - return m_full_module_name; -} - -class ExtensionModuleBasePtr : public PythonExtension -{ -public: - ExtensionModuleBasePtr( ExtensionModuleBase *_module ) - : module( _module ) - {} - - virtual ~ExtensionModuleBasePtr() - {} - - ExtensionModuleBase *module; -}; - -void ExtensionModuleBase::initialize( const char *module_doc ) -{ - PyObject *module_ptr = new ExtensionModuleBasePtr( this ); - Py_InitModule4 - ( - const_cast( m_module_name.c_str() ), // name - m_method_table.table(), // methods - const_cast( module_doc ), // docs - module_ptr, // pass to functions as "self" - PYTHON_API_VERSION // API version - ); -} - -Py::Module ExtensionModuleBase::module( void ) const -{ - return Module( m_full_module_name ); -} - -Py::Dict ExtensionModuleBase::moduleDictionary( void ) const -{ - return module().getDict(); -} - -//================================================================================ -// -// Implementation of PythonType -// -//================================================================================ -extern "C" -{ - static void standard_dealloc( PyObject *p ); - // - // All the following functions redirect the call from Python - // onto the matching virtual function in PythonExtensionBase - // -#if defined( PYCXX_PYTHON_2TO3 ) - static int print_handler( PyObject *, FILE *, int ); -#endif - static PyObject *getattr_handler( PyObject *, char * ); - static int setattr_handler( PyObject *, char *, PyObject * ); - static PyObject *getattro_handler( PyObject *, PyObject * ); - static int setattro_handler( PyObject *, PyObject *, PyObject * ); -#if defined( PYCXX_PYTHON_2TO3 ) - static int compare_handler( PyObject *, PyObject * ); -#endif - static PyObject *rich_compare_handler( PyObject *, PyObject *, int ); - static PyObject *repr_handler( PyObject * ); - static PyObject *str_handler( PyObject * ); - static long hash_handler( PyObject * ); - static PyObject *call_handler( PyObject *, PyObject *, PyObject * ); - static PyObject *iter_handler( PyObject * ); - static PyObject *iternext_handler( PyObject * ); - - // Sequence methods - static Py_ssize_t sequence_length_handler( PyObject * ); - static PyObject *sequence_concat_handler( PyObject *,PyObject * ); - static PyObject *sequence_repeat_handler( PyObject *, Py_ssize_t ); - static PyObject *sequence_item_handler( PyObject *, Py_ssize_t ); - static PyObject *sequence_slice_handler( PyObject *, Py_ssize_t, Py_ssize_t ); - static int sequence_ass_item_handler( PyObject *, Py_ssize_t, PyObject * ); - static int sequence_ass_slice_handler( PyObject *, Py_ssize_t, Py_ssize_t, PyObject * ); - - // Mapping - static Py_ssize_t mapping_length_handler( PyObject * ); - static PyObject *mapping_subscript_handler( PyObject *, PyObject * ); - static int mapping_ass_subscript_handler( PyObject *, PyObject *, PyObject * ); - - // Numeric methods - static int number_nonzero_handler( PyObject * ); - static PyObject *number_negative_handler( PyObject * ); - static PyObject *number_positive_handler( PyObject * ); - static PyObject *number_absolute_handler( PyObject * ); - static PyObject *number_invert_handler( PyObject * ); - static PyObject *number_int_handler( PyObject * ); - static PyObject *number_float_handler( PyObject * ); - static PyObject *number_long_handler( PyObject * ); - static PyObject *number_oct_handler( PyObject * ); - static PyObject *number_hex_handler( PyObject * ); - static PyObject *number_add_handler( PyObject *, PyObject * ); - static PyObject *number_subtract_handler( PyObject *, PyObject * ); - static PyObject *number_multiply_handler( PyObject *, PyObject * ); - static PyObject *number_divide_handler( PyObject *, PyObject * ); - static PyObject *number_remainder_handler( PyObject *, PyObject * ); - static PyObject *number_divmod_handler( PyObject *, PyObject * ); - static PyObject *number_lshift_handler( PyObject *, PyObject * ); - static PyObject *number_rshift_handler( PyObject *, PyObject * ); - static PyObject *number_and_handler( PyObject *, PyObject * ); - static PyObject *number_xor_handler( PyObject *, PyObject * ); - static PyObject *number_or_handler( PyObject *, PyObject * ); - static PyObject *number_power_handler( PyObject *, PyObject *, PyObject * ); - - // Buffer - static Py_ssize_t buffer_getreadbuffer_handler( PyObject *, Py_ssize_t, void ** ); - static Py_ssize_t buffer_getwritebuffer_handler( PyObject *, Py_ssize_t, void ** ); - static Py_ssize_t buffer_getsegcount_handler( PyObject *, Py_ssize_t * ); -} - -extern "C" void standard_dealloc( PyObject *p ) -{ - PyMem_DEL( p ); -} - -bool PythonType::readyType() -{ - return PyType_Ready( table ) >= 0; -} - -PythonType &PythonType::supportSequenceType() -{ - if( !sequence_table ) - { - sequence_table = new PySequenceMethods; - memset( sequence_table, 0, sizeof( PySequenceMethods ) ); // ensure new fields are 0 - table->tp_as_sequence = sequence_table; - sequence_table->sq_length = sequence_length_handler; - sequence_table->sq_concat = sequence_concat_handler; - sequence_table->sq_repeat = sequence_repeat_handler; - sequence_table->sq_item = sequence_item_handler; - sequence_table->sq_slice = sequence_slice_handler; - sequence_table->sq_ass_item = sequence_ass_item_handler; // BAS setup seperately? - sequence_table->sq_ass_slice = sequence_ass_slice_handler; // BAS setup seperately? - } - return *this; -} - -PythonType &PythonType::supportMappingType() -{ - if( !mapping_table ) - { - mapping_table = new PyMappingMethods; - memset( mapping_table, 0, sizeof( PyMappingMethods ) ); // ensure new fields are 0 - table->tp_as_mapping = mapping_table; - mapping_table->mp_length = mapping_length_handler; - mapping_table->mp_subscript = mapping_subscript_handler; - mapping_table->mp_ass_subscript = mapping_ass_subscript_handler; // BAS setup seperately? - } - return *this; -} - -PythonType &PythonType::supportNumberType() -{ - if( !number_table ) - { - number_table = new PyNumberMethods; - memset( number_table, 0, sizeof( PyNumberMethods ) ); // ensure new fields are 0 - table->tp_as_number = number_table; - number_table->nb_add = number_add_handler; - number_table->nb_subtract = number_subtract_handler; - number_table->nb_multiply = number_multiply_handler; - number_table->nb_divide = number_divide_handler; - number_table->nb_remainder = number_remainder_handler; - number_table->nb_divmod = number_divmod_handler; - number_table->nb_power = number_power_handler; - number_table->nb_negative = number_negative_handler; - number_table->nb_positive = number_positive_handler; - number_table->nb_absolute = number_absolute_handler; - number_table->nb_nonzero = number_nonzero_handler; - number_table->nb_invert = number_invert_handler; - number_table->nb_lshift = number_lshift_handler; - number_table->nb_rshift = number_rshift_handler; - number_table->nb_and = number_and_handler; - number_table->nb_xor = number_xor_handler; - number_table->nb_or = number_or_handler; - number_table->nb_coerce = 0; - number_table->nb_int = number_int_handler; - number_table->nb_long = number_long_handler; - number_table->nb_float = number_float_handler; - number_table->nb_oct = number_oct_handler; - number_table->nb_hex = number_hex_handler; - } - return *this; -} - -PythonType &PythonType::supportBufferType() -{ - if( !buffer_table ) - { - buffer_table = new PyBufferProcs; - memset( buffer_table, 0, sizeof( PyBufferProcs ) ); // ensure new fields are 0 - table->tp_as_buffer = buffer_table; - buffer_table->bf_getreadbuffer = buffer_getreadbuffer_handler; - buffer_table->bf_getwritebuffer = buffer_getwritebuffer_handler; - buffer_table->bf_getsegcount = buffer_getsegcount_handler; - } - return *this; -} - -// if you define one sequence method you must define -// all of them except the assigns - -PythonType::PythonType( size_t basic_size, int itemsize, const char *default_name ) -: table( new PyTypeObject ) -, sequence_table( NULL ) -, mapping_table( NULL ) -, number_table( NULL ) -, buffer_table( NULL ) -{ - // PyTypeObject is defined in /Include/object.h - - memset( table, 0, sizeof( PyTypeObject ) ); // ensure new fields are 0 - *reinterpret_cast( table ) = py_object_initializer; - table->ob_type = _Type_Type(); - table->ob_size = 0; - - table->tp_name = const_cast( default_name ); - table->tp_basicsize = basic_size; - table->tp_itemsize = itemsize; - - // Methods to implement standard operations - table->tp_dealloc = (destructor)standard_dealloc; - table->tp_print = 0; - table->tp_getattr = 0; - table->tp_setattr = 0; - table->tp_compare = 0; - table->tp_repr = 0; - - // Method suites for standard classes - table->tp_as_number = 0; - table->tp_as_sequence = 0; - table->tp_as_mapping = 0; - - // More standard operations (here for binary compatibility) - table->tp_hash = 0; - table->tp_call = 0; - table->tp_str = 0; - table->tp_getattro = 0; - table->tp_setattro = 0; - - // Functions to access object as input/output buffer - table->tp_as_buffer = 0; - - // Flags to define presence of optional/expanded features - table->tp_flags = Py_TPFLAGS_DEFAULT; - - // Documentation string - table->tp_doc = 0; - -#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 0) - table->tp_traverse = 0L; - - // delete references to contained objects - table->tp_clear = 0L; -#else - table->tp_xxx5 = 0L; - table->tp_xxx6 = 0L; -#endif -#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 1) - // first defined in 2.1 - table->tp_richcompare = 0L; - // weak reference enabler - table->tp_weaklistoffset = 0L; -#else - table->tp_xxx7 = 0L; - table->tp_xxx8 = 0L; -#endif -#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 2) - // first defined in 2.3 - // Iterators - table->tp_iter = 0L; - table->tp_iternext = 0L; -#endif -#ifdef COUNT_ALLOCS - table->tp_alloc = 0; - table->tp_free = 0; - table->tp_maxalloc = 0; - table->tp_next = 0; -#endif -} - -PythonType::~PythonType() -{ - delete table; - delete sequence_table; - delete mapping_table; - delete number_table; - delete buffer_table; -} - -PyTypeObject *PythonType::type_object() const -{ - return table; -} - -PythonType &PythonType::name( const char *nam ) -{ - table->tp_name = const_cast( nam ); - return *this; -} - -const char *PythonType::getName() const -{ - return table->tp_name; -} - -PythonType &PythonType::doc( const char *d ) -{ - table->tp_doc = const_cast( d ); - return *this; -} - -const char *PythonType::getDoc() const -{ - return table->tp_doc; -} - -PythonType &PythonType::set_tp_dealloc( void (*tp_dealloc)( PyObject *self ) ) -{ - table->tp_dealloc = tp_dealloc; - return *this; -} - -PythonType &PythonType::set_tp_init( int (*tp_init)( PyObject *self, PyObject *args, PyObject *kwds ) ) -{ - table->tp_init = tp_init; - return *this; -} - -PythonType &PythonType::set_tp_new( PyObject *(*tp_new)( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) ) -{ - table->tp_new = tp_new; - return *this; -} - -PythonType &PythonType::set_methods( PyMethodDef *methods ) -{ - table->tp_methods = methods; - return *this; -} - -PythonType &PythonType::supportClass() -{ - table->tp_flags |= Py_TPFLAGS_BASETYPE; - return *this; -} - -PythonType &PythonType::dealloc( void( *f )( PyObject * )) -{ - table->tp_dealloc = f; - return *this; -} - -#if defined( PYCXX_PYTHON_2TO3 ) -PythonType &PythonType::supportPrint() -{ - table->tp_print = print_handler; - return *this; -} -#endif - -PythonType &PythonType::supportGetattr() -{ - table->tp_getattr = getattr_handler; - return *this; -} - -PythonType &PythonType::supportSetattr() -{ - table->tp_setattr = setattr_handler; - return *this; -} - -PythonType &PythonType::supportGetattro() -{ - table->tp_getattro = getattro_handler; - return *this; -} - -PythonType &PythonType::supportSetattro() -{ - table->tp_setattro = setattro_handler; - return *this; -} - -#if defined( PYCXX_PYTHON_2TO3 ) -PythonType &PythonType::supportCompare() -{ - table->tp_compare = compare_handler; - return *this; -} -#endif - -#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 1) -PythonType &PythonType::supportRichCompare() -{ - table->tp_richcompare = rich_compare_handler; - return *this; -} -#endif - -PythonType &PythonType::supportRepr() -{ - table->tp_repr = repr_handler; - return *this; -} - -PythonType &PythonType::supportStr() -{ - table->tp_str = str_handler; - return *this; -} - -PythonType &PythonType::supportHash() -{ - table->tp_hash = hash_handler; - return *this; -} - -PythonType &PythonType::supportCall() -{ - table->tp_call = call_handler; - return *this; -} - -PythonType &PythonType::supportIter() -{ - table->tp_iter = iter_handler; - table->tp_iternext = iternext_handler; - return *this; -} - -//-------------------------------------------------------------------------------- -// -// Handlers -// -//-------------------------------------------------------------------------------- -PythonExtensionBase *getPythonExtensionBase( PyObject *self ) -{ - if( self->ob_type->tp_flags&Py_TPFLAGS_BASETYPE ) - { - PythonClassInstance *instance = reinterpret_cast( self ); - return instance->m_pycxx_object; - } - else - { - return static_cast( self ); - } -} - - -#if defined( PYCXX_PYTHON_2TO3 ) -extern "C" int print_handler( PyObject *self, FILE *fp, int flags ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->print( fp, flags ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} -#endif - -extern "C" PyObject *getattr_handler( PyObject *self, char *name ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->getattr( name ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" int setattr_handler( PyObject *self, char *name, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->setattr( name, Py::Object( value ) ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" PyObject *getattro_handler( PyObject *self, PyObject *name ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->getattro( Py::String( name ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" int setattro_handler( PyObject *self, PyObject *name, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->setattro( Py::String( name ), Py::Object( value ) ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -#if defined( PYCXX_PYTHON_2TO3 ) -extern "C" int compare_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->compare( Py::Object( other ) ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} -#endif - -#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 1) -extern "C" PyObject *rich_compare_handler( PyObject *self, PyObject *other, int op ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->rich_compare( Py::Object( other ), op ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} -#endif - -extern "C" PyObject *repr_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->repr() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *str_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->str() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" long hash_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->hash(); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" PyObject *call_handler( PyObject *self, PyObject *args, PyObject *kw ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - if( kw != NULL ) - return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) ); - else - return new_reference_to( p->call( Py::Object( args ), Py::Object() ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *iter_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->iter() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *iternext_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->iternext(); // might be a NULL ptr on end of iteration - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -// Sequence methods -extern "C" Py_ssize_t sequence_length_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->sequence_length(); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" PyObject *sequence_concat_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_concat( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *sequence_repeat_handler( PyObject *self, Py_ssize_t count ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_repeat( count ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *sequence_item_handler( PyObject *self, Py_ssize_t index ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_item( index ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *sequence_slice_handler( PyObject *self, Py_ssize_t first, Py_ssize_t last ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_slice( first, last ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" int sequence_ass_item_handler( PyObject *self, Py_ssize_t index, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->sequence_ass_item( index, Py::Object( value ) ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" int sequence_ass_slice_handler( PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->sequence_ass_slice( first, last, Py::Object( value ) ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -// Mapping -extern "C" Py_ssize_t mapping_length_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->mapping_length(); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" PyObject *mapping_subscript_handler( PyObject *self, PyObject *key ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->mapping_subscript( Py::Object( key ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" int mapping_ass_subscript_handler( PyObject *self, PyObject *key, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->mapping_ass_subscript( Py::Object( key ), Py::Object( value ) ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -// Number -extern "C" int number_nonzero_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->number_nonzero(); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" PyObject *number_negative_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_negative() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_positive_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_positive() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_absolute_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_absolute() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_invert_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_invert() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_int_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_int() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_float_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_float() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_long_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_long() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_oct_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_oct() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_hex_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_hex() ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_add_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_add( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_subtract_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_subtract( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_multiply_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_multiply( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_divide_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_divide( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_remainder_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_remainder( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_divmod_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_divmod( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_lshift_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_lshift( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_rshift_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_rshift( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_and_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_and( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_xor_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_xor( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_or_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_or( Py::Object( other ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_power_handler( PyObject *self, PyObject *x1, PyObject *x2 ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_power( Py::Object( x1 ), Py::Object( x2 ) ) ); - } - catch( Py::Exception &) - { - return NULL; // indicate error - } -} - -// Buffer -extern "C" Py_ssize_t buffer_getreadbuffer_handler( PyObject *self, Py_ssize_t index, void **pp ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->buffer_getreadbuffer( index, pp ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" Py_ssize_t buffer_getwritebuffer_handler( PyObject *self, Py_ssize_t index, void **pp ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->buffer_getwritebuffer( index, pp ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -extern "C" Py_ssize_t buffer_getsegcount_handler( PyObject *self, Py_ssize_t *count ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->buffer_getsegcount( count ); - } - catch( Py::Exception &) - { - return -1; // indicate error - } -} - -//================================================================================ -// -// Implementation of PythonExtensionBase -// -//================================================================================ -#define missing_method( method ) \ - throw RuntimeError( "Extension object missing implement of " #method ); - -PythonExtensionBase::PythonExtensionBase() -{ - ob_refcnt = 0; -} - -PythonExtensionBase::~PythonExtensionBase() -{ - assert( ob_refcnt == 0 ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name ) -{ - Py::TupleN args; - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1 ) -{ - Py::TupleN args( arg1 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2 ) -{ - Py::TupleN args( arg1, arg2 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3 ) -{ - Py::TupleN args( arg1, arg2, arg3 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7, const Py::Object &arg8 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7, const Py::Object &arg8, const Py::Object &arg9 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 ); - return self().callMemberFunction( fn_name, args ); -} - -void PythonExtensionBase::reinit( Tuple &args, Dict &kwds ) -{ - throw RuntimeError( "Must not call __init__ twice on this class" ); -} - -Py::Object PythonExtensionBase::genericGetAttro( const Py::String &name ) -{ - return asObject( PyObject_GenericGetAttr( selfPtr(), name.ptr() ) ); -} - -int PythonExtensionBase::genericSetAttro( const Py::String &name, const Py::Object &value ) -{ - return PyObject_GenericSetAttr( selfPtr(), name.ptr(), value.ptr() ); -} - -int PythonExtensionBase::print( FILE *, int ) -{ - missing_method( print ); - return -1; -} - -Py::Object PythonExtensionBase::getattr( const char * ) -{ - missing_method( getattr ); - return Py::None(); -} - -int PythonExtensionBase::setattr( const char *, const Py::Object &) -{ - missing_method( setattr ); - return -1; -} - -Py::Object PythonExtensionBase::getattro( const Py::String &name ) -{ - return genericGetAttro( name ); -} - -int PythonExtensionBase::setattro( const Py::String &name, const Py::Object &value ) -{ - return genericSetAttro( name, value ); -} - -int PythonExtensionBase::compare( const Py::Object &) -{ - missing_method( compare ); - return -1; -} - -#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 1) -Py::Object PythonExtensionBase::rich_compare( const Py::Object &, int op ) -{ - missing_method( rich_compare ); - return Py::None(); -} - -#endif -Py::Object PythonExtensionBase::repr() -{ - missing_method( repr ); - return Py::None(); -} - -Py::Object PythonExtensionBase::str() -{ - missing_method( str ); - return Py::None(); -} - -long PythonExtensionBase::hash() -{ - missing_method( hash ); - return -1; -} - -Py::Object PythonExtensionBase::call( const Py::Object &, const Py::Object &) -{ - missing_method( call ); - return Py::None(); -} - -Py::Object PythonExtensionBase::iter() -{ - missing_method( iter ); - return Py::None(); -} - -PyObject *PythonExtensionBase::iternext() -{ - missing_method( iternext ); - return NULL; -} - -// Sequence methods -int PythonExtensionBase::sequence_length() -{ - missing_method( sequence_length ); - return -1; -} - -Py::Object PythonExtensionBase::sequence_concat( const Py::Object &) -{ - missing_method( sequence_concat ); - return Py::None(); -} - -Py::Object PythonExtensionBase::sequence_repeat( Py_ssize_t ) -{ - missing_method( sequence_repeat ); - return Py::None(); -} - -Py::Object PythonExtensionBase::sequence_item( Py_ssize_t ) -{ - missing_method( sequence_item ); - return Py::None(); -} - -Py::Object PythonExtensionBase::sequence_slice( Py_ssize_t, Py_ssize_t ) -{ - missing_method( sequence_slice ); - return Py::None(); -} - -int PythonExtensionBase::sequence_ass_item( Py_ssize_t, const Py::Object &) -{ - missing_method( sequence_ass_item ); - return -1; -} - -int PythonExtensionBase::sequence_ass_slice( Py_ssize_t, Py_ssize_t, const Py::Object &) -{ - missing_method( sequence_ass_slice ); - return -1; -} - -// Mapping -int PythonExtensionBase::mapping_length() -{ - missing_method( mapping_length ); - return -1; -} - -Py::Object PythonExtensionBase::mapping_subscript( const Py::Object &) -{ - missing_method( mapping_subscript ); - return Py::None(); -} - -int PythonExtensionBase::mapping_ass_subscript( const Py::Object &, const Py::Object &) -{ - missing_method( mapping_ass_subscript ); - return -1; -} - -// Number -int PythonExtensionBase::number_nonzero() -{ - missing_method( number_nonzero ); - return -1; -} - -Py::Object PythonExtensionBase::number_negative() -{ - missing_method( number_negative ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_positive() -{ - missing_method( number_positive ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_absolute() -{ - missing_method( number_absolute ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_invert() -{ - missing_method( number_invert ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_int() -{ - missing_method( number_int ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_float() -{ - missing_method( number_float ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_long() -{ - missing_method( number_long ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_oct() -{ - missing_method( number_oct ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_hex() -{ - missing_method( number_hex ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_add( const Py::Object &) -{ - missing_method( number_add ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_subtract( const Py::Object &) -{ - missing_method( number_subtract ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_multiply( const Py::Object &) -{ - missing_method( number_multiply ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_divide( const Py::Object &) -{ - missing_method( number_divide ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_remainder( const Py::Object &) -{ - missing_method( number_remainder ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_divmod( const Py::Object &) -{ - missing_method( number_divmod ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_lshift( const Py::Object &) -{ - missing_method( number_lshift ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_rshift( const Py::Object &) -{ - missing_method( number_rshift ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_and( const Py::Object &) -{ - missing_method( number_and ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_xor( const Py::Object &) -{ - missing_method( number_xor ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_or( const Py::Object &) -{ - missing_method( number_or ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_power( const Py::Object &, const Py::Object &) -{ - missing_method( number_power ); - return Py::None(); -} - -// Buffer -Py_ssize_t PythonExtensionBase::buffer_getreadbuffer( Py_ssize_t, void** ) -{ - missing_method( buffer_getreadbuffer ); - return -1; -} - -Py_ssize_t PythonExtensionBase::buffer_getwritebuffer( Py_ssize_t, void** ) -{ - missing_method( buffer_getwritebuffer ); - return -1; -} - -Py_ssize_t PythonExtensionBase::buffer_getsegcount( Py_ssize_t* ) -{ - missing_method( buffer_getsegcount ); - return -1; -} - -//-------------------------------------------------------------------------------- -// -// Method call handlers for -// PythonExtensionBase -// ExtensionModuleBase -// -//-------------------------------------------------------------------------------- -extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ) -{ - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - void *self_as_void = PyCObject_AsVoidPtr( self_in_cobject ); - if( self_as_void == NULL ) - return NULL; - - ExtensionModuleBase *self = static_cast( self_as_void ); - - Tuple args( _args ); - - if( _keywords == NULL ) - { - Dict keywords; // pass an empty dict - - Object result - ( - self->invoke_method_keyword - ( - PyCObject_AsVoidPtr( self_and_name_tuple[1].ptr() ), - args, - keywords - ) - ); - - return new_reference_to( result.ptr() ); - } - else - { - Dict keywords( _keywords ); // make dict - - Object result - ( - self->invoke_method_keyword - ( - PyCObject_AsVoidPtr( self_and_name_tuple[1].ptr() ), - args, - keywords - ) - ); - - return new_reference_to( result.ptr() ); - } - } - catch( Exception & ) - { - return 0; - } -} - -extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ) -{ - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - void *self_as_void = PyCObject_AsVoidPtr( self_in_cobject ); - if( self_as_void == NULL ) - return NULL; - - ExtensionModuleBase *self = static_cast( self_as_void ); - Tuple args( _args ); - - Object result - ( - self->invoke_method_varargs - ( - PyCObject_AsVoidPtr( self_and_name_tuple[1].ptr() ), - args - ) - ); - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } -} - -extern "C" void do_not_dealloc( void * ) -{} - -//-------------------------------------------------------------------------------- -// -// ExtensionExceptionType -// -//-------------------------------------------------------------------------------- -ExtensionExceptionType::ExtensionExceptionType() -: Py::Object() -{ -} - -void ExtensionExceptionType::init( ExtensionModuleBase &module, const std::string& name ) -{ - std::string module_name( module.fullName() ); - module_name += "."; - module_name += name; - set( PyErr_NewException( const_cast( module_name.c_str() ), NULL, NULL ), true ); -} - -void ExtensionExceptionType::init( ExtensionModuleBase &module, const std::string& name, ExtensionExceptionType &parent) -{ - std::string module_name( module.fullName() ); - module_name += "."; - module_name += name; - set( PyErr_NewException( const_cast( module_name.c_str() ), parent.ptr(), NULL ), true ); -} - -ExtensionExceptionType::~ExtensionExceptionType() -{ -} - -Exception::Exception( ExtensionExceptionType &exception, const std::string& reason ) -{ - PyErr_SetString( exception.ptr(), reason.c_str() ); -} - -Exception::Exception( ExtensionExceptionType &exception, Object &reason ) -{ - PyErr_SetObject( exception.ptr(), reason.ptr() ); -} - -Exception::Exception( PyObject *exception, Object &reason ) -{ - PyErr_SetObject( exception, reason.ptr() ); -} - -} // end of namespace Py diff --git a/extern/CXX/Python2/cxxextensions.c b/extern/CXX/Python2/cxxextensions.c deleted file mode 100644 index edae3be6bce9..000000000000 --- a/extern/CXX/Python2/cxxextensions.c +++ /dev/null @@ -1,49 +0,0 @@ -/*---------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//---------------------------------------------------------------------------*/ - -#include "CXX/WrapPython.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -PyObject py_object_initializer = {PyObject_HEAD_INIT(0)}; - -#ifdef __cplusplus -} -#endif diff --git a/extern/CXX/Python2/cxxsupport.cxx b/extern/CXX/Python2/cxxsupport.cxx deleted file mode 100644 index 1dfba5a1908b..000000000000 --- a/extern/CXX/Python2/cxxsupport.cxx +++ /dev/null @@ -1,174 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#include "CXX/Objects.hxx" -namespace Py { - -Py_UNICODE unicode_null_string[1] = { 0 }; - -Type Object::type () const -{ - return Type (PyObject_Type (p), true); -} - -String Object::str () const -{ - return String (PyObject_Str (p), true); -} - -String Object::repr () const -{ - return String (PyObject_Repr (p), true); -} - -std::string Object::as_string() const -{ - return static_cast(str()); -} - -List Object::dir () const - { - return List (PyObject_Dir (p), true); - } - -bool Object::isType (const Type& t) const -{ - return type ().ptr() == t.ptr(); -} - -Char::operator String() const -{ - return String(ptr()); -} - -// TMM: non-member operaters for iterators - see above -// I've also made a bug fix in respect to the cxx code -// (dereffed the left.seq and right.seq comparison) -bool operator==(const Sequence::iterator& left, const Sequence::iterator& right) -{ - return left.eql( right ); -} - -bool operator!=(const Sequence::iterator& left, const Sequence::iterator& right) -{ - return left.neq( right ); -} - -bool operator< (const Sequence::iterator& left, const Sequence::iterator& right) -{ - return left.lss( right ); -} - -bool operator> (const Sequence::iterator& left, const Sequence::iterator& right) -{ - return left.gtr( right ); -} - -bool operator<=(const Sequence::iterator& left, const Sequence::iterator& right) -{ - return left.leq( right ); -} - -bool operator>=(const Sequence::iterator& left, const Sequence::iterator& right) -{ - return left.geq( right ); -} - -// now for const_iterator -bool operator==(const Sequence::const_iterator& left, const Sequence::const_iterator& right) -{ - return left.eql( right ); -} - -bool operator!=(const Sequence::const_iterator& left, const Sequence::const_iterator& right) -{ - return left.neq( right ); -} - -bool operator< (const Sequence::const_iterator& left, const Sequence::const_iterator& right) -{ - return left.lss( right ); -} - -bool operator> (const Sequence::const_iterator& left, const Sequence::const_iterator& right) -{ - return left.gtr( right ); -} - -bool operator<=(const Sequence::const_iterator& left, const Sequence::const_iterator& right) -{ - return left.leq( right ); -} - -bool operator>=(const Sequence::const_iterator& left, const Sequence::const_iterator& right) -{ - return left.geq( right ); -} - -// For mappings: -bool operator==(const Mapping::iterator& left, const Mapping::iterator& right) -{ - return left.eql( right ); -} - -bool operator!=(const Mapping::iterator& left, const Mapping::iterator& right) -{ - return left.neq( right ); -} - -// now for const_iterator -bool operator==(const Mapping::const_iterator& left, const Mapping::const_iterator& right) -{ - return left.eql( right ); -} - -bool operator!=(const Mapping::const_iterator& left, const Mapping::const_iterator& right) -{ - return left.neq( right ); -} - -// TMM: 31May'01 - Added the #ifndef so I can exclude iostreams. -#ifndef CXX_NO_IOSTREAMS -// output - -std::ostream& operator<< (std::ostream& os, const Object& ob) -{ - return (os << static_cast(ob.str())); -} -#endif - -} // Py diff --git a/extern/CXX/Python3/Config.hxx b/extern/CXX/Python3/Config.hxx deleted file mode 100644 index d74689944521..000000000000 --- a/extern/CXX/Python3/Config.hxx +++ /dev/null @@ -1,118 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __PyCXX_config_hh__ -#define __PyCXX_config_hh__ - -// -// Microsoft VC++ 6.0 has no traits -// -#if defined( _MSC_VER ) - -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 1 - -#elif defined( __GNUC__ ) -# if __GNUC__ >= 3 -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 1 -# else -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 0 -#endif - -// -// Assume all other compilers do -// -#else - -// Macros to deal with deficiencies in compilers -# define STANDARD_LIBRARY_HAS_ITERATOR_TRAITS 1 -#endif - -#if STANDARD_LIBRARY_HAS_ITERATOR_TRAITS -# define random_access_iterator_parent(itemtype) std::iterator -#else -# define random_access_iterator_parent(itemtype) std::random_access_iterator -#endif - -// -// Which C++ standard is in use? -// -#if defined( _MSC_VER ) -# if _MSC_VER <= 1200 -// MSVC++ 6.0 -# define PYCXX_ISO_CPP_LIB 0 -# define STR_STREAM -# define TEMPLATE_TYPENAME class -# else -# define PYCXX_ISO_CPP_LIB 1 -# define STR_STREAM -# define TEMPLATE_TYPENAME typename -# endif -#elif defined( __GNUC__ ) -# if __GNUC__ >= 3 -# define PYCXX_ISO_CPP_LIB 1 -# define STR_STREAM -# define TEMPLATE_TYPENAME typename -# else -# define PYCXX_ISO_CPP_LIB 0 -# define STR_STREAM -# define TEMPLATE_TYPENAME class -# endif -#endif - -#if PYCXX_ISO_CPP_LIB -# define STR_STREAM -# define OSTRSTREAM ostringstream -# define EXPLICIT_TYPENAME typename -# define EXPLICIT_CLASS class -# define TEMPLATE_TYPENAME typename -#else -# define STR_STREAM -# define OSTRSTREAM ostrstream -# define EXPLICIT_TYPENAME -# define EXPLICIT_CLASS -# define TEMPLATE_TYPENAME class -#endif - - -/* Need to fudge Py_hash_t types for python > 3.2 */ - -#if PY_VERSION_HEX < 0x030200A4 -typedef long Py_hash_t; -typedef unsigned long Py_uhash_t; -#endif - -#endif // __PyCXX_config_hh__ diff --git a/extern/CXX/Python3/CxxDebug.hxx b/extern/CXX/Python3/CxxDebug.hxx deleted file mode 100644 index b646ffdd9afa..000000000000 --- a/extern/CXX/Python3/CxxDebug.hxx +++ /dev/null @@ -1,17 +0,0 @@ -// -// CxxDebug.hxx -// -// Copyright (c) 2008 Barry A. Scott -// -#ifndef __CXX_Debug_hxx -#define __CXX_Debug_hxx - -// -// Functions useful when debugging PyCXX -// -#ifdef PYCXX_DEBUG -extern void bpt(); -extern void printRefCount( PyObject *obj ); -#endif - -#endif diff --git a/extern/CXX/Python3/Exception.hxx b/extern/CXX/Python3/Exception.hxx deleted file mode 100644 index 0bd052d5cc7d..000000000000 --- a/extern/CXX/Python3/Exception.hxx +++ /dev/null @@ -1,260 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_Exception_h -#define __CXX_Exception_h - -#include "CXX/WrapPython.h" -#include "CXX/Version.hxx" -#include "CXX/Python3/Config.hxx" -#include "CXX/Python3/CxxDebug.hxx" -#include "CXX/Python3/IndirectPythonInterface.hxx" - -#include -#include - -// This mimics the Python structure, in order to minimize confusion -namespace Py -{ - class ExtensionExceptionType; - - class Object; - - class Exception - { - public: - Exception( ExtensionExceptionType &exception, const std::string &reason ); - Exception( ExtensionExceptionType &exception, Object &reason ); - - explicit Exception () - {} - - Exception (const std::string &reason) - { - PyErr_SetString( Py::_Exc_RuntimeError(), reason.c_str() ); - } - - Exception( PyObject *exception, const std::string &reason ) - { - PyErr_SetString( exception, reason.c_str() ); - } - - Exception( PyObject *exception, Object &reason ); - - void clear() // clear the error - // technically but not philosophically const - { - PyErr_Clear(); - } - }; - - - // Abstract - class StandardError: public Exception - { - protected: - explicit StandardError() - {} - }; - - class LookupError: public StandardError - { - protected: - explicit LookupError() - {} - }; - - class ArithmeticError: public StandardError - { - protected: - explicit ArithmeticError() - {} - }; - - class EnvironmentError: public StandardError - { - protected: - explicit EnvironmentError() - {} - }; - - // Concrete - - class TypeError: public StandardError - { - public: - TypeError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_TypeError(),reason.c_str() ); - } - }; - - class IndexError: public LookupError - { - public: - IndexError (const std::string& reason) - : LookupError() - { - PyErr_SetString( Py::_Exc_IndexError(), reason.c_str() ); - } - }; - - class AttributeError: public StandardError - { - public: - AttributeError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_AttributeError(), reason.c_str() ); - } - }; - - class NameError: public StandardError - { - public: - NameError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_NameError(), reason.c_str() ); - } - }; - - class RuntimeError: public StandardError - { - public: - RuntimeError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_RuntimeError(), reason.c_str() ); - } - }; - - class NotImplementedError: public StandardError - { - public: - NotImplementedError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_NotImplementedError(), reason.c_str()); - } - }; - - class SystemError: public StandardError - { - public: - SystemError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_SystemError(),reason.c_str() ); - } - }; - - class KeyError: public LookupError - { - public: - KeyError (const std::string& reason) - : LookupError() - { - PyErr_SetString( Py::_Exc_KeyError(),reason.c_str() ); - } - }; - - - class ValueError: public StandardError - { - public: - ValueError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_ValueError(), reason.c_str() ); - } - }; - - class OverflowError: public ArithmeticError - { - public: - OverflowError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString( Py::_Exc_OverflowError(), reason.c_str() ); - } - }; - - class ZeroDivisionError: public ArithmeticError - { - public: - ZeroDivisionError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString( Py::_Exc_ZeroDivisionError(), reason.c_str() ); - } - }; - - class FloatingPointError: public ArithmeticError - { - public: - FloatingPointError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString( Py::_Exc_FloatingPointError(), reason.c_str() ); - } - }; - - class MemoryError: public StandardError - { - public: - MemoryError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_MemoryError(), reason.c_str() ); - } - }; - - class SystemExit: public StandardError - { - public: - SystemExit (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_SystemExit(),reason.c_str() ); - } - }; - -}// Py - -#endif diff --git a/extern/CXX/Python3/ExtensionModule.hxx b/extern/CXX/Python3/ExtensionModule.hxx deleted file mode 100644 index 75eb77568ae4..000000000000 --- a/extern/CXX/Python3/ExtensionModule.hxx +++ /dev/null @@ -1,204 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionModule__h -#define __CXX_ExtensionModule__h - -namespace Py -{ - class ExtensionModuleBase - { - public: - ExtensionModuleBase( const char *name ); - virtual ~ExtensionModuleBase(); - - Module module( void ) const; // only valid after initialize() has been called - Dict moduleDictionary( void ) const; // only valid after initialize() has been called - - virtual Object invoke_method_noargs( void *method_def ) = 0; - virtual Object invoke_method_keyword( void *method_def, const Tuple &_args, const Dict &_keywords ) = 0; - virtual Object invoke_method_varargs( void *method_def, const Tuple &_args ) = 0; - - const std::string &name() const; - const std::string &fullName() const; - - // what is returned from PyInit_ function - Object moduleObject( void ) const; - - protected: - // Initialize the module - void initialize( const char *module_doc ); - - const std::string m_module_name; - const std::string m_full_module_name; - MethodTable m_method_table; - PyModuleDef m_module_def; - PyObject *m_module; - - private: - // - // prevent the compiler generating these unwanted functions - // - ExtensionModuleBase( const ExtensionModuleBase & ); //unimplemented - void operator=( const ExtensionModuleBase & ); //unimplemented - }; - - // Note: Python calls noargs as varargs buts args==NULL - extern "C" PyObject *method_noargs_call_handler( PyObject *_self_and_name_tuple, PyObject * ); - extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ); - extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ); - - template - class ExtensionModule : public ExtensionModuleBase - { - public: - ExtensionModule( const char *name ) - : ExtensionModuleBase( name ) - {} - virtual ~ExtensionModule() - {} - - protected: - typedef Object (T::*method_noargs_function_t)(); - typedef Object (T::*method_varargs_function_t)( const Tuple &args ); - typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - typedef std::map *> method_map_t; - - static void add_noargs_method( const char *name, method_noargs_function_t function, const char *doc="" ) - { - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_noargs_call_handler, doc ); - } - - static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" ) - { - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_varargs_call_handler, doc ); - } - - static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" ) - { - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_keyword_call_handler, doc ); - } - - void initialize( const char *module_doc="" ) - { - ExtensionModuleBase::initialize( module_doc ); - Dict dict( moduleDictionary() ); - - // - // put each of the methods into the modules dictionary - // so that we get called back at the function in T. - // - method_map_t &mm = methods(); - EXPLICIT_TYPENAME method_map_t::const_iterator i = mm.begin(); - EXPLICIT_TYPENAME method_map_t::const_iterator i_end = mm.end(); - for ( ; i != i_end; ++i ) - { - MethodDefExt *method_def = (*i).second; - - static PyObject *self = PyCapsule_New( this, NULL, NULL ); - - Tuple args( 2 ); - args[0] = Object( self, true ); - args[1] = Object( PyCapsule_New( method_def, NULL, NULL ), true ); - - PyObject *func = PyCFunction_New - ( - &method_def->ext_meth_def, - new_reference_to( args ) - ); - - method_def->py_method = Object( func, true ); - - dict[ (*i).first ] = method_def->py_method; - } - } - - protected: // Tom Malcolmson reports that derived classes need access to these - static method_map_t &methods( void ) - { - static method_map_t *map_of_methods = NULL; - if( map_of_methods == NULL ) - map_of_methods = new method_map_t; - - return *map_of_methods; - } - - // this invoke function must be called from within a try catch block - virtual Object invoke_method_noargs( void *method_def ) - { - // cast up to the derived class, method_def and call - T *self = static_cast( this ); - MethodDefExt *meth_def = reinterpret_cast *>( method_def ); - - return (self->*meth_def->ext_noargs_function)(); - } - - // this invoke function must be called from within a try catch block - virtual Object invoke_method_varargs( void *method_def, const Tuple &args ) - { - // cast up to the derived class, method_def and call - T *self = static_cast( this ); - MethodDefExt *meth_def = reinterpret_cast *>( method_def ); - - return (self->*meth_def->ext_varargs_function)( args ); - } - - // this invoke function must be called from within a try catch block - virtual Object invoke_method_keyword( void *method_def, const Tuple &args, const Dict &keywords ) - { - // cast up to the derived class, method_def and call - T *self = static_cast( this ); - MethodDefExt *meth_def = reinterpret_cast *>( method_def ); - - return (self->*meth_def->ext_keyword_function)( args, keywords ); - } - - private: - // - // prevent the compiler generating these unwanted functions - // - ExtensionModule( const ExtensionModule & ); //unimplemented - void operator=( const ExtensionModule & ); //unimplemented - }; -} // Namespace Py - - -// End of __CXX_ExtensionModule__h -#endif diff --git a/extern/CXX/Python3/ExtensionOldType.hxx b/extern/CXX/Python3/ExtensionOldType.hxx deleted file mode 100644 index 355dcfb220bb..000000000000 --- a/extern/CXX/Python3/ExtensionOldType.hxx +++ /dev/null @@ -1,398 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionOldType__h -#define __CXX_ExtensionOldType__h - -namespace Py -{ - template class PythonExtension - : public PythonExtensionBase - { - public: - static PyTypeObject *type_object() - { - return behaviors().type_object(); - } - - static bool check( PyObject *p ) - { - // is p like me? - return p->ob_type == type_object(); - } - - static bool check( const Object &ob ) - { - return check( ob.ptr() ); - } - - // - // every object needs getattr implemented - // to support methods - // - virtual Object getattr( const char *name ) - { - return getattr_methods( name ); - } - - PyObject *selfPtr() - { - return this; - } - - Object self() - { - return asObject( this ); - } - - protected: - explicit PythonExtension() - : PythonExtensionBase() - { - PyObject_Init( this, type_object() ); - - // every object must support getattr - behaviors().supportGetattr(); - } - - virtual ~PythonExtension() - {} - - static PythonType &behaviors() - { - static PythonType* p; - if( p == NULL ) - { -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - const char *default_name =( typeid( T ) ).name(); -#else - const char *default_name = "unknown"; -#endif - p = new PythonType( sizeof( T ), 0, default_name ); - p->set_tp_dealloc( extension_object_deallocator ); - } - - return *p; - } - - typedef Object (T::*method_noargs_function_t)(); - typedef Object (T::*method_varargs_function_t)( const Tuple &args ); - typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - typedef std::map *> method_map_t; - - // support the default attributes, __name__, __doc__ and methods - virtual Object getattr_default( const char *_name ) - { - std::string name( _name ); - - if( name == "__name__" && type_object()->tp_name != NULL ) - { - return Py::String( type_object()->tp_name ); - } - - if( name == "__doc__" && type_object()->tp_doc != NULL ) - { - return Py::String( type_object()->tp_doc ); - } - -// trying to fake out being a class for help() -// else if( name == "__bases__" ) -// { -// return Py::Tuple( 0 ); -// } -// else if( name == "__module__" ) -// { -// return Py::Nothing(); -// } -// else if( name == "__dict__" ) -// { -// return Py::Dict(); -// } - - return getattr_methods( _name ); - } - - // turn a name into function object - virtual Object getattr_methods( const char *_name ) - { - std::string name( _name ); - - method_map_t &mm = methods(); - - // see if name exists and get entry with method - EXPLICIT_TYPENAME method_map_t::const_iterator i = mm.find( name ); - if( i == mm.end() ) - { - if( name == "__methods__" ) - { - List methods; - - i = mm.begin(); - EXPLICIT_TYPENAME method_map_t::const_iterator i_end = mm.end(); - - for( ; i != i_end; ++i ) - methods.append( String( (*i).first ) ); - - return methods; - } - - throw AttributeError( name ); - } - - MethodDefExt *method_def = i->second; - - Tuple self( 2 ); - - self[0] = Object( this ); - self[1] = Object( PyCapsule_New( method_def, NULL, NULL ), true ); - - PyObject *func = PyCFunction_New( &method_def->ext_meth_def, self.ptr() ); - - return Object(func, true); - } - - // check that all methods added are unique - static void check_unique_method_name( const char *name ) - { - method_map_t &mm = methods(); - EXPLICIT_TYPENAME method_map_t::const_iterator i; - i = mm.find( name ); - if( i != mm.end() ) - throw AttributeError( name ); - } - - static void add_noargs_method( const char *name, method_noargs_function_t function, const char *doc="" ) - { - check_unique_method_name( name ); - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_noargs_call_handler, doc ); - } - - static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" ) - { - check_unique_method_name( name ); - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_varargs_call_handler, doc ); - } - - static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" ) - { - check_unique_method_name( name ); - method_map_t &mm = methods(); - mm[ std::string( name ) ] = new MethodDefExt( name, function, method_keyword_call_handler, doc ); - } - - private: - static method_map_t &methods( void ) - { - static method_map_t *map_of_methods = NULL; - if( map_of_methods == NULL ) - map_of_methods = new method_map_t; - - return *map_of_methods; - } - - // Note: Python calls noargs as varargs buts args==NULL - static PyObject *method_noargs_call_handler( PyObject *_self_and_name_tuple, PyObject * ) - { - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - T *self = static_cast( self_in_cobject ); - - MethodDefExt *meth_def = reinterpret_cast *>( - PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ) ); - - Object result; - - // Adding try & catch in case of STL debug-mode exceptions. - #ifdef _STLP_DEBUG - try - { - result = (self->*meth_def->ext_noargs_function)(); - } - catch( std::__stl_debug_exception ) - { - // throw cxx::RuntimeError( sErrMsg ); - throw RuntimeError( "Error message not set yet." ); - } - #else - result = (self->*meth_def->ext_noargs_function)(); - #endif // _STLP_DEBUG - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } - } - - static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ) - { - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - T *self = static_cast( self_in_cobject ); - MethodDefExt *meth_def = reinterpret_cast *>( - PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ) ); - - Tuple args( _args ); - - Object result; - - // Adding try & catch in case of STL debug-mode exceptions. - #ifdef _STLP_DEBUG - try - { - result = (self->*meth_def->ext_varargs_function)( args ); - } - catch( std::__stl_debug_exception ) - { - throw RuntimeError( "Error message not set yet." ); - } - #else - result = (self->*meth_def->ext_varargs_function)( args ); - #endif // _STLP_DEBUG - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } - } - - static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ) - { - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - T *self = static_cast( self_in_cobject ); - MethodDefExt *meth_def = reinterpret_cast *>( - PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ) ); - - Tuple args( _args ); - - // _keywords may be NULL so be careful about the way the dict is created - Dict keywords; - if( _keywords != NULL ) - keywords = Dict( _keywords ); - - Object result( ( self->*meth_def->ext_keyword_function )( args, keywords ) ); - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } - } - - static void extension_object_deallocator( PyObject* t ) - { - delete (T *)( t ); - } - - // - // prevent the compiler generating these unwanted functions - // - explicit PythonExtension( const PythonExtension &other ); - void operator=( const PythonExtension &rhs ); - }; - - // - // ExtensionObject is an Object that will accept only T's. - // - template - class ExtensionObject: public Object - { - public: - - explicit ExtensionObject( PyObject *pyob ) - : Object( pyob ) - { - validate(); - } - - ExtensionObject( const ExtensionObject &other ) - : Object( *other ) - { - validate(); - } - - ExtensionObject( const Object &other ) - : Object( *other ) - { - validate(); - } - - ExtensionObject &operator=( const Object &rhs ) - { - return( *this = *rhs ); - } - - ExtensionObject &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - virtual bool accepts( PyObject *pyob ) const - { - return( pyob && T::check( pyob ) ); - } - - // - // Obtain a pointer to the PythonExtension object - // - T *extensionObject( void ) - { - return static_cast( ptr() ); - } - }; -} // Namespace Py - -// End of __CXX_ExtensionOldType__h -#endif diff --git a/extern/CXX/Python3/ExtensionType.hxx b/extern/CXX/Python3/ExtensionType.hxx deleted file mode 100644 index df680dbdfe15..000000000000 --- a/extern/CXX/Python3/ExtensionType.hxx +++ /dev/null @@ -1,403 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionClass__h -#define __CXX_ExtensionClass__h - -#define PYCXX_NOARGS_METHOD_NAME( NAME ) _callNoArgsMethod__##NAME -#define PYCXX_VARARGS_METHOD_NAME( NAME ) _callVarArgsMethod__##NAME -#define PYCXX_KEYWORDS_METHOD_NAME( NAME ) _callKeywordsMethod__##NAME - -#define PYCXX_NOARGS_METHOD_DECL( CLS, NAME ) \ - static PyObject *PYCXX_NOARGS_METHOD_NAME( NAME )( PyObject *_self, PyObject *, PyObject * ) \ - { \ - try \ - { \ - Py::PythonClassInstance *self_python = reinterpret_cast< Py::PythonClassInstance * >( _self ); \ - CLS *self = reinterpret_cast< CLS * >( self_python->m_pycxx_object ); \ - Py::Object r( (self->NAME)() ); \ - return Py::new_reference_to( r.ptr() ); \ - } \ - catch( Py::Exception & ) \ - { \ - return 0; \ - } \ - } -#define PYCXX_VARARGS_METHOD_DECL( CLS, NAME ) \ - static PyObject *PYCXX_VARARGS_METHOD_NAME( NAME )( PyObject *_self, PyObject *_a, PyObject * ) \ - { \ - try \ - { \ - Py::PythonClassInstance *self_python = reinterpret_cast< Py::PythonClassInstance * >( _self ); \ - CLS *self = reinterpret_cast< CLS * >( self_python->m_pycxx_object ); \ - Py::Tuple a( _a ); \ - Py::Object r( (self->NAME)( a ) ); \ - return Py::new_reference_to( r.ptr() ); \ - } \ - catch( Py::Exception & ) \ - { \ - return 0; \ - } \ - } -#define PYCXX_KEYWORDS_METHOD_DECL( CLS, NAME ) \ - static PyObject *PYCXX_KEYWORDS_METHOD_NAME( NAME )( PyObject *_self, PyObject *_a, PyObject *_k ) \ - { \ - try \ - { \ - Py::PythonClassInstance *self_python = reinterpret_cast< Py::PythonClassInstance * >( _self ); \ - CLS *self = reinterpret_cast< CLS * >( self_python->m_pycxx_object ); \ - Py::Tuple a( _a ); \ - Py::Dict k; \ - if( _k != NULL ) \ - k = _k; \ - Py::Object r( (self->NAME)( a, k ) ); \ - return Py::new_reference_to( r.ptr() ); \ - } \ - catch( Py::Exception & ) \ - { \ - return 0; \ - } \ - } - -// need to support METH_STATIC and METH_CLASS - -#define PYCXX_ADD_NOARGS_METHOD( PYNAME, NAME, docs ) \ - add_method( #PYNAME, (PyCFunction)PYCXX_NOARGS_METHOD_NAME( NAME ), METH_NOARGS, docs ) -#define PYCXX_ADD_VARARGS_METHOD( PYNAME, NAME, docs ) \ - add_method( #PYNAME, (PyCFunction)PYCXX_VARARGS_METHOD_NAME( NAME ), METH_VARARGS, docs ) -#define PYCXX_ADD_KEYWORDS_METHOD( PYNAME, NAME, docs ) \ - add_method( #PYNAME, (PyCFunction)PYCXX_KEYWORDS_METHOD_NAME( NAME ), METH_VARARGS | METH_KEYWORDS, docs ) - -namespace Py -{ - extern PythonExtensionBase *getPythonExtensionBase( PyObject *self ); - struct PythonClassInstance - { - PyObject_HEAD - PythonExtensionBase *m_pycxx_object; - }; - - - class ExtensionClassMethodsTable - { - public: - ExtensionClassMethodsTable() - : m_methods_table( new PyMethodDef[ METHOD_TABLE_SIZE_INCREMENT ] ) - , m_methods_used( 0 ) - , m_methods_size( METHOD_TABLE_SIZE_INCREMENT ) - { - } - - ~ExtensionClassMethodsTable() - { - delete m_methods_table; - } - - // check that all methods added are unique - void check_unique_method_name( const char *_name ) - { - std::string name( _name ); - for( int i=0; iml_name = name; - p->ml_meth = function; - p->ml_flags = flags; - p->ml_doc = doc; - - m_methods_used++; - p++; - - // add the sentinel marking the table end - p->ml_name = NULL; - p->ml_meth = NULL; - p->ml_flags = 0; - p->ml_doc = NULL; - - return m_methods_table; - } - - private: - enum {METHOD_TABLE_SIZE_INCREMENT = 1}; - PyMethodDef *m_methods_table; - int m_methods_used; - int m_methods_size; - }; - - template class PythonClass - : public PythonExtensionBase - { - protected: - explicit PythonClass( PythonClassInstance *self, Tuple &args, Dict &kwds ) - : PythonExtensionBase() - , m_class_instance( self ) - { - } - - virtual ~PythonClass() - {} - - static ExtensionClassMethodsTable &methodTable() - { - static ExtensionClassMethodsTable *method_table; - if( method_table == NULL ) - method_table = new ExtensionClassMethodsTable; - return *method_table; - } - - static void add_method( const char *name, PyCFunction function, int flags, const char *doc=NULL ) - { - behaviors().set_methods( methodTable().add_method( name, function, flags, doc ) ); - } - - static PythonType &behaviors() - { - static PythonType *p; - if( p == NULL ) - { -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - const char *default_name = (typeid( T )).name(); -#else - const char *default_name = "unknown"; -#endif - p = new PythonType( sizeof( T ), 0, default_name ); - p->set_tp_new( extension_object_new ); - p->set_tp_init( extension_object_init ); - p->set_tp_dealloc( extension_object_deallocator ); - - // we are a class - p->supportClass(); - - // always support get and set attr - p->supportGetattro(); - p->supportSetattro(); - } - - return *p; - } - - static PyObject *extension_object_new( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) - { -#ifdef PYCXX_DEBUG - std::cout << "extension_object_new()" << std::endl; -#endif - PythonClassInstance *o = reinterpret_cast( subtype->tp_alloc( subtype, 0 ) ); - if( o == NULL ) - return NULL; - - o->m_pycxx_object = NULL; - - PyObject *self = reinterpret_cast( o ); -#ifdef PYCXX_DEBUG - std::cout << "extension_object_new() => self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << std::endl; -#endif - return self; - } - - static int extension_object_init( PyObject *_self, PyObject *args_, PyObject *kwds_ ) - { - try - { - Py::Tuple args( args_ ); - Py::Dict kwds; - if( kwds_ != NULL ) - kwds = kwds_; - - PythonClassInstance *self = reinterpret_cast( _self ); -#ifdef PYCXX_DEBUG - std::cout << "extension_object_init( self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << " )" << std::endl; - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - - if( self->m_pycxx_object == NULL ) - { - self->m_pycxx_object = new T( self, args, kwds ); -#ifdef PYCXX_DEBUG - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - } - else - { -#ifdef PYCXX_DEBUG - std::cout << " reinit - self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - self->m_pycxx_object->reinit( args, kwds ); - } - } - catch( Exception & ) - { - return -1; - } - return 0; - } - - static void extension_object_deallocator( PyObject *_self ) - { - PythonClassInstance *self = reinterpret_cast< PythonClassInstance * >( _self ); -#ifdef PYCXX_DEBUG - std::cout << "extension_object_deallocator( self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << " )" << std::endl; - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; -#endif - delete self->m_pycxx_object; - _self->ob_type->tp_free( _self ); - } - - public: - static PyTypeObject *type_object() - { - return behaviors().type_object(); - } - - static Object type() - { - return Object( reinterpret_cast( behaviors().type_object() ) ); - } - - static bool check( PyObject *p ) - { - // is p like me? - return p->ob_type == type_object(); - } - - static bool check( const Object &ob ) - { - return check( ob.ptr() ); - } - - virtual PyObject *selfPtr() - { - return reinterpret_cast( m_class_instance ); - } - - virtual Object self() - { - return Object( reinterpret_cast( m_class_instance ) ); - } - - protected: - private: - PythonClassInstance *m_class_instance; - - private: - // - // prevent the compiler generating these unwanted functions - // - explicit PythonClass( const PythonClass &other ); - void operator=( const PythonClass &rhs ); - }; - - // - // ExtensionObject is an Object that will accept only T's. - // - template - class PythonClassObject: public Object - { - public: - - explicit PythonClassObject( PyObject *pyob ) - : Object( pyob ) - { - validate(); - } - - PythonClassObject( const PythonClassObject &other ) - : Object( *other ) - { - validate(); - } - - PythonClassObject( const Object &other ) - : Object( *other ) - { - validate(); - } - - PythonClassObject &operator=( const Object &rhs ) - { - *this = *rhs; - return *this; - } - - PythonClassObject &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - virtual bool accepts( PyObject *pyob ) const - { - return( pyob && T::check( pyob ) ); - } - - // - // Obtain a pointer to the PythonExtension object - // - T *getCxxObject( void ) - { - return dynamic_cast< T * >( getPythonExtensionBase( ptr() ) ); - } - }; -} // Namespace Py - -// End of __CXX_ExtensionClass__h -#endif diff --git a/extern/CXX/Python3/ExtensionTypeBase.hxx b/extern/CXX/Python3/ExtensionTypeBase.hxx deleted file mode 100644 index 3936ccc28801..000000000000 --- a/extern/CXX/Python3/ExtensionTypeBase.hxx +++ /dev/null @@ -1,170 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_ExtensionTypeBase__h -#define __CXX_ExtensionTypeBase__h - -namespace Py -{ - // Class PythonExtension is what you inherit from to create - // a new Python extension type. You give your class itself - // as the template paramter. - - // There are two ways that extension objects can get destroyed. - // 1. Their reference count goes to zero - // 2. Someone does an explicit delete on a pointer. - // In(1) the problem is to get the destructor called - // We register a special deallocator in the Python type object - // (see behaviors()) to do this. - // In(2) there is no problem, the dtor gets called. - - // PythonExtension does not use the usual Python heap allocator, - // instead using new/delete. We do the setting of the type object - // and reference count, usually done by PyObject_New, in the - // base class ctor. - - // This special deallocator does a delete on the pointer. - - class PythonExtensionBase : public PyObject - { - public: - PythonExtensionBase(); - virtual ~PythonExtensionBase(); - - public: - // object - virtual void reinit( Tuple &args, Dict &kwds ); - - // object basics -#ifdef PYCXX_PYTHON_2TO3 - virtual int print( FILE *, int ); -#endif - virtual Object getattr( const char * ); - virtual int setattr( const char *, const Object & ); - virtual Object getattro( const String & ); - Object genericGetAttro( const String & ); - virtual int setattro( const String &, const Object & ); - int genericSetAttro( const String &, const Object & ); - virtual int compare( const Object & ); - virtual Object rich_compare( const Object &, int ); - virtual Object repr(); - virtual Object str(); - virtual Py_hash_t hash(); - virtual Object call( const Object &, const Object & ); - virtual Object iter(); - virtual PyObject *iternext(); - - // Sequence methods - virtual int sequence_length(); - virtual Object sequence_concat( const Object & ); - virtual Object sequence_repeat( Py_ssize_t ); - virtual Object sequence_item( Py_ssize_t ); - virtual int sequence_ass_item( Py_ssize_t, const Object & ); - - // Mapping - virtual int mapping_length(); - virtual Object mapping_subscript( const Object & ); - virtual int mapping_ass_subscript( const Object &, const Object & ); - - // Number - virtual Object number_negative(); - virtual Object number_positive(); - virtual Object number_absolute(); - virtual Object number_invert(); - virtual Object number_int(); - virtual Object number_float(); - virtual Object number_long(); - virtual Object number_add( const Object & ); - virtual Object number_subtract( const Object & ); - virtual Object number_multiply( const Object & ); - virtual Object number_remainder( const Object & ); - virtual Object number_divmod( const Object & ); - virtual Object number_lshift( const Object & ); - virtual Object number_rshift( const Object & ); - virtual Object number_and( const Object & ); - virtual Object number_xor( const Object & ); - virtual Object number_or( const Object & ); - virtual Object number_power( const Object &, const Object & ); - - // Buffer - virtual int buffer_get( Py_buffer *, int flags ); - virtual int buffer_release( Py_buffer *buf ); - - public: - // helper functions to call function fn_name with 0 to 9 args - Object callOnSelf( const std::string &fn_name ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6, - const Object &arg7 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6, - const Object &arg7, const Object &arg8 ); - Object callOnSelf( const std::string &fn_name, - const Object &arg1, const Object &arg2, const Object &arg3, - const Object &arg4, const Object &arg5, const Object &arg6, - const Object &arg7, const Object &arg8, const Object &arg9 ); - - public: - virtual PyObject *selfPtr() = 0; - virtual Object self() = 0; - - private: - void missing_method( void ); - static PyObject *method_call_handler( PyObject *self, PyObject *args ); - }; - -} // Namespace Py - -// End of __CXX_ExtensionTypeBase__h -#endif diff --git a/extern/CXX/Python3/Extensions.hxx b/extern/CXX/Python3/Extensions.hxx deleted file mode 100644 index 7533d97c7690..000000000000 --- a/extern/CXX/Python3/Extensions.hxx +++ /dev/null @@ -1,189 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_Extensions__h -#define __CXX_Extensions__h - - -#ifdef _MSC_VER -// disable warning C4786: symbol greater than 255 character, -// okay to ignore -#pragma warning( disable: 4786 ) -#endif - -#include "CXX/WrapPython.h" -#include "CXX/Version.hxx" -#include "CXX/Python3/Config.hxx" -#include "CXX/Python3/CxxDebug.hxx" -#include "CXX/Python3/Objects.hxx" - -extern "C" { extern PyObject py_object_initializer; } - -#include -#include - -// ---------------------------------------------------------------------- - -namespace Py -{ - class ExtensionModuleBase; - - // Make an Exception Type for use in raising custom exceptions - class ExtensionExceptionType : public Object - { - public: - ExtensionExceptionType(); - virtual ~ExtensionExceptionType(); - - // call init to create the type - void init( ExtensionModuleBase &module, const std::string &name, ExtensionExceptionType &parent ); - void init( ExtensionModuleBase &module, const std::string &name ); - }; - - class MethodTable - { - public: - MethodTable(); - virtual ~MethodTable(); - - void add( const char *method_name, PyCFunction f, const char *doc="", int flag=1 ); - PyMethodDef *table(); - - protected: - std::vector t; // accumulator of PyMethodDef's - PyMethodDef *mt; // Actual method table produced when full - - static PyMethodDef method( const char* method_name, PyCFunction f, int flags=1, const char* doc="" ); - - private: - // - // prevent the compiler generating these unwanted functions - // - MethodTable( const MethodTable &m ); //unimplemented - void operator=( const MethodTable &m ); //unimplemented - - }; // end class MethodTable - - // Note: Python calls noargs as varargs buts args==NULL - extern "C" typedef PyObject *(*method_noargs_call_handler_t)( PyObject *_self, PyObject * ); - extern "C" typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args ); - extern "C" typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict ); - - template - class MethodDefExt : public PyMethodDef - { - public: - typedef Object (T::*method_noargs_function_t)(); - typedef Object (T::*method_varargs_function_t)( const Tuple &args ); - typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - - // NOARGS - MethodDefExt - ( - const char *_name, - method_noargs_function_t _function, - method_noargs_call_handler_t _handler, - const char *_doc - ) - { - ext_meth_def.ml_name = const_cast( _name ); - ext_meth_def.ml_meth = reinterpret_cast( _handler ); - ext_meth_def.ml_flags = METH_NOARGS; - ext_meth_def.ml_doc = const_cast( _doc ); - - ext_noargs_function = _function; - ext_varargs_function = NULL; - ext_keyword_function = NULL; - } - - // VARARGS - MethodDefExt - ( - const char *_name, - method_varargs_function_t _function, - method_varargs_call_handler_t _handler, - const char *_doc - ) - { - ext_meth_def.ml_name = const_cast( _name ); - ext_meth_def.ml_meth = reinterpret_cast( _handler ); - ext_meth_def.ml_flags = METH_VARARGS; - ext_meth_def.ml_doc = const_cast( _doc ); - - ext_noargs_function = NULL; - ext_varargs_function = _function; - ext_keyword_function = NULL; - } - - // VARARGS + KEYWORD - MethodDefExt - ( - const char *_name, - method_keyword_function_t _function, - method_keyword_call_handler_t _handler, - const char *_doc - ) - { - ext_meth_def.ml_name = const_cast( _name ); - ext_meth_def.ml_meth = reinterpret_cast( _handler ); - ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS; - ext_meth_def.ml_doc = const_cast( _doc ); - - ext_noargs_function = NULL; - ext_varargs_function = NULL; - ext_keyword_function = _function; - } - - ~MethodDefExt() - {} - - PyMethodDef ext_meth_def; - method_noargs_function_t ext_noargs_function; - method_varargs_function_t ext_varargs_function; - method_keyword_function_t ext_keyword_function; - Object py_method; - }; -} // Namespace Py - -#include "CXX/Python3/ExtensionModule.hxx" -#include "CXX/Python3/PythonType.hxx" -#include "CXX/Python3/ExtensionTypeBase.hxx" -#include "CXX/Python3/ExtensionOldType.hxx" -#include "CXX/Python3/ExtensionType.hxx" - -// End of CXX_Extensions.h -#endif diff --git a/extern/CXX/Python3/IndirectPythonInterface.hxx b/extern/CXX/Python3/IndirectPythonInterface.hxx deleted file mode 100644 index cdae3ad35e75..000000000000 --- a/extern/CXX/Python3/IndirectPythonInterface.hxx +++ /dev/null @@ -1,183 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ -#define __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ - -#include "CXX/WrapPython.h" - -namespace Py -{ -bool InitialisePythonIndirectInterface(); - -// -// Wrap Exception variables as function calls -// -PyObject * _Exc_Exception(); -PyObject * _Exc_StandardError(); -PyObject * _Exc_ArithmeticError(); -PyObject * _Exc_LookupError(); - -PyObject * _Exc_AssertionError(); -PyObject * _Exc_AttributeError(); -PyObject * _Exc_EOFError(); -PyObject * _Exc_FloatingPointError(); -PyObject * _Exc_EnvironmentError(); -PyObject * _Exc_IOError(); -PyObject * _Exc_OSError(); -PyObject * _Exc_ImportError(); -PyObject * _Exc_IndexError(); -PyObject * _Exc_KeyError(); -PyObject * _Exc_KeyboardInterrupt(); -PyObject * _Exc_MemoryError(); -PyObject * _Exc_NameError(); -PyObject * _Exc_OverflowError(); -PyObject * _Exc_RuntimeError(); -PyObject * _Exc_NotImplementedError(); -PyObject * _Exc_SyntaxError(); -PyObject * _Exc_SystemError(); -PyObject * _Exc_SystemExit(); -PyObject * _Exc_TypeError(); -PyObject * _Exc_ValueError(); -PyObject * _Exc_ZeroDivisionError(); -#ifdef MS_WINDOWS -PyObject * _Exc_WindowsError(); -#endif - -PyObject * _Exc_IndentationError(); -PyObject * _Exc_TabError(); -PyObject * _Exc_UnboundLocalError(); -PyObject * _Exc_UnicodeError(); - -// -// Wrap Object variables as function calls -// -PyObject * _None(); - -PyObject * _False(); -PyObject * _True(); - -// -// Wrap Type variables as function calls -// -PyTypeObject * _List_Type(); -bool _List_Check( PyObject *o ); - -PyTypeObject * _Buffer_Type(); -bool _Buffer_Check( PyObject *op ); - -PyTypeObject * _Class_Type(); -bool _Class_Check( PyObject *op ); - -PyTypeObject * _Instance_Type(); -bool _Instance_Check( PyObject *op ); - -PyTypeObject * _Method_Type(); -bool _Method_Check( PyObject *op ); - -PyTypeObject * _Complex_Type(); -bool _Complex_Check( PyObject *op ); - -PyTypeObject * _Dict_Type(); -bool _Dict_Check( PyObject *op ); - -PyTypeObject * _File_Type(); -bool _File_Check( PyObject *op ); - -PyTypeObject * _Float_Type(); -bool _Float_Check( PyObject *op ); - -PyTypeObject * _Frame_Type(); -bool _Frame_Check( PyObject *op ); - -PyTypeObject * _Function_Type(); -bool _Function_Check( PyObject *op ); - -PyTypeObject * _Bool_Type(); -bool _Boolean_Check( PyObject *op ); - -PyTypeObject * _Int_Type(); -bool _Int_Check( PyObject *op ); - -PyTypeObject * _List_Type(); -bool _List_Check( PyObject *op ); - -PyTypeObject * _Long_Type(); -bool _Long_Check( PyObject *op ); - -PyTypeObject * _CFunction_Type(); -bool _CFunction_Check( PyObject *op ); - -PyTypeObject * _Module_Type(); -bool _Module_Check( PyObject *op ); - -PyTypeObject * _Type_Type(); -bool _Type_Check( PyObject *op ); - -PyTypeObject * _Range_Type(); -bool _Range_Check( PyObject *op ); - -PyTypeObject * _Slice_Type(); -bool _Slice_Check( PyObject *op ); - -PyTypeObject * _Unicode_Type(); -bool _Unicode_Check( PyObject *op ); - -PyTypeObject * _Bytes_Type(); -bool _Bytes_Check( PyObject *op ); - -PyTypeObject * _TraceBack_Type(); -bool _TraceBack_Check( PyObject *v ); - -PyTypeObject * _Tuple_Type(); -bool _Tuple_Check( PyObject *op ); - -int &_Py_DebugFlag(); -int &_Py_InteractiveFlag(); -int &_Py_OptimizeFlag(); -int &_Py_NoSiteFlag(); -int &_Py_TabcheckFlag(); -int &_Py_VerboseFlag(); -int &_Py_UnicodeFlag(); - -void _XINCREF( PyObject *op ); -void _XDECREF( PyObject *op ); - -char *__Py_PackageContext(); -}; - -#endif // __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ diff --git a/extern/CXX/Python3/Objects.hxx b/extern/CXX/Python3/Objects.hxx deleted file mode 100644 index 927618f0ba06..000000000000 --- a/extern/CXX/Python3/Objects.hxx +++ /dev/null @@ -1,3426 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_Objects__h -#define __CXX_Objects__h - -#include "CXX/WrapPython.h" -#include "CXX/Version.hxx" -#include "CXX/Python3/Config.hxx" -#include "CXX/Python3/CxxDebug.hxx" -#include "CXX/Python3/Exception.hxx" - -#include -#include STR_STREAM -#include -#include -#include -#include - -namespace Py -{ - typedef int sequence_index_type; // type of an index into a sequence - - // Forward declarations - class Object; - class Type; - template class SeqBase; - class Bytes; - class String; - class List; - template class MapBase; - class Tuple; - class Dict; - - //===========================================================================// - // class Object - // The purpose of this class is to serve as the most general kind of - // Python object, for the purpose of writing C++ extensions in Python - // Objects hold a PyObject* which they own. This pointer is always a - // valid pointer to a Python object. In children we must maintain this behavior. - // - // Instructions on how to make your own class MyType descended from Object: - // (0) Pick a base class, either Object or perhaps SeqBase or MapBase. - // This example assumes Object. - - // (1) Write a routine int MyType_Check( PyObject * ) modeled after PyInt_Check, - // PyFloat_Check, etc. - - // (2) Add method accepts: - // virtual bool accepts( PyObject *pyob ) const { - // return pyob && MyType_Check( pyob ); - // } - - // (3) Include the following constructor and copy constructor - // - /* - explicit MyType( PyObject *pyob ): Object( pyob ) - { - validate(); - } - - MyType( const Object &other ): Object( other.ptr() ) - { - validate(); - } - */ - - // Alernate version for the constructor to allow for construction from owned pointers: - /* - explicit MyType( PyObject *pyob ): Object( pyob ) - { - validate(); - } - */ - - // You may wish to add other constructors; see the classes below for examples. - // Each constructor must use "set" to set the pointer - // and end by validating the pointer you have created. - - //( 4 ) Each class needs at least these two assignment operators: - /* - MyType &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Mytype &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - */ - // Note on accepts: constructors call the base class - // version of a virtual when calling the base class constructor, - // so the test has to be done explicitly in a descendent. - - // If you are inheriting from PythonExtension to define an object - // note that it contains PythonExtension::check - // which you can use in accepts when writing a wrapper class. - // See Demo/range.h and Demo/range.cxx for an example. - - class Object - { - private: - // the pointer to the Python object - // Only Object sets this directly. - // The default constructor for Object sets it to Py_None and - // child classes must use "set" to set it - // - PyObject *p; - - protected: - void set( PyObject *pyob, bool owned = false ) - { - release(); - p = pyob; - if( !owned ) - { - Py::_XINCREF( p ); - } - validate(); - } - - void release() - { - Py::_XDECREF( p ); - p = NULL; - } - - void validate(); - - public: - // Constructor acquires new ownership of pointer unless explicitly told not to. - explicit Object( PyObject *pyob=Py::_None(), bool owned = false ) - : p( pyob ) - { - if( !owned ) - { - Py::_XINCREF( p ); - } - validate(); - } - - // Copy constructor acquires new ownership of pointer - Object( const Object &ob ) - : p( ob.p ) - { - Py::_XINCREF( p ); - validate(); - } - - // Assignment acquires new ownership of pointer - Object &operator=( const Object &rhs ) - { - set( rhs.p ); - return *this; - } - - Object &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - - return *this; - } - - // Destructor - virtual ~Object() - { - release(); - } - - // Loaning the pointer to others, retain ownership - PyObject *operator*() const - { - return p; - } - - // Explicit reference_counting changes - void increment_reference_count() - { - Py::_XINCREF( p ); - } - - void decrement_reference_count() - { - // not allowed to commit suicide, however - if( reference_count() == 1 ) - throw RuntimeError( "Object::decrement_reference_count error." ); - Py::_XDECREF( p ); - } - - // Would like to call this pointer() but messes up STL in SeqBase - PyObject *ptr() const - { - return p; - } - - // - // Queries - // - - // Can pyob be used in this object's constructor? - virtual bool accepts( PyObject *pyob ) const - { - // allow any object or NULL - return true; - } - - Py_ssize_t reference_count() const - { // the reference count - return p ? p->ob_refcnt : 0; - } - - Type type() const; // the type object associated with this one - - String str() const; // the str() representation - - std::string as_string() const; - - String repr() const; // the repr() representation - - List dir() const; // the dir() list - - bool hasAttr( const std::string &s ) const - { - return PyObject_HasAttrString( p, const_cast( s.c_str() ) ) ? true: false; - } - - Object getAttr( const std::string &s ) const - { - return Object( PyObject_GetAttrString( p, const_cast( s.c_str() ) ), true ); - } - - Object callMemberFunction( const std::string &function_name ) const; - Object callMemberFunction( const std::string &function_name, const Tuple &args ) const; - Object callMemberFunction( const std::string &function_name, const Tuple &args, const Dict &kw ) const; - - Object getItem( const Object &key ) const - { - return Object( PyObject_GetItem( p, *key ), true ); - } - - Py_hash_t hashValue() const - { - return PyObject_Hash( p ); - } - - // convert to bool - bool as_bool() const - { - return PyObject_IsTrue( ptr() ) != 0; - } - - //operator bool() const - //{ - // return as_bool(); - //} - - // int print( FILE *fp, int flags=Py_Print_RAW ) - //{ - // return PyObject_Print( p, fp, flags ); - //} - - bool is( PyObject *pother ) const - { // identity test - return p == pother; - } - - bool is( const Object &other ) const - { // identity test - return p == other.p; - } - - bool isNull() const - { - return p == NULL; - } - - bool isNone() const - { - return p == _None(); - } - - bool isCallable() const - { - return PyCallable_Check( p ) != 0; - } - - bool isDict() const - { - return Py::_Dict_Check( p ); - } - - bool isList() const - { - return Py::_List_Check( p ); - } - - bool isMapping() const - { - return PyMapping_Check( p ) != 0; - } - - bool isNumeric() const - { - return PyNumber_Check( p ) != 0; - } - - bool isSequence() const - { - return PySequence_Check( p ) != 0; - } - - bool isTrue() const - { - return PyObject_IsTrue( p ) != 0; - } - - bool isType( const Type &t ) const; - - bool isTuple() const - { - return Py::_Tuple_Check( p ); - } - - bool isString() const - { - return Py::_Unicode_Check( p ); - } - - bool isBytes() const - { - return Py::_Bytes_Check( p ); - } - - bool isBoolean() const - { - return Py::_Boolean_Check( p ); - } - - // Commands - void setAttr( const std::string &s, const Object &value ) - { - if( PyObject_SetAttrString( p, const_cast( s.c_str() ), *value ) == -1 ) - throw AttributeError( "getAttr failed." ); - } - - void delAttr( const std::string &s ) - { - if( PyObject_DelAttrString( p, const_cast( s.c_str() ) ) == -1 ) - throw AttributeError( "delAttr failed." ); - } - - // PyObject_SetItem is too weird to be using from C++ - // so it is intentionally omitted. - - void delItem( const Object &key ) - { - //if( PyObject_DelItem( p, *key ) == -1 ) - // failed to link on Windows? - throw KeyError( "delItem failed." ); - } - // Equality and comparison use PyObject_Compare - - }; - // End of class Object - - // Null can be return from when it is require to return NULL to Python from a method - class Null: public Object - { - public: - Null() - : Object( NULL ) - { - } - virtual ~Null() - { - } - - virtual bool accepts( PyObject *pyob ) - { - return pyob == NULL; - } - }; - - //------------------------------------------------------------ - bool operator==( const Object &o1, const Object &o2 ); - bool operator!=( const Object &o1, const Object &o2 ); - bool operator>=( const Object &o1, const Object &o2 ); - bool operator<=( const Object &o1, const Object &o2 ); - bool operator<( const Object &o1, const Object &o2 ); - bool operator>( const Object &o1, const Object &o2 ); - - //------------------------------------------------------------ - - - // - // Convert an owned Python pointer into a PyCXX Object - // - inline Object asObject( PyObject *p ) - { - return Object( p, true ); - } - - // new_reference_to also overloaded below on Object - inline PyObject *new_reference_to( PyObject *p ) - { - Py::_XINCREF( p ); - return p; - } - - inline PyObject *new_reference_to( const Object &g ) - { - PyObject *p = g.ptr(); - Py::_XINCREF( p ); - return p; - } - - // Python special None value - inline Object None() - { - return Object( Py::_None() ); - } - - // Python special Boolean values - inline Object False() - { - return Object( Py::_False() ); - } - - inline Object True() - { - return Object( Py::_True() ); - } - - // TMM: 31May'01 - Added the #ifndef so I can exlude iostreams. -#ifndef CXX_NO_IOSTREAMS - std::ostream &operator<<( std::ostream &os, const Object &ob ); -#endif - - // Class Type - class Type: public Object - { - public: - explicit Type( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Type( const Object &ob ) - : Object( *ob ) - { - validate(); - } - - Type( const Type &t ) - : Object( t ) - { - validate(); - } - - Type &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Type &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_Type_Check( pyob ); - } - }; - - // =============================================== - // class boolean - class Boolean: public Object - { - public: - // Constructor - Boolean( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Boolean( const Boolean &ob ) - : Object( *ob ) - { - validate(); - } - - // create from bool - Boolean( bool v=false ) - { - set( PyBool_FromLong( v ? 1 : 0 ), true ); - validate(); - } - - explicit Boolean( const Object &ob ) - : Object( *ob ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - Boolean &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Boolean &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - // Membership - virtual bool accepts( PyObject *pyob ) const - { - // accepts any object that can be converted to a boolean - return pyob && PyObject_IsTrue( pyob ) != -1; - } - - Boolean &operator=( bool v ) - { - set( PyBool_FromLong( v ? 1 : 0 ), true ); - return *this; - } - - operator bool() const - { - return as_bool(); - } - }; - - // =============================================== - // class Long - class Long: public Object - { - public: - // Constructor - explicit Long( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Long( const Long &ob ) - : Object( ob.ptr() ) - { - validate(); - } - - // try to create from any object - explicit Long( const Object &ob ) - : Object( PyNumber_Long( *ob ), true ) - { - validate(); - } - - // create from long - explicit Long( long v = 0L ) - : Object( PyLong_FromLong( v ), true ) - { - validate(); - } - - // create from unsigned long - explicit Long( unsigned long v ) - : Object( PyLong_FromUnsignedLong( v ), true ) - { - validate(); - } - - // create from int - explicit Long( int v ) - : Object( PyLong_FromLong( static_cast( v ) ), true ) - { - validate(); - } - -#ifdef HAVE_LONG_LONG - // create from long long - explicit Long( PY_LONG_LONG v ) - : Object( PyLong_FromLongLong( v ), true ) - { - validate(); - } - - // create from unsigned long long - explicit Long( unsigned PY_LONG_LONG v ) - : Object( PyLong_FromUnsignedLongLong( v ), true ) - { - validate(); - } -#endif - - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_Long_Check( pyob ); - } - - // Assignment acquires new ownership of pointer - Long &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Long &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( PyNumber_Long( rhsp ), true ); - return *this; - } - - // assign from an int - Long &operator=( int v ) - { - set( PyLong_FromLong( long( v ) ), true ); - return *this; - } - - // assign from long - Long &operator=( long v ) - { - set( PyLong_FromLong( v ), true ); - return *this; - } - - // assign from unsigned long - Long &operator=( unsigned long v ) - { - set( PyLong_FromUnsignedLong( v ), true ); - return *this; - } - -#ifdef HAVE_LONG_LONG - Long &operator=( PY_LONG_LONG v ) - { - set( PyLong_FromLongLong( v ), true ); - return *this; - } - - Long &operator=( unsigned PY_LONG_LONG v ) - { - set( PyLong_FromUnsignedLongLong( v ), true ); - return *this; - } -#endif - - //operator bool() const - //{ - // return as_bool(); - //} - - // convert to long - long as_long() const - { - return PyLong_AsLong( ptr() ); - } - - operator long() const - { - return as_long(); - } - - operator int() const - { - return static_cast( as_long() ); - } - - // convert to unsigned - long as_unsigned_long() const - { - return PyLong_AsUnsignedLong( ptr() ); - } - - operator unsigned long() const - { - return as_unsigned_long(); - } - - double as_double() const - { - return PyLong_AsDouble( ptr() ); - } - - operator double() const - { - return as_double(); - } - -#ifdef HAVE_LONG_LONG - PY_LONG_LONG as_long_long() const - { - return PyLong_AsLongLong( ptr() ); - } - - operator PY_LONG_LONG() const - { - return as_long_long(); - } - - unsigned PY_LONG_LONG as_unsigned_long_long() const - { - return PyLong_AsUnsignedLongLong( ptr() ); - } - - operator unsigned PY_LONG_LONG() const - { - return as_unsigned_long_long(); - } -#endif - - // prefix ++ - Long operator++() - { - set( PyNumber_Add( ptr(), *Long( 1 ) ) ); - return *this; - } - - // postfix ++ - Long operator++( int ) - { - Long a = *this; - set( PyNumber_Add( ptr(), *Long( 1 ) ) ); - return a; - } - - // prefix -- - Long operator--() - { - set( PyNumber_Subtract( ptr(), *Long( 1 ) ) ); - return *this; - } - - // postfix -- - Long operator--( int ) - { - Long a = *this; - set( PyNumber_Subtract( ptr(), *Long( 1 ) ) ); - return a; - } - }; - -#ifdef PYCXX_PYTHON_2TO3 - // PyCXX for Python2 had an Int and LongLong classes - typedef Long Int; -#ifdef HAVE_LONG_LONG - typedef Long LongLong; -#endif -#endif - -#if 1 - //------------------------------------------------------------ - // compare operators - bool operator!=( const Long &a, const Long &b ); - bool operator!=( const Long &a, int b ); - bool operator!=( const Long &a, long b ); - bool operator!=( int a, const Long &b ); - bool operator!=( long a, const Long &b ); - //------------------------------ - bool operator==( const Long &a, const Long &b ); - bool operator==( const Long &a, int b ); - bool operator==( const Long &a, long b ); - bool operator==( int a, const Long &b ); - bool operator==( long a, const Long &b ); - //------------------------------ - bool operator>( const Long &a, const Long &b ); - bool operator>( const Long &a, int b ); - bool operator>( const Long &a, long b ); - bool operator>( int a, const Long &b ); - bool operator>( long a, const Long &b ); - //------------------------------ - bool operator>=( const Long &a, const Long &b ); - bool operator>=( const Long &a, int b ); - bool operator>=( const Long &a, long b ); - bool operator>=( int a, const Long &b ); - bool operator>=( long a, const Long &b ); - //------------------------------ - bool operator<( const Long &a, const Long &b ); - bool operator<( const Long &a, int b ); - bool operator<( const Long &a, long b ); - bool operator<( int a, const Long &b ); - bool operator<( long a, const Long &b ); - //------------------------------ - bool operator<=( const Long &a, const Long &b ); - bool operator<=( int a, const Long &b ); - bool operator<=( long a, const Long &b ); - bool operator<=( const Long &a, int b ); - bool operator<=( const Long &a, long b ); - -#ifdef HAVE_LONG_LONG - //------------------------------ - bool operator!=( const Long &a, PY_LONG_LONG b ); - bool operator!=( PY_LONG_LONG a, const Long &b ); - //------------------------------ - bool operator==( const Long &a, PY_LONG_LONG b ); - bool operator==( PY_LONG_LONG a, const Long &b ); - //------------------------------ - bool operator>( const Long &a, PY_LONG_LONG b ); - bool operator>( PY_LONG_LONG a, const Long &b ); - //------------------------------ - bool operator>=( const Long &a, PY_LONG_LONG b ); - bool operator>=( PY_LONG_LONG a, const Long &b ); - //------------------------------ - bool operator<( const Long &a, PY_LONG_LONG b ); - bool operator<( PY_LONG_LONG a, const Long &b ); - //------------------------------ - bool operator<=( const Long &a, PY_LONG_LONG b ); - bool operator<=( PY_LONG_LONG a, const Long &b ); -#endif -#endif - - // =============================================== - // class Float - // - class Float: public Object - { - public: - // Constructor - explicit Float( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Float( const Float &f ) - : Object( f ) - { - validate(); - } - - // make from double - explicit Float( double v=0.0 ) - : Object( PyFloat_FromDouble( v ), true ) - { - validate(); - } - - // try to make from any object - Float( const Object &ob ) - : Object( PyNumber_Float( *ob ), true ) - { - validate(); - } - - Float &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Float &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( PyNumber_Float( rhsp ), true ); - return *this; - } - - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_Float_Check( pyob ); - } - - double as_double() const - { - return PyFloat_AsDouble( ptr() ); - } - - // convert to double - operator double() const - { - return as_double(); - } - - // assign from a double - Float &operator=( double v ) - { - set( PyFloat_FromDouble( v ), true ); - return *this; - } - // assign from an int - Float &operator=( int v ) - { - set( PyFloat_FromDouble( double( v ) ), true ); - return *this; - } - // assign from long - Float &operator=( long v ) - { - set( PyFloat_FromDouble( double( v ) ), true ); - return *this; - } - // assign from an Long - Float &operator=( const Long &iob ) - { - set( PyFloat_FromDouble( double( iob.as_long() ) ), true ); - return *this; - } - }; - - //------------------------------------------------------------ - // compare operators - bool operator!=( const Float &a, const Float &b ); - bool operator!=( const Float &a, double b ); - bool operator!=( double a, const Float &b ); - //------------------------------ - bool operator==( const Float &a, const Float &b ); - bool operator==( const Float &a, double b ); - bool operator==( double a, const Float &b ); - //------------------------------ - bool operator>( const Float &a, const Float &b ); - bool operator>( const Float &a, double b ); - bool operator>( double a, const Float &b ); - //------------------------------ - bool operator>=( const Float &a, const Float &b ); - bool operator>=( const Float &a, double b ); - bool operator>=( double a, const Float &b ); - //------------------------------ - bool operator<( const Float &a, const Float &b ); - bool operator<( const Float &a, double b ); - bool operator<( double a, const Float &b ); - //------------------------------ - bool operator<=( const Float &a, const Float &b ); - bool operator<=( double a, const Float &b ); - bool operator<=( const Float &a, double b ); - - // =============================================== - // class Complex - class Complex: public Object - { - public: - // Constructor - explicit Complex( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Complex( const Complex &f ) - : Object( f ) - { - validate(); - } - - // make from double - explicit Complex( double v=0.0, double w=0.0 ) - :Object( PyComplex_FromDoubles( v, w ), true ) - { - validate(); - } - - Complex &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Complex &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_Complex_Check( pyob ); - } - // convert to Py_complex - operator Py_complex() const - { - return PyComplex_AsCComplex( ptr() ); - } - // assign from a Py_complex - Complex &operator=( const Py_complex &v ) - { - set( PyComplex_FromCComplex( v ), true ); - return *this; - } - // assign from a double - Complex &operator=( double v ) - { - set( PyComplex_FromDoubles( v, 0.0 ), true ); - return *this; - } - // assign from an int - Complex &operator=( int v ) - { - set( PyComplex_FromDoubles( double( v ), 0.0 ), true ); - return *this; - } - // assign from long - Complex &operator=( long v ) - { - set( PyComplex_FromDoubles( double( v ), 0.0 ), true ); - return *this; - } - // assign from an Long - Complex &operator=( const Long &iob ) - { - set( PyComplex_FromDoubles( double( iob.as_long() ), 0.0 ), true ); - return *this; - } - - double real() const - { - return PyComplex_RealAsDouble( ptr() ); - } - - double imag() const - { - return PyComplex_ImagAsDouble( ptr() ); - } - }; - // Sequences - // Sequences are here represented as sequences of items of type T. - // The base class SeqBase represents that. - // In basic Python T is always "Object". - - // seqref is what you get if you get elements from a non-const SeqBase. - // Note: seqref could probably be a nested class in SeqBase but that might stress - // some compilers needlessly. Simlarly for mapref later. - - // While this class is not intended for enduser use, it needs some public - // constructors for the benefit of the STL. - - // See Scott Meyer's More Essential C++ for a description of proxies. - // This application is even more complicated. We are doing an unusual thing - // in having a double proxy. If we want the STL to work - // properly we have to compromise by storing the rvalue inside. The - // entire Object API is repeated so that things like s[i].isList() will - // work properly. - - // Still, once in a while a weird compiler message may occur using expressions like x[i] - // Changing them to Object( x[i] ) helps the compiler to understand that the - // conversion of a seqref to an Object is wanted. - - template - class seqref - { - protected: - SeqBase &s; // the sequence - int offset; // item number - T the_item; // lvalue - - public: - seqref( SeqBase &seq, sequence_index_type j ) - : s( seq ) - , offset( j ) - , the_item( s.getItem( j ) ) - {} - - seqref( const seqref &range ) - : s( range.s ) - , offset( range.offset ) - , the_item( range.the_item ) - {} - - // TMM: added this seqref ctor for use with STL algorithms - seqref( Object &obj ) - : s( dynamic_cast< SeqBase&>( obj ) ) - , offset( NULL ) - , the_item( s.getItem( offset ) ) - {} - - ~seqref() - {} - - operator T() const - { // rvalue - return the_item; - } - - seqref &operator=( const seqref &rhs ) - { //used as lvalue - the_item = rhs.the_item; - s.setItem( offset, the_item ); - return *this; - } - - seqref &operator=( const T &ob ) - { // used as lvalue - the_item = ob; - s.setItem( offset, ob ); - return *this; - } - - // forward everything else to the item - PyObject *ptr() const - { - return the_item.ptr(); - } - - int reference_count() const - { // the reference count - return the_item.reference_count(); - } - - Type type() const - { - return the_item.type(); - } - - String str() const; - String repr() const; - - bool hasAttr( const std::string &attr_name ) const - { - return the_item.hasAttr( attr_name ); - } - - Object getAttr( const std::string &attr_name ) const - { - return the_item.getAttr( attr_name ); - } - - Object getItem( const Object &key ) const - { - return the_item.getItem( key ); - } - - Py_hash_t hashValue() const - { - return the_item.hashValue(); - } - - bool isCallable() const - { - return the_item.isCallable(); - } - - bool isInstance() const - { - return the_item.isInstance(); - } - - bool isDict() const - { - return the_item.isDict(); - } - - bool isList() const - { - return the_item.isList(); - } - - bool isMapping() const - { - return the_item.isMapping(); - } - - bool isNumeric() const - { - return the_item.isNumeric(); - } - - bool isSequence() const - { - return the_item.isSequence(); - } - - bool isTrue() const - { - return the_item.isTrue(); - } - - bool isType( const Type &t ) const - { - return the_item.isType( t ); - } - - bool isTuple() const - { - return the_item.isTuple(); - } - - bool isString() const - { - return the_item.isString(); - } - // Commands - void setAttr( const std::string &attr_name, const Object &value ) - { - the_item.setAttr( attr_name, value ); - } - - void delAttr( const std::string &attr_name ) - { - the_item.delAttr( attr_name ); - } - - void delItem( const Object &key ) - { - the_item.delItem( key ); - } - - bool operator==( const Object &o2 ) const - { - return the_item == o2; - } - - bool operator!=( const Object &o2 ) const - { - return the_item != o2; - } - - bool operator>=( const Object &o2 ) const - { - return the_item >= o2; - } - - bool operator<=( const Object &o2 ) const - { - return the_item <= o2; - } - - bool operator<( const Object &o2 ) const - { - return the_item < o2; - } - - bool operator>( const Object &o2 ) const - { - return the_item > o2; - } - }; // end of seqref - - - // class SeqBase - // ...the base class for all sequence types - - template - class SeqBase: public Object - { - public: - // STL definitions - typedef size_t size_type; - typedef seqref reference; - typedef T const_reference; - typedef seqref *pointer; - typedef int difference_type; - typedef T value_type; // TMM: 26Jun'01 - - virtual size_type max_size() const - { - return std::string::npos; // ? - } - - virtual size_type capacity() const - { - return size(); - } - - virtual void swap( SeqBase &c ) - { - SeqBase temp = c; - c = ptr(); - set( temp.ptr() ); - } - - virtual size_type size() const - { - return PySequence_Length( ptr() ); - } - - explicit SeqBase() - :Object( PyTuple_New( 0 ), true ) - { - validate(); - } - - explicit SeqBase( PyObject *pyob, bool owned=false ) - : Object( pyob, owned ) - { - validate(); - } - - SeqBase( const Object &ob ) - : Object( ob ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - SeqBase &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - SeqBase &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - virtual bool accepts( PyObject *pyob ) const - { - return pyob && PySequence_Check( pyob ); - } - - size_type length() const - { - return PySequence_Length( ptr() ); - } - - // Element access - const T operator[]( sequence_index_type index ) const - { - return getItem( index ); - } - - seqref operator[]( sequence_index_type index ) - { - return seqref( *this, index ); - } - - virtual T getItem( sequence_index_type i ) const - { - return T( asObject( PySequence_GetItem( ptr(), i ) ) ); - } - - virtual void setItem( sequence_index_type i, const T &ob ) - { - if( PySequence_SetItem( ptr(), i, *ob ) == -1 ) - { - throw Exception(); - } - } - - SeqBase repeat( int count ) const - { - return SeqBase( PySequence_Repeat( ptr(), count ), true ); - } - - SeqBase concat( const SeqBase &other ) const - { - return SeqBase( PySequence_Concat( ptr(), *other ), true ); - } - - // more STL compatability - const T front() const - { - return getItem( 0 ); - } - - seqref front() - { - return seqref( *this, 0 ); - } - - const T back() const - { - return getItem( size()-1 ); - } - - seqref back() - { - return seqref( *this, size()-1 ); - } - - void verify_length( size_type required_size ) const - { - if( size() != required_size ) - throw IndexError( "Unexpected SeqBase length." ); - } - - void verify_length( size_type min_size, size_type max_size ) const - { - size_type n = size(); - if( n < min_size || n > max_size ) - throw IndexError( "Unexpected SeqBase length." ); - } - - class iterator - : public random_access_iterator_parent( seqref ) - { - protected: - friend class SeqBase; - SeqBase *seq; - int count; - - public: - ~iterator() - {} - - iterator() - : seq( 0 ) - , count( 0 ) - {} - - iterator( SeqBase *s, int where ) - : seq( s ) - , count( where ) - {} - - iterator( const iterator &other ) - : seq( other.seq ) - , count( other.count ) - {} - - bool eql( const iterator &other ) const - { - return seq->ptr() == other.seq->ptr() && count == other.count; - } - - bool neq( const iterator &other ) const - { - return seq->ptr() != other.seq->ptr() || count != other.count; - } - - bool lss( const iterator &other ) const - { - return count < other.count; - } - - bool gtr( const iterator &other ) const - { - return count > other.count; - } - - bool leq( const iterator &other ) const - { - return count <= other.count; - } - - bool geq( const iterator &other ) const - { - return count >= other.count; - } - - seqref operator*() - { - return seqref( *seq, count ); - } - - seqref operator[]( sequence_index_type i ) - { - return seqref( *seq, count + i ); - } - - iterator &operator=( const iterator &other ) - { - if( this != &other ) - { - seq = other.seq; - count = other.count; - } - return *this; - } - - iterator operator+( int n ) const - { - return iterator( seq, count + n ); - } - - iterator operator-( int n ) const - { - return iterator( seq, count - n ); - } - - iterator &operator+=( int n ) - { - count = count + n; - return *this; - } - - iterator &operator-=( int n ) - { - count = count - n; - return *this; - } - - int operator-( const iterator &other ) const - { - if( seq->ptr() != other.seq->ptr() ) - throw RuntimeError( "SeqBase::iterator comparison error" ); - - return count - other.count; - } - - // prefix ++ - iterator &operator++() - { - count++; - return *this; - } - - // postfix ++ - iterator operator++( int ) - { - return iterator( seq, count++ ); - } - - // prefix -- - iterator &operator--() - { - count--; - return *this; - } - - // postfix -- - iterator operator--( int ) - { - return iterator( seq, count-- ); - } - - std::string diagnose() const - { - std::OSTRSTREAM oss; - oss << "iterator diagnosis " << seq << ", " << count << std::ends; - return std::string( oss.str() ); - } - - }; // end of class SeqBase::iterator - - iterator begin() - { - return iterator( this, 0 ); - } - - iterator end() - { - return iterator( this, length() ); - } - - class const_iterator - : public random_access_iterator_parent( const Object ) - { - protected: - friend class SeqBase; - const SeqBase *seq; - sequence_index_type count; - - public: - ~const_iterator() - {} - - const_iterator() - : seq( 0 ) - , count( 0 ) - {} - - const_iterator( const SeqBase *s, int where ) - : seq( s ) - , count( where ) - {} - - const_iterator( const const_iterator &other ) - : seq( other.seq ) - , count( other.count ) - {} - - const T operator*() const - { - return seq->getItem( count ); - } - - const T operator[]( sequence_index_type i ) const - { - return seq->getItem( count + i ); - } - - const_iterator &operator=( const const_iterator &other ) - { - if( this != &other ) - { - seq = other.seq; - count = other.count; - } - return *this; - } - - const_iterator operator+( int n ) const - { - return const_iterator( seq, count + n ); - } - - bool eql( const const_iterator &other ) const - { - return seq->ptr() == other.seq->ptr() && count == other.count; - } - - bool neq( const const_iterator &other ) const - { - return seq->ptr() != other.seq->ptr() || count != other.count; - } - - bool lss( const const_iterator &other ) const - { - return count < other.count; - } - - bool gtr( const const_iterator &other ) const - { - return count > other.count; - } - - bool leq( const const_iterator &other ) const - { - return count <= other.count; - } - - bool geq( const const_iterator &other ) const - { - return count >= other.count; - } - - const_iterator operator-( int n ) - { - return const_iterator( seq, count - n ); - } - - const_iterator &operator+=( int n ) - { - count = count + n; - return *this; - } - - const_iterator &operator-=( int n ) - { - count = count - n; - return *this; - } - - int operator-( const const_iterator &other ) const - { - if( *seq != *other.seq ) - throw RuntimeError( "SeqBase::const_iterator::- error" ); - return count - other.count; - } - - // prefix ++ - const_iterator &operator++() - { - count++; - return *this; - } - - // postfix ++ - const_iterator operator++( int ) - { - return const_iterator( seq, count++ ); - } - - // prefix -- - const_iterator &operator--() - { - count--; - return *this; - } - - // postfix -- - const_iterator operator--( int ) - { - return const_iterator( seq, count-- ); - } - - }; // end of class SeqBase::const_iterator - - const_iterator begin() const - { - return const_iterator( this, 0 ); - } - - const_iterator end() const - { - return const_iterator( this, length() ); - } - }; - - // Here's an important typedef you might miss if reading too fast... - typedef SeqBase Sequence; - - template bool operator==( const EXPLICIT_TYPENAME SeqBase::iterator &left, const EXPLICIT_TYPENAME SeqBase::iterator &right ); - template bool operator!=( const EXPLICIT_TYPENAME SeqBase::iterator &left, const EXPLICIT_TYPENAME SeqBase::iterator &right ); - template bool operator< ( const EXPLICIT_TYPENAME SeqBase::iterator &left, const EXPLICIT_TYPENAME SeqBase::iterator &right ); - template bool operator> ( const EXPLICIT_TYPENAME SeqBase::iterator &left, const EXPLICIT_TYPENAME SeqBase::iterator &right ); - template bool operator<=( const EXPLICIT_TYPENAME SeqBase::iterator &left, const EXPLICIT_TYPENAME SeqBase::iterator &right ); - template bool operator>=( const EXPLICIT_TYPENAME SeqBase::iterator &left, const EXPLICIT_TYPENAME SeqBase::iterator &right ); - - template bool operator==( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - template bool operator!=( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - template bool operator< ( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - template bool operator> ( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - template bool operator<=( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - template bool operator>=( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - - - extern bool operator==( const Sequence::iterator &left, const Sequence::iterator &right ); - extern bool operator!=( const Sequence::iterator &left, const Sequence::iterator &right ); - extern bool operator< ( const Sequence::iterator &left, const Sequence::iterator &right ); - extern bool operator> ( const Sequence::iterator &left, const Sequence::iterator &right ); - extern bool operator<=( const Sequence::iterator &left, const Sequence::iterator &right ); - extern bool operator>=( const Sequence::iterator &left, const Sequence::iterator &right ); - - extern bool operator==( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - extern bool operator!=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - extern bool operator< ( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - extern bool operator> ( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - extern bool operator<=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - extern bool operator>=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - - // ================================================== - // class Char - // Python strings return strings as individual elements. - // I'll try having a class Char which is a String of length 1 - // - typedef std::basic_string unicodestring; - extern Py_UNICODE unicode_null_string[1]; - - class Byte: public Object - { - public: - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob != NULL - && Py::_Unicode_Check( pyob ) - && PySequence_Length( pyob ) == 1; - } - - explicit Byte( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Byte( const Object &ob ) - : Object( ob ) - { - validate(); - } - - Byte( const std::string &v = "" ) - : Object( PyBytes_FromStringAndSize( const_cast( v.c_str() ), 1 ), true ) - { - validate(); - } - - Byte( char v ) - : Object( PyBytes_FromStringAndSize( &v, 1 ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - Byte &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Byte &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - // Assignment from C string - Byte &operator=( const std::string &v ) - { - set( PyBytes_FromStringAndSize( const_cast( v.c_str() ),1 ), true ); - return *this; - } - - Byte &operator=( char v ) - { - set( PyUnicode_FromStringAndSize( &v, 1 ), true ); - return *this; - } - - // Conversion - operator Bytes() const; - }; - - class Bytes: public SeqBase - { - public: - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob != NULL && Py::_Bytes_Check( pyob ); - } - - virtual size_type capacity() const - { - return max_size(); - } - - explicit Bytes( PyObject *pyob, bool owned = false ) - : SeqBase( pyob, owned ) - { - validate(); - } - - Bytes( const Object &ob ) - : SeqBase( ob ) - { - validate(); - } - - Bytes() - : SeqBase( PyBytes_FromStringAndSize( "", 0 ), true ) - { - validate(); - } - - Bytes( const std::string &v ) - : SeqBase( PyBytes_FromStringAndSize( const_cast( v.data() ), static_cast( v.length() ) ), true ) - { - validate(); - } - - Bytes( const std::string &v, Py_ssize_t vsize ) - : SeqBase( PyBytes_FromStringAndSize( const_cast( v.data() ), static_cast( vsize ) ), true ) - { - validate(); - } - - Bytes( const char *v ) - : SeqBase( PyBytes_FromString( v ), true ) - { - validate(); - } - - Bytes( const char *v, Py_ssize_t vsize ) - : SeqBase( PyBytes_FromStringAndSize( const_cast( v ), vsize ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - Bytes &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Bytes &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - // Assignment from C string - Bytes &operator=( const std::string &v ) - { - set( PyBytes_FromStringAndSize( const_cast( v.data() ), static_cast( v.length() ) ), true ); - return *this; - } - - String decode( const char *encoding, const char *error="strict" ); - - // Queries - virtual size_type size() const - { - return static_cast( PyBytes_Size( ptr() ) ); - } - - operator std::string() const - { - return as_std_string(); - } - - std::string as_std_string() const - { - return std::string( PyBytes_AsString( ptr() ), static_cast( PyBytes_Size( ptr() ) ) ); - } - }; - - class Char: public Object - { - public: - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob != 0 &&( Py::_Unicode_Check( pyob ) ) && PySequence_Length( pyob ) == 1; - } - - explicit Char( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Char( const Object &ob ) - : Object( ob ) - { - validate(); - } - - Char( int v ) - : Object( PyUnicode_FromOrdinal( v ), true ) - { - validate(); - } - - Char( Py_UNICODE v ) - : Object( PyUnicode_FromOrdinal( v ), true ) - { - validate(); - } - - Char( const unicodestring &v ) - : Object( PyUnicode_FromUnicode( const_cast( v.data() ),1 ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - Char &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Char &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - Char &operator=( const unicodestring &v ) - { - set( PyUnicode_FromUnicode( const_cast( v.data() ), 1 ), true ); - return *this; - } - - Char &operator=( int v_ ) - { - Py_UNICODE v( v_ ); - set( PyUnicode_FromUnicode( &v, 1 ), true ); - return *this; - } - - Char &operator=( Py_UNICODE v ) - { - set( PyUnicode_FromUnicode( &v, 1 ), true ); - return *this; - } - - // Conversion - operator String() const; - }; - - class String: public SeqBase - { - public: - virtual size_type capacity() const - { - return max_size(); - } - - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob != NULL && Py::_Unicode_Check( pyob ); - } - - explicit String( PyObject *pyob, bool owned = false ) - : SeqBase( pyob, owned ) - { - validate(); - } - - String( const Object &ob ) - : SeqBase( ob ) - { - validate(); - } - - String() - : SeqBase( PyUnicode_FromString( "" ) ) - { - validate(); - } - - String( const char *latin1 ) - : SeqBase( PyUnicode_FromString( latin1 ) ) - { - validate(); - } - - String( const std::string &latin1 ) - : SeqBase( PyUnicode_FromStringAndSize( latin1.c_str(), latin1.size() ) ) - { - validate(); - } - - String( const char *latin1, Py_ssize_t size ) - : SeqBase( PyUnicode_FromStringAndSize( latin1, size ) ) - { - validate(); - } - - /* [Taken from Pythons's unicode.h] - - Many of these APIs take two arguments encoding and errors. These - parameters encoding and errors have the same semantics as the ones - of the builtin unicode() API. - - Setting encoding to NULL causes the default encoding to be used. - - Error handling is set by errors which may also be set to NULL - meaning to use the default handling defined for the codec. Default - error handling for all builtin codecs is "strict" (ValueErrors are - raised). - - The codecs all use a similar interface. Only deviation from the - generic ones are documented. - - */ - String( const std::string &s, const char *encoding, const char *errors=NULL ) - : SeqBase( PyUnicode_Decode( s.c_str(), s.size(), encoding, errors ), true ) - { - validate(); - } - - String( const char *s, const char *encoding, const char *errors=NULL ) - : SeqBase( PyUnicode_Decode( s, strlen(s), encoding, errors ), true ) - { - validate(); - } - - String( const char *s, Py_ssize_t size, const char *encoding, const char *errors=NULL ) - : SeqBase( PyUnicode_Decode( s, size, encoding, errors ), true ) - { - validate(); - } - - String( const Py_UNICODE *s, int length ) - : SeqBase( PyUnicode_FromUnicode( s, length ), true ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - String &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - String &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - String &operator=( const unicodestring &v ) - { - set( PyUnicode_FromUnicode( const_cast( v.data() ), static_cast( v.length() ) ), true ); - return *this; - } - - // Encode - Bytes encode( const char *encoding, const char *error="strict" ) const - { - return Bytes( PyUnicode_AsEncodedString( ptr(), encoding, error ), true ); - } - - // Queries - virtual size_type size() const - { - return static_cast( PyUnicode_GET_SIZE( ptr() ) ); - } - - unicodestring as_unicodestring() const - { - return unicodestring( PyUnicode_AS_UNICODE( ptr() ), static_cast( PyUnicode_GET_SIZE( ptr() ) ) ); - } - - operator std::string() const - { - // use the default encoding - return as_std_string( NULL ); - } - - std::string as_std_string( const char *encoding=NULL, const char *error="strict" ) const - { - Bytes b( encode( encoding, error ) ); - return b.as_std_string(); - } - - const Py_UNICODE *unicode_data() const - { - return PyUnicode_AS_UNICODE( ptr() ); - } - }; - - // ================================================== - // class Tuple - class Tuple: public Sequence - { - public: - virtual void setItem( sequence_index_type offset, const Object&ob ) - { - // note PyTuple_SetItem is a thief... - if( PyTuple_SetItem( ptr(), offset, new_reference_to( ob ) ) == -1 ) - { - throw Exception(); - } - } - - // Constructor - explicit Tuple( PyObject *pyob, bool owned = false ) - : Sequence( pyob, owned ) - { - validate(); - } - - Tuple( const Object &ob ) - : Sequence( ob ) - { - validate(); - } - - // New tuple of a given size - explicit Tuple( int size = 0 ) - { - set( PyTuple_New( size ), true ); - validate(); - for( sequence_index_type i=0; i < size; i++ ) - { - if( PyTuple_SetItem( ptr(), i, new_reference_to( Py::_None() ) ) == -1 ) - { - throw Exception(); - } - } - } - // Tuple from any sequence - explicit Tuple( const Sequence &s ) - { - sequence_index_type limit( sequence_index_type( s.length() ) ); - - set( PyTuple_New( limit ), true ); - validate(); - - for( sequence_index_type i=0; i < limit; i++ ) - { - if( PyTuple_SetItem( ptr(), i, new_reference_to( s[i] ) ) == -1 ) - { - throw Exception(); - } - } - } - - // Assignment acquires new ownership of pointer - Tuple &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Tuple &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_Tuple_Check( pyob ); - } - - Tuple getSlice( int i, int j ) const - { - return Tuple( PySequence_GetSlice( ptr(), i, j ), true ); - } - - }; - - class TupleN: public Tuple - { - public: - TupleN() - : Tuple( 0 ) - { - } - - TupleN( const Object &obj1 ) - : Tuple( 1 ) - { - setItem( 0, obj1 ); - } - - TupleN( const Object &obj1, const Object &obj2 ) - : Tuple( 2 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3 ) - : Tuple( 3 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4 ) - : Tuple( 4 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5 ) - : Tuple( 5 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6 ) - : Tuple( 6 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6, - const Object &obj7 ) - : Tuple( 7 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - setItem( 6, obj7 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6, - const Object &obj7, const Object &obj8 ) - : Tuple( 8 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - setItem( 6, obj7 ); - setItem( 7, obj8 ); - } - - TupleN( const Object &obj1, const Object &obj2, const Object &obj3, - const Object &obj4, const Object &obj5, const Object &obj6, - const Object &obj7, const Object &obj8, const Object &obj9 ) - : Tuple( 9 ) - { - setItem( 0, obj1 ); - setItem( 1, obj2 ); - setItem( 2, obj3 ); - setItem( 3, obj4 ); - setItem( 4, obj5 ); - setItem( 5, obj6 ); - setItem( 6, obj7 ); - setItem( 7, obj8 ); - setItem( 8, obj9 ); - } - - virtual ~TupleN() - { } - }; - - // ================================================== - // class List - - class List: public Sequence - { - public: - // Constructor - explicit List( PyObject *pyob, bool owned = false ) - : Sequence( pyob, owned ) - { - validate(); - } - List( const Object &ob ) - : Sequence( ob ) - { - validate(); - } - // Creation at a fixed size - List( int size = 0 ) - { - set( PyList_New( size ), true ); - validate(); - for( sequence_index_type i=0; i < size; i++ ) - { - if( PyList_SetItem( ptr(), i, new_reference_to( Py::_None() ) ) == -1 ) - { - throw Exception(); - } - } - } - - // List from a sequence - List( const Sequence &s ) - : Sequence() - { - int n =( int )s.length(); - set( PyList_New( n ), true ); - validate(); - for( sequence_index_type i=0; i < n; i++ ) - { - if( PyList_SetItem( ptr(), i, new_reference_to( s[i] ) ) == -1 ) - { - throw Exception(); - } - } - } - - virtual size_type capacity() const - { - return max_size(); - } - - // Assignment acquires new ownership of pointer - List &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - List &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_List_Check( pyob ); - } - - List getSlice( int i, int j ) const - { - return List( PyList_GetSlice( ptr(), i, j ), true ); - } - - void setSlice( int i, int j, const Object &v ) - { - if( PyList_SetSlice( ptr(), i, j, *v ) == -1 ) - { - throw Exception(); - } - } - - void append( const Object &ob ) - { - if( PyList_Append( ptr(), *ob ) == -1 ) - { - throw Exception(); - } - } - - void extend( const Object &ob ) - { - setSlice( size(), size(), ob ); - } - - void insert( int i, const Object &ob ) - { - if( PyList_Insert( ptr(), i, *ob ) == -1 ) - { - throw Exception(); - } - } - - void sort() - { - if( PyList_Sort( ptr() ) == -1 ) - { - throw Exception(); - } - } - - void reverse() - { - if( PyList_Reverse( ptr() ) == -1 ) - { - throw Exception(); - } - } - }; - - - // Mappings - // ================================================== - template - class mapref - { - protected: - MapBase &s; // the map - Object key; // item key - T the_item; - - public: - mapref( MapBase &map, const std::string &k ) - : s( map ), the_item() - { - key = String( k ); - if( map.hasKey( key ) ) the_item = map.getItem( key ); - } - - mapref( MapBase &map, const Object &k ) - : s( map ), key( k ), the_item() - { - if( map.hasKey( key ) ) the_item = map.getItem( key ); - } - - virtual ~mapref() - {} - - // MapBase stuff - // lvalue - mapref &operator=( const mapref &other ) - { - if( this != &other ) - { - the_item = other.the_item; - s.setItem( key, other.the_item ); - } - return *this; - } - - mapref &operator=( const T &ob ) - { - the_item = ob; - s.setItem( key, ob ); - return *this; - } - - // rvalue - operator T() const - { - return the_item; - } - - // forward everything else to the_item - PyObject *ptr() const - { - return the_item.ptr(); - } - - int reference_count() const - { // the mapref count - return the_item.reference_count(); - } - - Type type() const - { - return the_item.type(); - } - - String str() const - { - return the_item.str(); - } - - String repr() const - { - return the_item.repr(); - } - - bool hasAttr( const std::string &attr_name ) const - { - return the_item.hasAttr( attr_name ); - } - - Object getAttr( const std::string &attr_name ) const - { - return the_item.getAttr( attr_name ); - } - - Object getItem( const Object &k ) const - { - return the_item.getItem( k ); - } - - Py_hash_t hashValue() const - { - return the_item.hashValue(); - } - - bool isCallable() const - { - return the_item.isCallable(); - } - - bool isInstance() const - { - return the_item.isInstance(); - } - - bool isList() const - { - return the_item.isList(); - } - - bool isMapping() const - { - return the_item.isMapping(); - } - - bool isNumeric() const - { - return the_item.isNumeric(); - } - - bool isSequence() const - { - return the_item.isSequence(); - } - - bool isTrue() const - { - return the_item.isTrue(); - } - - bool isType( const Type &t ) const - { - return the_item.isType( t ); - } - - bool isTuple() const - { - return the_item.isTuple(); - } - - bool isString() const - { - return the_item.isString(); - } - - // Commands - void setAttr( const std::string &attr_name, const Object &value ) - { - the_item.setAttr( attr_name, value ); - } - - void delAttr( const std::string &attr_name ) - { - the_item.delAttr( attr_name ); - } - - void delItem( const Object &k ) - { - the_item.delItem( k ); - } - }; // end of mapref - -#if 0 - // TMM: now for mapref - template< class T > - bool operator==( const mapref &left, const mapref &right ) - { - return true; // NOT completed. - } - - template< class T > - bool operator!=( const mapref &left, const mapref &right ) - { - return true; // not completed. - } -#endif - - template - class MapBase: public Object - { - protected: - explicit MapBase() - {} - public: - // reference: proxy class for implementing [] - // TMM: 26Jun'01 - the types - // If you assume that Python mapping is a hash_map... - // hash_map::value_type is not assignable, but - //( *it ).second = data must be a valid expression - typedef size_t size_type; - typedef Object key_type; - typedef mapref data_type; - typedef std::pair< const T, T > value_type; - typedef std::pair< const T, mapref > reference; - typedef const std::pair< const T, const T > const_reference; - typedef std::pair< const T, mapref > pointer; - - // Constructor - explicit MapBase( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - // TMM: 02Jul'01 - changed MapBase to Object in next line - MapBase( const Object &ob ) - : Object( ob ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - MapBase &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - MapBase &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && PyMapping_Check( pyob ); - } - - // Clear -- PyMapping Clear is missing - // - - void clear() - { - List k = keys(); - for( List::iterator i = k.begin(); i != k.end(); i++ ) - { - delItem( *i ); - } - } - - virtual size_type size() const - { - return PyMapping_Length( ptr() ); - } - - // Element Access - T operator[]( const std::string &key ) const - { - return getItem( key ); - } - - T operator[]( const Object &key ) const - { - return getItem( key ); - } - - mapref operator[]( const char *key ) - { - return mapref( *this, key ); - } - - mapref operator[]( const std::string &key ) - { - return mapref( *this, key ); - } - - mapref operator[]( const Object &key ) - { - return mapref( *this, key ); - } - - int length() const - { - return PyMapping_Length( ptr() ); - } - - bool hasKey( const std::string &s ) const - { - return PyMapping_HasKeyString( ptr(),const_cast( s.c_str() ) ) != 0; - } - - bool hasKey( const Object &s ) const - { - return PyMapping_HasKey( ptr(), s.ptr() ) != 0; - } - - T getItem( const std::string &s ) const - { - return T( asObject( PyMapping_GetItemString( ptr(),const_cast( s.c_str() ) ) ) ); - } - - T getItem( const Object &s ) const - { - return T( asObject( PyObject_GetItem( ptr(), s.ptr() ) ) ); - } - - virtual void setItem( const char *s, const Object &ob ) - { - if( PyMapping_SetItemString( ptr(), const_cast( s ), *ob ) == -1 ) - { - throw Exception(); - } - } - - virtual void setItem( const std::string &s, const Object &ob ) - { - if( PyMapping_SetItemString( ptr(), const_cast( s.c_str() ), *ob ) == -1 ) - { - throw Exception(); - } - } - - virtual void setItem( const Object &s, const Object &ob ) - { - if( PyObject_SetItem( ptr(), s.ptr(), ob.ptr() ) == -1 ) - { - throw Exception(); - } - } - - void delItem( const std::string &s ) - { - if( PyMapping_DelItemString( ptr(), const_cast( s.c_str() ) ) == -1 ) - { - throw Exception(); - } - } - - void delItem( const Object &s ) - { - if( PyMapping_DelItem( ptr(), *s ) == -1 ) - { - throw Exception(); - } - } - - // Queries - List keys() const - { - return List( PyMapping_Keys( ptr() ), true ); - } - - List values() const - { - // each returned item is a (key, value) pair - return List( PyMapping_Values( ptr() ), true ); - } - - List items() const - { - return List( PyMapping_Items( ptr() ), true ); - } - - class iterator - { - // : public forward_iterator_parent( std::pair ) { - protected: - typedef std::forward_iterator_tag iterator_category; - typedef std::pair< const T, T > value_type; - typedef int difference_type; - typedef std::pair< const T, mapref > pointer; - typedef std::pair< const T, mapref > reference; - - friend class MapBase; - // - MapBase *map; - List keys; // for iterating over the map - int pos; // index into the keys - - public: - ~iterator() - {} - - iterator() - : map( 0 ) - , keys() - , pos( 0 ) - {} - - iterator( MapBase *m, bool end = false ) - : map( m ) - , keys( m->keys() ) - , pos( end ? keys.length() : 0 ) - {} - - iterator( const iterator &other ) - : map( other.map ) - , keys( other.keys ) - , pos( other.pos ) - {} - - iterator( MapBase *map_, List keys_, int pos_ ) - : map( map_ ) - , keys( keys_ ) - , pos( pos_ ) - {} - - reference operator*() - { - Object key = keys[ pos ]; - return std::make_pair( key, mapref( *map, key ) ); - } - - iterator &operator=( const iterator &other ) - { - if( this != &other ) - { - map = other.map; - keys = other.keys; - pos = other.pos; - } - return *this; - } - - bool eql( const iterator &other ) const - { - return map->ptr() == other.map->ptr() && pos == other.pos; - } - - bool neq( const iterator &other ) const - { - return map->ptr() != other.map->ptr() || pos != other.pos; - } - - // pointer operator->() { - // return ; - // } - - // prefix ++ - iterator &operator++() - { - pos++; - return *this; - } - - // postfix ++ - iterator operator++( int ) - { - return iterator( map, keys, pos++ ); - } - - // prefix -- - iterator &operator--() - { - pos--; - return *this; - } - - // postfix -- - iterator operator--( int ) - { - return iterator( map, keys, pos-- ); - } - - std::string diagnose() const - { - std::OSTRSTREAM oss; - oss << "iterator diagnosis " << map << ", " << pos << std::ends; - return std::string( oss.str() ); - } - }; // end of class MapBase::iterator - - iterator begin() - { - return iterator( this, false ); - } - - iterator end() - { - return iterator( this, true ); - } - - class const_iterator - { - protected: - typedef std::forward_iterator_tag iterator_category; - typedef const std::pair< const T, T > value_type; - typedef int difference_type; - typedef const std::pair< const T, T > pointer; - typedef const std::pair< const T, T > reference; - - friend class MapBase; - const MapBase *map; - List keys; // for iterating over the map - int pos; // index into the keys - - public: - ~const_iterator() - {} - - const_iterator() - : map( 0 ) - , keys() - , pos() - {} - - const_iterator( const MapBase *m, List k, int p ) - : map( m ) - , keys( k ) - , pos( p ) - {} - - const_iterator( const const_iterator &other ) - : map( other.map ) - , keys( other.keys ) - , pos( other.pos ) - {} - - bool eql( const const_iterator &other ) const - { - return map->ptr() == other.map->ptr() && pos == other.pos; - } - - bool neq( const const_iterator &other ) const - { - return map->ptr() != other.map->ptr() || pos != other.pos; - } - - - // const_reference operator*() { - // Object key = *pos; - // return std::make_pair( key, map->[key] ); - // GCC < 3 barfes on this line at the '['. - // } - - const_reference operator*() - { - Object key = keys[ pos ]; - return std::make_pair( key, mapref( *map, key ) ); - } - - const_iterator &operator=( const const_iterator &other ) - { - if( this != &other ) - { - map = other.map; - keys = other.keys; - pos = other.pos; - } - return *this; - } - - // prefix ++ - const_iterator &operator++() - { - pos++; - return *this; - } - - // postfix ++ - const_iterator operator++( int ) - { - return const_iterator( map, keys, pos++ ); - } - - // prefix -- - const_iterator &operator--() - { - pos--; - return *this; - } - - // postfix -- - const_iterator operator--( int ) - { - return const_iterator( map, keys, pos-- ); - } - }; // end of class MapBase::const_iterator - - const_iterator begin() const - { - return const_iterator( this, keys(), 0 ); - } - - const_iterator end() const - { - return const_iterator( this, keys(), length() ); - } - - }; // end of MapBase - - typedef MapBase Mapping; - - template bool operator==( const EXPLICIT_TYPENAME MapBase::iterator &left, const EXPLICIT_TYPENAME MapBase::iterator &right ); - template bool operator!=( const EXPLICIT_TYPENAME MapBase::iterator &left, const EXPLICIT_TYPENAME MapBase::iterator &right ); - template bool operator==( const EXPLICIT_TYPENAME MapBase::const_iterator &left, const EXPLICIT_TYPENAME MapBase::const_iterator &right ); - template bool operator!=( const EXPLICIT_TYPENAME MapBase::const_iterator &left, const EXPLICIT_TYPENAME MapBase::const_iterator &right ); - - extern bool operator==( const Mapping::iterator &left, const Mapping::iterator &right ); - extern bool operator!=( const Mapping::iterator &left, const Mapping::iterator &right ); - extern bool operator==( const Mapping::const_iterator &left, const Mapping::const_iterator &right ); - extern bool operator!=( const Mapping::const_iterator &left, const Mapping::const_iterator &right ); - - - // ================================================== - // class Dict - class Dict: public Mapping - { - public: - // Constructor - explicit Dict( PyObject *pyob, bool owned=false ) - : Mapping( pyob, owned ) - { - validate(); - } - - Dict( const Object &ob ) - : Mapping( ob ) - { - validate(); - } - - // Creation - Dict() - { - set( PyDict_New(), true ); - validate(); - } - - // Assignment acquires new ownership of pointer - Dict &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Dict &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && Py::_Dict_Check( pyob ); - } - }; - - class Callable: public Object - { - public: - // Constructor - explicit Callable() - : Object() - {} - - explicit Callable( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - Callable( const Object &ob ) - : Object( ob ) - { - validate(); - } - - // Assignment acquires new ownership of pointer - Callable &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Callable &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - // Membership - virtual bool accepts( PyObject *pyob ) const - { - return pyob && PyCallable_Check( pyob ); - } - - // Call - Object apply( const Tuple &args ) const - { - return asObject( PyObject_CallObject( ptr(), args.ptr() ) ); - } - - // Call with keywords - Object apply( const Tuple &args, const Dict &kw ) const - { - return asObject( PyEval_CallObjectWithKeywords( ptr(), args.ptr(), kw.ptr() ) ); - } - - Object apply( PyObject *pargs = 0 ) const - { - return apply( Tuple( pargs ) ); - } - }; - - class Module: public Object - { - public: - explicit Module( PyObject *pyob, bool owned = false ) - : Object( pyob, owned ) - { - validate(); - } - - // Construct from module name - explicit Module( const std::string &s ) - : Object() - { - PyObject *m = PyImport_AddModule( const_cast( s.c_str() ) ); - set( m, false ); - validate(); - } - - // Copy constructor acquires new ownership of pointer - Module( const Module &ob ) - : Object( *ob ) - { - validate(); - } - - Module &operator=( const Object &rhs ) - { - return *this = *rhs; - } - - Module &operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - return *this; - } - - Dict getDict() const - { - return Dict( PyModule_GetDict( ptr() ) ); - // Caution -- PyModule_GetDict returns borrowed reference! - } - }; - - // Call function helper - inline Object Object::callMemberFunction( const std::string &function_name ) const - { - Callable target( getAttr( function_name ) ); - Tuple args( 0 ); - return target.apply( args ); - } - - inline Object Object::callMemberFunction( const std::string &function_name, const Tuple &args ) const - { - Callable target( getAttr( function_name ) ); - return target.apply( args ); - } - - inline Object Object::callMemberFunction( const std::string &function_name, const Tuple &args, const Dict &kw ) const - { - Callable target( getAttr( function_name ) ); - return target.apply( args, kw ); - } - - // Numeric interface - inline Object operator+( const Object &a ) - { - return asObject( PyNumber_Positive( *a ) ); - } - - inline Object operator-( const Object &a ) - { - return asObject( PyNumber_Negative( *a ) ); - } - - inline Object abs( const Object &a ) - { - return asObject( PyNumber_Absolute( *a ) ); - } - - //------------------------------------------------------------ - // operator + - inline Object operator+( const Object &a, const Object &b ) - { - return asObject( PyNumber_Add( *a, *b ) ); - } - - inline Object operator+( const Object &a, int j ) - { - return asObject( PyNumber_Add( *a, *Long( j ) ) ); - } - - inline Object operator+( const Object &a, long j ) - { - return asObject( PyNumber_Add( *a, *Long( j ) ) ); - } - - inline Object operator+( const Object &a, double v ) - { - return asObject( PyNumber_Add( *a, *Float( v ) ) ); - } - - inline Object operator+( int j, const Object &b ) - { - return asObject( PyNumber_Add( *Long( j ), *b ) ); - } - - inline Object operator+( long j, const Object &b ) - { - return asObject( PyNumber_Add( *Long( j ), *b ) ); - } - - inline Object operator+( double v, const Object &b ) - { - return asObject( PyNumber_Add( *Float( v ), *b ) ); - } - - //------------------------------------------------------------ - // operator - - inline Object operator-( const Object &a, const Object &b ) - { - return asObject( PyNumber_Subtract( *a, *b ) ); - } - - inline Object operator-( const Object &a, int j ) - { - return asObject( PyNumber_Subtract( *a, *Long( j ) ) ); - } - - inline Object operator-( const Object &a, double v ) - { - return asObject( PyNumber_Subtract( *a, *Float( v ) ) ); - } - - inline Object operator-( int j, const Object &b ) - { - return asObject( PyNumber_Subtract( *Long( j ), *b ) ); - } - - inline Object operator-( double v, const Object &b ) - { - return asObject( PyNumber_Subtract( *Float( v ), *b ) ); - } - - //------------------------------------------------------------ - // operator * - inline Object operator*( const Object &a, const Object &b ) - { - return asObject( PyNumber_Multiply( *a, *b ) ); - } - - inline Object operator*( const Object &a, int j ) - { - return asObject( PyNumber_Multiply( *a, *Long( j ) ) ); - } - - inline Object operator*( const Object &a, double v ) - { - return asObject( PyNumber_Multiply( *a, *Float( v ) ) ); - } - - inline Object operator*( int j, const Object &b ) - { - return asObject( PyNumber_Multiply( *Long( j ), *b ) ); - } - - inline Object operator*( double v, const Object &b ) - { - return asObject( PyNumber_Multiply( *Float( v ), *b ) ); - } - - //------------------------------------------------------------ - // operator / - inline Object operator/( const Object &a, const Object &b ) - { - return asObject( PyNumber_TrueDivide( *a, *b ) ); - } - - inline Object operator/( const Object &a, int j ) - { - return asObject( PyNumber_TrueDivide( *a, *Long( j ) ) ); - } - - inline Object operator/( const Object &a, double v ) - { - return asObject( PyNumber_TrueDivide( *a, *Float( v ) ) ); - } - - inline Object operator/( int j, const Object &b ) - { - return asObject( PyNumber_TrueDivide( *Long( j ), *b ) ); - } - - inline Object operator/( double v, const Object &b ) - { - return asObject( PyNumber_TrueDivide( *Float( v ), *b ) ); - } - - //------------------------------------------------------------ - // operator % - inline Object operator%( const Object &a, const Object &b ) - { - return asObject( PyNumber_Remainder( *a, *b ) ); - } - - inline Object operator%( const Object &a, int j ) - { - return asObject( PyNumber_Remainder( *a, *Long( j ) ) ); - } - - inline Object operator%( const Object &a, double v ) - { - return asObject( PyNumber_Remainder( *a, *Float( v ) ) ); - } - - inline Object operator%( int j, const Object &b ) - { - return asObject( PyNumber_Remainder( *Long( j ), *b ) ); - } - - inline Object operator%( double v, const Object &b ) - { - return asObject( PyNumber_Remainder( *Float( v ), *b ) ); - } - - //------------------------------------------------------------ - // type - inline Object type( const Exception &) // return the type of the error - { - PyObject *ptype, *pvalue, *ptrace; - PyErr_Fetch( &ptype, &pvalue, &ptrace ); - Object result; - if( ptype ) - result = ptype; - PyErr_Restore( ptype, pvalue, ptrace ); - return result; - } - - inline Object value( const Exception &) // return the value of the error - { - PyObject *ptype, *pvalue, *ptrace; - PyErr_Fetch( &ptype, &pvalue, &ptrace ); - Object result; - if( pvalue ) - result = pvalue; - PyErr_Restore( ptype, pvalue, ptrace ); - return result; - } - - inline Object trace( const Exception &) // return the traceback of the error - { - PyObject *ptype, *pvalue, *ptrace; - PyErr_Fetch( &ptype, &pvalue, &ptrace ); - Object result; - if( ptrace ) - result = ptrace; - PyErr_Restore( ptype, pvalue, ptrace ); - return result; - } - - template - String seqref::str() const - { - return the_item.str(); - } - - template - String seqref::repr() const - { - return the_item.repr(); - } - -} // namespace Py -#endif // __CXX_Objects__h diff --git a/extern/CXX/Python3/PythonType.hxx b/extern/CXX/Python3/PythonType.hxx deleted file mode 100644 index bb77bb16ee93..000000000000 --- a/extern/CXX/Python3/PythonType.hxx +++ /dev/null @@ -1,114 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __CXX_PythonType__h -#define __CXX_PythonType__h - -namespace Py -{ - class PythonType - { - public: - // if you define one sequence method you must define - // all of them except the assigns - - PythonType( size_t base_size, int itemsize, const char *default_name ); - virtual ~PythonType(); - - const char *getName() const; - const char *getDoc() const; - - PyTypeObject *type_object() const; - PythonType &name( const char *nam ); - PythonType &doc( const char *d ); - - PythonType &supportClass( void ); -#ifdef PYCXX_PYTHON_2TO3 - PythonType &supportPrint( void ); -#endif - PythonType &supportGetattr( void ); - PythonType &supportSetattr( void ); - PythonType &supportGetattro( void ); - PythonType &supportSetattro( void ); -#ifdef PYCXX_PYTHON_2TO3 - PythonType &supportCompare( void ); -#endif - PythonType &supportRichCompare( void ); - PythonType &supportRepr( void ); - PythonType &supportStr( void ); - PythonType &supportHash( void ); - PythonType &supportCall( void ); - PythonType &supportIter( void ); - - PythonType &supportSequenceType( void ); - PythonType &supportMappingType( void ); - PythonType &supportNumberType( void ); - PythonType &supportBufferType( void ); - - PythonType &set_tp_dealloc( void (*tp_dealloc)( PyObject * ) ); - PythonType &set_tp_init( int (*tp_init)( PyObject *self, PyObject *args, PyObject *kwds ) ); - PythonType &set_tp_new( PyObject *(*tp_new)( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) ); - PythonType &set_methods( PyMethodDef *methods ); - - // call once all support functions have been called to ready the type - bool readyType(); - - protected: - void init_sequence(); - void init_mapping(); - void init_number(); - void init_buffer(); - - PyTypeObject *table; - PySequenceMethods *sequence_table; - PyMappingMethods *mapping_table; - PyNumberMethods *number_table; - PyBufferProcs *buffer_table; - - private: - // - // prevent the compiler generating these unwanted functions - // - PythonType( const PythonType &tb ); // unimplemented - void operator=( const PythonType &t ); // unimplemented - - }; - -} // Namespace Py - -// End of __CXX_PythonType__h -#endif diff --git a/extern/CXX/Python3/cxx_extensions.cxx b/extern/CXX/Python3/cxx_extensions.cxx deleted file mode 100644 index 8f2a4886c251..000000000000 --- a/extern/CXX/Python3/cxx_extensions.cxx +++ /dev/null @@ -1,1977 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/Extensions.hxx" -#include "CXX/Exception.hxx" - -#include - -#ifdef PYCXX_DEBUG -// -// Functions useful when debugging PyCXX -// -void bpt( void ) -{ -} - -void printRefCount( PyObject *obj ) -{ - std::cout << "RefCount of 0x" << std::hex << reinterpret_cast< unsigned int >( obj ) << std::dec << " is " << Py_REFCNT( obj ) << std::endl; -} -#endif - -namespace Py -{ - -void Object::validate() -{ - // release pointer if not the right type - if( !accepts( p ) ) - { -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - std::string s( "PyCXX: Error creating object of type " ); - s += (typeid( *this )).name(); - - if( p != NULL ) - { - String from_repr = repr(); - s += " from "; - s += from_repr.as_std_string(); - } - else - { - s += " from (nil)"; - } -#endif - release(); - if( PyErr_Occurred() ) - { // Error message already set - throw Exception(); - } - // Better error message if RTTI available -#if defined( _CPPRTTI ) || defined( __GNUG__ ) - throw TypeError( s ); -#else - throw TypeError( "PyCXX: type error." ); -#endif - } -} - -//================================================================================ -// -// Implementation of MethodTable -// -//================================================================================ - -PyMethodDef MethodTable::method( const char *method_name, PyCFunction f, int flags, const char *doc ) -{ - PyMethodDef m; - m.ml_name = const_cast( method_name ); - m.ml_meth = f; - m.ml_flags = flags; - m.ml_doc = const_cast( doc ); - return m; -} - -MethodTable::MethodTable() -{ - t.push_back( method( 0, 0, 0, 0 ) ); - mt = NULL; -} - -MethodTable::~MethodTable() -{ - delete [] mt; -} - -void MethodTable::add( const char *method_name, PyCFunction f, const char *doc, int flag ) -{ - if( !mt ) - { - t.insert( t.end()-1, method( method_name, f, flag, doc ) ); - } - else - { - throw RuntimeError( "Too late to add a module method!" ); - } -} - -PyMethodDef *MethodTable::table() -{ - if( !mt ) - { - Py_ssize_t t1size = t.size(); - mt = new PyMethodDef[ t1size ]; - int j = 0; - for( std::vector::iterator i = t.begin(); i != t.end(); i++ ) - { - mt[ j++ ] = *i; - } - } - return mt; -} - -//================================================================================ -// -// Implementation of ExtensionModule -// -//================================================================================ -ExtensionModuleBase::ExtensionModuleBase( const char *name ) -: m_module_name( name ) -, m_full_module_name( __Py_PackageContext() != NULL ? std::string( __Py_PackageContext() ) : m_module_name ) -, m_method_table() -//m_module_def -, m_module( NULL ) -{} - -ExtensionModuleBase::~ExtensionModuleBase() -{} - -const std::string &ExtensionModuleBase::name() const -{ - return m_module_name; -} - -const std::string &ExtensionModuleBase::fullName() const -{ - return m_full_module_name; -} - -class ExtensionModuleBasePtr : public PythonExtension -{ -public: - ExtensionModuleBasePtr( ExtensionModuleBase *_module ) - : module( _module ) - {} - - virtual ~ExtensionModuleBasePtr() - {} - - ExtensionModuleBase *module; -}; - -void ExtensionModuleBase::initialize( const char *module_doc ) -{ - memset( &m_module_def, 0, sizeof( m_module_def ) ); - - m_module_def.m_name = const_cast( m_module_name.c_str() ); - m_module_def.m_doc = const_cast( module_doc ); - m_module_def.m_methods = m_method_table.table(); - // where does module_ptr get passed in? - - m_module = PyModule_Create( &m_module_def ); -} - -Py::Module ExtensionModuleBase::module( void ) const -{ - return Module( m_module ); -} - -Py::Dict ExtensionModuleBase::moduleDictionary( void ) const -{ - return module().getDict(); -} - -//================================================================================ -// -// Implementation of PythonType -// -//================================================================================ -extern "C" -{ - static void standard_dealloc( PyObject *p ); - // - // All the following functions redirect the call from Python - // onto the matching virtual function in PythonExtensionBase - // - static int print_handler( PyObject *, FILE *, int ); - static PyObject *getattr_handler( PyObject *, char * ); - static int setattr_handler( PyObject *, char *, PyObject * ); - static PyObject *getattro_handler( PyObject *, PyObject * ); - static int setattro_handler( PyObject *, PyObject *, PyObject * ); - static PyObject *rich_compare_handler( PyObject *, PyObject *, int ); - static PyObject *repr_handler( PyObject * ); - static PyObject *str_handler( PyObject * ); - static Py_hash_t hash_handler( PyObject * ); - static PyObject *call_handler( PyObject *, PyObject *, PyObject * ); - static PyObject *iter_handler( PyObject * ); - static PyObject *iternext_handler( PyObject * ); - - // Sequence methods - static Py_ssize_t sequence_length_handler( PyObject * ); - static PyObject *sequence_concat_handler( PyObject *,PyObject * ); - static PyObject *sequence_repeat_handler( PyObject *, Py_ssize_t ); - static PyObject *sequence_item_handler( PyObject *, Py_ssize_t ); - static int sequence_ass_item_handler( PyObject *, Py_ssize_t, PyObject * ); - - // Mapping - static Py_ssize_t mapping_length_handler( PyObject * ); - static PyObject *mapping_subscript_handler( PyObject *, PyObject * ); - static int mapping_ass_subscript_handler( PyObject *, PyObject *, PyObject * ); - - // Numeric methods - static PyObject *number_negative_handler( PyObject * ); - static PyObject *number_positive_handler( PyObject * ); - static PyObject *number_absolute_handler( PyObject * ); - static PyObject *number_invert_handler( PyObject * ); - static PyObject *number_int_handler( PyObject * ); - static PyObject *number_float_handler( PyObject * ); - static PyObject *number_add_handler( PyObject *, PyObject * ); - static PyObject *number_subtract_handler( PyObject *, PyObject * ); - static PyObject *number_multiply_handler( PyObject *, PyObject * ); - static PyObject *number_remainder_handler( PyObject *, PyObject * ); - static PyObject *number_divmod_handler( PyObject *, PyObject * ); - static PyObject *number_lshift_handler( PyObject *, PyObject * ); - static PyObject *number_rshift_handler( PyObject *, PyObject * ); - static PyObject *number_and_handler( PyObject *, PyObject * ); - static PyObject *number_xor_handler( PyObject *, PyObject * ); - static PyObject *number_or_handler( PyObject *, PyObject * ); - static PyObject *number_power_handler( PyObject *, PyObject *, PyObject * ); - - // Buffer - static int buffer_get_handler( PyObject *, Py_buffer *, int ); - static void buffer_release_handler( PyObject *, Py_buffer * ); -} - -extern "C" void standard_dealloc( PyObject *p ) -{ - PyMem_DEL( p ); -} - -bool PythonType::readyType() -{ - return PyType_Ready( table ) >= 0; -} - -PythonType &PythonType::supportSequenceType() -{ - if( !sequence_table ) - { - sequence_table = new PySequenceMethods; - memset( sequence_table, 0, sizeof( PySequenceMethods ) ); // ensure new fields are 0 - table->tp_as_sequence = sequence_table; - sequence_table->sq_length = sequence_length_handler; - sequence_table->sq_concat = sequence_concat_handler; - sequence_table->sq_repeat = sequence_repeat_handler; - sequence_table->sq_item = sequence_item_handler; - - sequence_table->sq_ass_item = sequence_ass_item_handler; // BAS setup seperately? - // QQQ sq_inplace_concat - // QQQ sq_inplace_repeat - } - return *this; -} - -PythonType &PythonType::supportMappingType() -{ - if( !mapping_table ) - { - mapping_table = new PyMappingMethods; - memset( mapping_table, 0, sizeof( PyMappingMethods ) ); // ensure new fields are 0 - table->tp_as_mapping = mapping_table; - mapping_table->mp_length = mapping_length_handler; - mapping_table->mp_subscript = mapping_subscript_handler; - mapping_table->mp_ass_subscript = mapping_ass_subscript_handler; // BAS setup seperately? - } - return *this; -} - -PythonType &PythonType::supportNumberType() -{ - if( !number_table ) - { - number_table = new PyNumberMethods; - memset( number_table, 0, sizeof( PyNumberMethods ) ); // ensure new fields are 0 - table->tp_as_number = number_table; - number_table->nb_add = number_add_handler; - number_table->nb_subtract = number_subtract_handler; - number_table->nb_multiply = number_multiply_handler; - number_table->nb_remainder = number_remainder_handler; - number_table->nb_divmod = number_divmod_handler; - number_table->nb_power = number_power_handler; - number_table->nb_negative = number_negative_handler; - number_table->nb_positive = number_positive_handler; - number_table->nb_absolute = number_absolute_handler; - number_table->nb_invert = number_invert_handler; - number_table->nb_lshift = number_lshift_handler; - number_table->nb_rshift = number_rshift_handler; - number_table->nb_and = number_and_handler; - number_table->nb_xor = number_xor_handler; - number_table->nb_or = number_or_handler; - number_table->nb_int = number_int_handler; - number_table->nb_float = number_float_handler; - - // QQQ lots of new methods to add - } - return *this; -} - -PythonType &PythonType::supportBufferType() -{ - if( !buffer_table ) - { - buffer_table = new PyBufferProcs; - memset( buffer_table, 0, sizeof( PyBufferProcs ) ); // ensure new fields are 0 - table->tp_as_buffer = buffer_table; - buffer_table->bf_getbuffer = buffer_get_handler; - buffer_table->bf_releasebuffer = buffer_release_handler; - } - return *this; -} - -// if you define one sequence method you must define -// all of them except the assigns - -PythonType::PythonType( size_t basic_size, int itemsize, const char *default_name ) -: table( new PyTypeObject ) -, sequence_table( NULL ) -, mapping_table( NULL ) -, number_table( NULL ) -, buffer_table( NULL ) -{ - // PyTypeObject is defined in /Include/object.h - - memset( table, 0, sizeof( PyTypeObject ) ); // ensure new fields are 0 - *reinterpret_cast( table ) = py_object_initializer; - reinterpret_cast( table )->ob_type = _Type_Type(); - // QQQ table->ob_size = 0; - table->tp_name = const_cast( default_name ); - table->tp_basicsize = basic_size; - table->tp_itemsize = itemsize; - - // Methods to implement standard operations - table->tp_dealloc = (destructor)standard_dealloc; - table->tp_print = 0; - table->tp_getattr = 0; - table->tp_setattr = 0; - table->tp_repr = 0; - - // Method suites for standard classes - table->tp_as_number = 0; - table->tp_as_sequence = 0; - table->tp_as_mapping = 0; - - // More standard operations (here for binary compatibility) - table->tp_hash = 0; - table->tp_call = 0; - table->tp_str = 0; - table->tp_getattro = 0; - table->tp_setattro = 0; - - // Functions to access object as input/output buffer - table->tp_as_buffer = 0; - - // Flags to define presence of optional/expanded features - table->tp_flags = Py_TPFLAGS_DEFAULT; - - // Documentation string - table->tp_doc = 0; - - table->tp_traverse = 0; - - // delete references to contained objects - table->tp_clear = 0; - - // Assigned meaning in release 2.1 - // rich comparisons - table->tp_richcompare = 0; - // weak reference enabler - table->tp_weaklistoffset = 0; - - // Iterators - table->tp_iter = 0; - table->tp_iternext = 0; - - // Attribute descriptor and subclassing stuff - table->tp_methods = 0; - table->tp_members = 0; - table->tp_getset = 0; - table->tp_base = 0; - table->tp_dict = 0; - table->tp_descr_get = 0; - table->tp_descr_set = 0; - table->tp_dictoffset = 0; - table->tp_init = 0; - table->tp_alloc = 0; - table->tp_new = 0; - table->tp_free = 0; // Low-level free-memory routine - table->tp_is_gc = 0; // For PyObject_IS_GC - table->tp_bases = 0; - table->tp_mro = 0; // method resolution order - table->tp_cache = 0; - table->tp_subclasses = 0; - table->tp_weaklist = 0; - table->tp_del = 0; - - // Type attribute cache version tag. Added in version 2.6 - table->tp_version_tag = 0; - -#ifdef COUNT_ALLOCS - table->tp_alloc = 0; - table->tp_free = 0; - table->tp_maxalloc = 0; - table->tp_orev = 0; - table->tp_next = 0; -#endif -} - -PythonType::~PythonType() -{ - delete table; - delete sequence_table; - delete mapping_table; - delete number_table; - delete buffer_table; -} - -PyTypeObject *PythonType::type_object() const -{ - return table; -} - -PythonType &PythonType::name( const char *nam ) -{ - table->tp_name = const_cast( nam ); - return *this; -} - -const char *PythonType::getName() const -{ - return table->tp_name; -} - -PythonType &PythonType::doc( const char *d ) -{ - table->tp_doc = const_cast( d ); - return *this; -} - -const char *PythonType::getDoc() const -{ - return table->tp_doc; -} - -PythonType &PythonType::set_tp_dealloc( void (*tp_dealloc)( PyObject *self ) ) -{ - table->tp_dealloc = tp_dealloc; - return *this; -} - -PythonType &PythonType::set_tp_init( int (*tp_init)( PyObject *self, PyObject *args, PyObject *kwds ) ) -{ - table->tp_init = tp_init; - return *this; -} - -PythonType &PythonType::set_tp_new( PyObject *(*tp_new)( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) ) -{ - table->tp_new = tp_new; - return *this; -} - -PythonType &PythonType::set_methods( PyMethodDef *methods ) -{ - table->tp_methods = methods; - return *this; -} - -PythonType &PythonType::supportClass() -{ - table->tp_flags |= Py_TPFLAGS_BASETYPE; - return *this; -} - -#ifdef PYCXX_PYTHON_2TO3 -PythonType &PythonType::supportPrint() -{ - table->tp_print = print_handler; - return *this; -} -#endif - -PythonType &PythonType::supportGetattr() -{ - table->tp_getattr = getattr_handler; - return *this; -} - -PythonType &PythonType::supportSetattr() -{ - table->tp_setattr = setattr_handler; - return *this; -} - -PythonType &PythonType::supportGetattro() -{ - table->tp_getattro = getattro_handler; - return *this; -} - -PythonType &PythonType::supportSetattro() -{ - table->tp_setattro = setattro_handler; - return *this; -} - -#ifdef PYCXX_PYTHON_2TO3 -PythonType &PythonType::supportCompare( void ) -{ - return *this; -} -#endif - - -PythonType &PythonType::supportRichCompare() -{ - table->tp_richcompare = rich_compare_handler; - return *this; -} - -PythonType &PythonType::supportRepr() -{ - table->tp_repr = repr_handler; - return *this; -} - -PythonType &PythonType::supportStr() -{ - table->tp_str = str_handler; - return *this; -} - -PythonType &PythonType::supportHash() -{ - table->tp_hash = hash_handler; - return *this; -} - -PythonType &PythonType::supportCall() -{ - table->tp_call = call_handler; - return *this; -} - -PythonType &PythonType::supportIter() -{ - table->tp_iter = iter_handler; - table->tp_iternext = iternext_handler; - return *this; -} - -//-------------------------------------------------------------------------------- -// -// Handlers -// -//-------------------------------------------------------------------------------- -PythonExtensionBase *getPythonExtensionBase( PyObject *self ) -{ - if( self->ob_type->tp_flags&Py_TPFLAGS_BASETYPE ) - { - PythonClassInstance *instance = reinterpret_cast( self ); - return instance->m_pycxx_object; - } - else - { - return static_cast( self ); - } -} - -#ifdef PYCXX_PYTHON_2TO3 -extern "C" int print_handler( PyObject *self, FILE *fp, int flags ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->print( fp, flags ); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} -#endif - -extern "C" PyObject *getattr_handler( PyObject *self, char *name ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->getattr( name ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" int setattr_handler( PyObject *self, char *name, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->setattr( name, Py::Object( value ) ); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -extern "C" PyObject *getattro_handler( PyObject *self, PyObject *name ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->getattro( Py::String( name ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" int setattro_handler( PyObject *self, PyObject *name, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->setattro( Py::String( name ), Py::Object( value ) ); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -extern "C" PyObject *rich_compare_handler( PyObject *self, PyObject *other, int op ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->rich_compare( Py::Object( other ), op ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *repr_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->repr() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *str_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->str() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" Py_hash_t hash_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->hash(); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -extern "C" PyObject *call_handler( PyObject *self, PyObject *args, PyObject *kw ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - if( kw != NULL ) - return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) ); - else - return new_reference_to( p->call( Py::Object( args ), Py::Object() ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *iter_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->iter() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *iternext_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->iternext(); // might be a NULL ptr on end of iteration - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - - -// Sequence methods -extern "C" Py_ssize_t sequence_length_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->sequence_length(); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -extern "C" PyObject *sequence_concat_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_concat( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *sequence_repeat_handler( PyObject *self, Py_ssize_t count ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_repeat( count ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *sequence_item_handler( PyObject *self, Py_ssize_t index ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_item( index ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" int sequence_ass_item_handler( PyObject *self, Py_ssize_t index, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->sequence_ass_item( index, Py::Object( value ) ); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -// Mapping -extern "C" Py_ssize_t mapping_length_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->mapping_length(); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -extern "C" PyObject *mapping_subscript_handler( PyObject *self, PyObject *key ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->mapping_subscript( Py::Object( key ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" int mapping_ass_subscript_handler( PyObject *self, PyObject *key, PyObject *value ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->mapping_ass_subscript( Py::Object( key ), Py::Object( value ) ); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -// Number -extern "C" PyObject *number_negative_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_negative() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_positive_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_positive() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_absolute_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_absolute() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_invert_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_invert() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_int_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_int() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_float_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_float() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_add_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_add( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_subtract_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_subtract( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_multiply_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_multiply( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_remainder_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_remainder( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_divmod_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_divmod( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_lshift_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_lshift( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_rshift_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_rshift( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_and_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_and( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_xor_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_xor( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_or_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_or( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_power_handler( PyObject *self, PyObject *x1, PyObject *x2 ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_power( Py::Object( x1 ), Py::Object( x2 ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -// Buffer -extern "C" int buffer_get_handler( PyObject *self, Py_buffer *buf, int flags ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->buffer_get( buf, flags ); - } - catch( Py::Exception & ) - { - return -1; // indicate error - } -} - -extern "C" void buffer_release_handler( PyObject *self, Py_buffer *buf ) -{ - PythonExtensionBase *p = getPythonExtensionBase( self ); - p->buffer_release( buf ); - // NOTE: No way to indicate error to Python -} - -//================================================================================ -// -// Implementation of PythonExtensionBase -// -//================================================================================ -#define missing_method( method ) \ - throw RuntimeError( "Extension object missing implement of " #method ); - -PythonExtensionBase::PythonExtensionBase() -{ - ob_refcnt = 0; -} - -PythonExtensionBase::~PythonExtensionBase() -{ - assert( ob_refcnt == 0 ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name ) -{ - Py::TupleN args; - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1 ) -{ - Py::TupleN args( arg1 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2 ) -{ - Py::TupleN args( arg1, arg2 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3 ) -{ - Py::TupleN args( arg1, arg2, arg3 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7, const Py::Object &arg8 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 ); - return self().callMemberFunction( fn_name, args ); -} - -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7, const Py::Object &arg8, const Py::Object &arg9 ) -{ - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 ); - return self().callMemberFunction( fn_name, args ); -} - -void PythonExtensionBase::reinit( Tuple &args, Dict &kwds ) -{ - throw RuntimeError( "Must not call __init__ twice on this class" ); -} - - -Py::Object PythonExtensionBase::genericGetAttro( const Py::String &name ) -{ - return asObject( PyObject_GenericGetAttr( selfPtr(), name.ptr() ) ); -} - -int PythonExtensionBase::genericSetAttro( const Py::String &name, const Py::Object &value ) -{ - return PyObject_GenericSetAttr( selfPtr(), name.ptr(), value.ptr() ); -} - -#ifdef PYCXX_PYTHON_2TO3 -int PythonExtensionBase::print( FILE *, int ) -{ - missing_method( print ); - return -1; -} -#endif - -Py::Object PythonExtensionBase::getattr( const char * ) -{ - missing_method( getattr ); - return Py::None(); -} - -int PythonExtensionBase::setattr( const char *, const Py::Object & ) -{ - missing_method( setattr ); - return -1; -} - -Py::Object PythonExtensionBase::getattro( const Py::String &name ) -{ - return asObject( PyObject_GenericGetAttr( selfPtr(), name.ptr() ) ); -} - -int PythonExtensionBase::setattro( const Py::String &name, const Py::Object &value ) -{ - return PyObject_GenericSetAttr( selfPtr(), name.ptr(), value.ptr() ); -} - - -int PythonExtensionBase::compare( const Py::Object & ) -{ - missing_method( compare ); - return -1; -} - -Py::Object PythonExtensionBase::rich_compare( const Py::Object &, int ) -{ - missing_method( rich_compare ); - return Py::None(); -} - -Py::Object PythonExtensionBase::repr() -{ - missing_method( repr ); - return Py::None(); -} - -Py::Object PythonExtensionBase::str() -{ - missing_method( str ); - return Py::None(); -} - -Py_hash_t PythonExtensionBase::hash() -{ - missing_method( hash ); - return -1; } - - -Py::Object PythonExtensionBase::call( const Py::Object &, const Py::Object & ) -{ - missing_method( call ); - return Py::None(); -} - -Py::Object PythonExtensionBase::iter() -{ - missing_method( iter ); - return Py::None(); -} - -PyObject *PythonExtensionBase::iternext() -{ - missing_method( iternext ); - return NULL; } - - - -// Sequence methods -int PythonExtensionBase::sequence_length() -{ - missing_method( sequence_length ); - return -1; } - - -Py::Object PythonExtensionBase::sequence_concat( const Py::Object & ) -{ - missing_method( sequence_concat ); - return Py::None(); -} - -Py::Object PythonExtensionBase::sequence_repeat( Py_ssize_t ) -{ - missing_method( sequence_repeat ); - return Py::None(); -} - -Py::Object PythonExtensionBase::sequence_item( Py_ssize_t ) -{ - missing_method( sequence_item ); - return Py::None(); -} - -int PythonExtensionBase::sequence_ass_item( Py_ssize_t, const Py::Object & ) -{ - missing_method( sequence_ass_item ); - return -1; -} - - -// Mapping -int PythonExtensionBase::mapping_length() -{ - missing_method( mapping_length ); - return -1; -} - - -Py::Object PythonExtensionBase::mapping_subscript( const Py::Object & ) -{ - missing_method( mapping_subscript ); - return Py::None(); -} - -int PythonExtensionBase::mapping_ass_subscript( const Py::Object &, const Py::Object & ) -{ - missing_method( mapping_ass_subscript ); - return -1; -} - -Py::Object PythonExtensionBase::number_negative() -{ - missing_method( number_negative ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_positive() -{ - missing_method( number_positive ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_absolute() -{ - missing_method( number_absolute ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_invert() -{ - missing_method( number_invert ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_int() -{ - missing_method( number_int ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_float() -{ - missing_method( number_float ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_long() -{ - missing_method( number_long ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_add( const Py::Object & ) -{ - missing_method( number_add ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_subtract( const Py::Object & ) -{ - missing_method( number_subtract ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_multiply( const Py::Object & ) -{ - missing_method( number_multiply ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_remainder( const Py::Object & ) -{ - missing_method( number_remainder ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_divmod( const Py::Object & ) -{ - missing_method( number_divmod ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_lshift( const Py::Object & ) -{ - missing_method( number_lshift ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_rshift( const Py::Object & ) -{ - missing_method( number_rshift ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_and( const Py::Object & ) -{ - missing_method( number_and ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_xor( const Py::Object & ) -{ - missing_method( number_xor ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_or( const Py::Object & ) -{ - missing_method( number_or ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_power( const Py::Object &, const Py::Object & ) -{ - missing_method( number_power ); - return Py::None(); -} - - -// Buffer -int PythonExtensionBase::buffer_get( Py_buffer *buf, int flags ) -{ - missing_method( buffer_get ); - return -1; -} - -int PythonExtensionBase::buffer_release( Py_buffer *buf ) -{ - /* This method is optional and only required if the buffer's - memory is dynamic. */ - return 0; -} - -//-------------------------------------------------------------------------------- -// -// Method call handlers for -// PythonExtensionBase -// ExtensionModuleBase -// -//-------------------------------------------------------------------------------- -// Note: Python calls noargs as varargs buts args==NULL -extern "C" PyObject *method_noargs_call_handler( PyObject *_self_and_name_tuple, PyObject * ) -{ - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - void *self_as_void = PyCapsule_GetPointer( self_in_cobject, NULL ); - if( self_as_void == NULL ) - return NULL; - - ExtensionModuleBase *self = static_cast( self_as_void ); - - Object result( self->invoke_method_noargs( PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ) ) ); - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } -} - -extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ) -{ - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - void *self_as_void = PyCapsule_GetPointer( self_in_cobject, NULL ); - if( self_as_void == NULL ) - return NULL; - - ExtensionModuleBase *self = static_cast( self_as_void ); - Tuple args( _args ); - Object result - ( - self->invoke_method_varargs - ( - PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ), - args - ) - ); - - return new_reference_to( result.ptr() ); - } - catch( Exception & ) - { - return 0; - } -} - -extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ) -{ - try - { - Tuple self_and_name_tuple( _self_and_name_tuple ); - - PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); - void *self_as_void = PyCapsule_GetPointer( self_in_cobject, NULL ); - if( self_as_void == NULL ) - return NULL; - - ExtensionModuleBase *self = static_cast( self_as_void ); - - Tuple args( _args ); - - if( _keywords == NULL ) - { - Dict keywords; // pass an empty dict - - Object result - ( - self->invoke_method_keyword - ( - PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ), - args, - keywords - ) - ); - - return new_reference_to( result.ptr() ); - } - else - { - Dict keywords( _keywords ); // make dict - - Object result - ( - self->invoke_method_keyword - ( - PyCapsule_GetPointer( self_and_name_tuple[1].ptr(), NULL ), - args, - keywords - ) - ); - - return new_reference_to( result.ptr() ); - } - } - catch( Exception & ) - { - return 0; - } -} - - -//-------------------------------------------------------------------------------- -// -// ExtensionExceptionType -// -//-------------------------------------------------------------------------------- -ExtensionExceptionType::ExtensionExceptionType() - : Py::Object() -{ -} - -void ExtensionExceptionType::init( ExtensionModuleBase &module, const std::string& name ) -{ - std::string module_name( module.fullName() ); - module_name += "."; - module_name += name; - - set( PyErr_NewException( const_cast( module_name.c_str() ), NULL, NULL ), true ); -} - -void ExtensionExceptionType::init( ExtensionModuleBase &module, const std::string& name, ExtensionExceptionType &parent ) - { - std::string module_name( module.fullName() ); - module_name += "."; - module_name += name; - - set( PyErr_NewException( const_cast( module_name.c_str() ), parent.ptr(), NULL ), true ); -} - -ExtensionExceptionType::~ExtensionExceptionType() -{ -} - -Exception::Exception( ExtensionExceptionType &exception, const std::string& reason ) -{ - PyErr_SetString( exception.ptr(), reason.c_str() ); -} - -Exception::Exception( ExtensionExceptionType &exception, Object &reason ) -{ - PyErr_SetObject( exception.ptr(), reason.ptr() ); -} - -Exception::Exception( PyObject *exception, Object &reason ) -{ - PyErr_SetObject( exception, reason.ptr() ); -} - -#if 1 -//------------------------------------------------------------ -// compare operators -bool operator!=( const Long &a, const Long &b ) -{ - return a.as_long() != b.as_long(); -} - -bool operator!=( const Long &a, int b ) -{ - return a.as_long() != b; -} - -bool operator!=( const Long &a, long b ) -{ - return a.as_long() != b; -} - -bool operator!=( int a, const Long &b ) -{ - return a != b.as_long(); -} - -bool operator!=( long a, const Long &b ) -{ - return a != b.as_long(); -} - -//------------------------------ -bool operator==( const Long &a, const Long &b ) -{ - return a.as_long() == b.as_long(); -} - -bool operator==( const Long &a, int b ) -{ - return a.as_long() == b; -} - -bool operator==( const Long &a, long b ) -{ - return a.as_long() == b; -} - -bool operator==( int a, const Long &b ) -{ - return a == b.as_long(); -} - -bool operator==( long a, const Long &b ) -{ - return a == b.as_long(); -} - -//------------------------------ -bool operator>( const Long &a, const Long &b ) -{ - return a.as_long() > b.as_long(); -} - -bool operator>( const Long &a, int b ) -{ - return a.as_long() > b; -} - -bool operator>( const Long &a, long b ) -{ - return a.as_long() > b; -} - -bool operator>( int a, const Long &b ) -{ - return a > b.as_long(); -} - -bool operator>( long a, const Long &b ) -{ - return a > b.as_long(); -} - -//------------------------------ -bool operator>=( const Long &a, const Long &b ) -{ - return a.as_long() >= b.as_long(); -} - -bool operator>=( const Long &a, int b ) -{ - return a.as_long() >= b; -} - -bool operator>=( const Long &a, long b ) -{ - return a.as_long() >= b; -} - -bool operator>=( int a, const Long &b ) -{ - return a >= b.as_long(); -} - -bool operator>=( long a, const Long &b ) -{ - return a >= b.as_long(); -} - -//------------------------------ -bool operator<( const Long &a, const Long &b ) -{ - return a.as_long() < b.as_long(); -} - -bool operator<( const Long &a, int b ) -{ - return a.as_long() < b; -} - -bool operator<( const Long &a, long b ) -{ - return a.as_long() < b; -} - -bool operator<( int a, const Long &b ) -{ - return a < b.as_long(); -} - -bool operator<( long a, const Long &b ) -{ - return a < b.as_long(); -} - -//------------------------------ -bool operator<=( const Long &a, const Long &b ) -{ - return a.as_long() <= b.as_long(); -} - -bool operator<=( int a, const Long &b ) -{ - return a <= b.as_long(); -} - -bool operator<=( long a, const Long &b ) -{ - return a <= b.as_long(); -} - -bool operator<=( const Long &a, int b ) -{ - return a.as_long() <= b; -} - -bool operator<=( const Long &a, long b ) -{ - return a.as_long() <= b; -} - -#ifdef HAVE_LONG_LONG -//------------------------------ -bool operator!=( const Long &a, PY_LONG_LONG b ) -{ - return a.as_long_long() != b; -} - -bool operator!=( PY_LONG_LONG a, const Long &b ) -{ - return a != b.as_long_long(); -} - -//------------------------------ -bool operator==( const Long &a, PY_LONG_LONG b ) -{ - return a.as_long_long() == b; -} - -bool operator==( PY_LONG_LONG a, const Long &b ) -{ - return a == b.as_long_long(); -} - -//------------------------------ -bool operator>( const Long &a, PY_LONG_LONG b ) -{ - return a.as_long_long() > b; -} - -bool operator>( PY_LONG_LONG a, const Long &b ) -{ - return a > b.as_long_long(); -} - -//------------------------------ -bool operator>=( const Long &a, PY_LONG_LONG b ) -{ - return a.as_long_long() >= b; -} - -bool operator>=( PY_LONG_LONG a, const Long &b ) -{ - return a >= b.as_long_long(); -} - -//------------------------------ -bool operator<( const Long &a, PY_LONG_LONG b ) -{ - return a.as_long_long() < b; -} - -bool operator<( PY_LONG_LONG a, const Long &b ) -{ - return a < b.as_long_long(); -} - -//------------------------------ -bool operator<=( const Long &a, PY_LONG_LONG b ) -{ - return a.as_long_long() <= b; -} - -bool operator<=( PY_LONG_LONG a, const Long &b ) -{ - return a <= b.as_long_long(); -} -#endif -#endif - -//------------------------------------------------------------ -// compare operators -bool operator!=( const Float &a, const Float &b ) -{ - return a.as_double() != b.as_double(); -} - -bool operator!=( const Float &a, double b ) -{ - return a.as_double() != b; -} - -bool operator!=( double a, const Float &b ) -{ - return a != b.as_double(); -} - -//------------------------------ -bool operator==( const Float &a, const Float &b ) -{ - return a.as_double() == b.as_double(); -} - -bool operator==( const Float &a, double b ) -{ - return a.as_double() == b; -} - -bool operator==( double a, const Float &b ) -{ - return a == b.as_double(); -} - -//------------------------------ -bool operator>( const Float &a, const Float &b ) -{ - return a.as_double() > b.as_double(); -} - -bool operator>( const Float &a, double b ) -{ - return a.as_double() > b; -} - -bool operator>( double a, const Float &b ) -{ - return a > b.as_double(); -} - -//------------------------------ -bool operator>=( const Float &a, const Float &b ) -{ - return a.as_double() >= b.as_double(); -} - -bool operator>=( const Float &a, double b ) -{ - return a.as_double() >= b; -} - -bool operator>=( double a, const Float &b ) -{ - return a >= b.as_double(); -} - -//------------------------------ -bool operator<( const Float &a, const Float &b ) -{ - return a.as_double() < b.as_double(); -} - -bool operator<( const Float &a, double b ) -{ - return a.as_double() < b; -} - -bool operator<( double a, const Float &b ) -{ - return a < b.as_double(); -} - -//------------------------------ -bool operator<=( const Float &a, const Float &b ) -{ - return a.as_double() <= b.as_double(); -} - -bool operator<=( double a, const Float &b ) -{ - return a <= b.as_double(); -} - -bool operator<=( const Float &a, double b ) -{ - return a.as_double() <= b; -} - -} // end of namespace Py diff --git a/extern/CXX/Python3/cxxextensions.c b/extern/CXX/Python3/cxxextensions.c deleted file mode 100644 index 7feb1e0db278..000000000000 --- a/extern/CXX/Python3/cxxextensions.c +++ /dev/null @@ -1,54 +0,0 @@ -/*---------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//---------------------------------------------------------------------------*/ - -#include "CXX/WrapPython.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -PyObject py_object_initializer = - { - _PyObject_EXTRA_INIT - 1, - NULL // type must be init'ed by user - }; - -#ifdef __cplusplus -} -#endif diff --git a/extern/CXX/Python3/cxxsupport.cxx b/extern/CXX/Python3/cxxsupport.cxx deleted file mode 100644 index 442d932b2b3e..000000000000 --- a/extern/CXX/Python3/cxxsupport.cxx +++ /dev/null @@ -1,228 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#include "CXX/Objects.hxx" -namespace Py -{ - -Py_UNICODE unicode_null_string[1] = { 0 }; - -Type Object::type() const -{ - return Type( PyObject_Type( p ), true ); -} - -String Object::str() const -{ - return String( PyObject_Str( p ), true ); -} - -String Object::repr() const -{ - return String( PyObject_Repr( p ), true ); -} - -std::string Object::as_string() const -{ - return static_cast( str() ); -} - -List Object::dir() const -{ - return List( PyObject_Dir( p ), true ); -} - -bool Object::isType( const Type &t ) const -{ - return type().ptr() == t.ptr(); -} - -Char::operator String() const -{ - return String( ptr() ); -} - -String Bytes::decode( const char *encoding, const char *error ) -{ - return String( PyUnicode_FromEncodedObject( ptr(), encoding, error ), true ); -} - -// Object compares -bool operator==( const Object &o1, const Object &o2 ) -{ - int k = PyObject_RichCompareBool( *o1, *o2, Py_EQ ); - if( PyErr_Occurred() ) - throw Exception(); - return k != 0; -} - -bool operator!=( const Object &o1, const Object &o2 ) -{ - int k = PyObject_RichCompareBool( *o1, *o2, Py_NE ); - if( PyErr_Occurred() ) - throw Exception(); - return k != 0; - -} - -bool operator>=( const Object &o1, const Object &o2 ) -{ - int k = PyObject_RichCompareBool( *o1, *o2, Py_GE ); - if( PyErr_Occurred() ) - throw Exception(); - return k != 0; -} - -bool operator<=( const Object &o1, const Object &o2 ) -{ - int k = PyObject_RichCompareBool( *o1, *o2, Py_LE ); - if( PyErr_Occurred() ) - throw Exception(); - return k != 0; -} - -bool operator<( const Object &o1, const Object &o2 ) -{ - int k = PyObject_RichCompareBool( *o1, *o2, Py_LT ); - if( PyErr_Occurred() ) - throw Exception(); - return k != 0; -} - -bool operator>( const Object &o1, const Object &o2 ) -{ - int k = PyObject_RichCompareBool( *o1, *o2, Py_GT ); - if( PyErr_Occurred() ) - throw Exception(); - return k != 0; -} - -// iterator compares -bool operator==( const Sequence::iterator &left, const Sequence::iterator &right ) -{ - return left.eql( right ); -} - -bool operator!=( const Sequence::iterator &left, const Sequence::iterator &right ) -{ - return left.neq( right ); -} - -bool operator<( const Sequence::iterator &left, const Sequence::iterator &right ) -{ - return left.lss( right ); -} - -bool operator>( const Sequence::iterator &left, const Sequence::iterator &right ) -{ - return left.gtr( right ); -} - -bool operator<=( const Sequence::iterator &left, const Sequence::iterator &right ) -{ - return left.leq( right ); -} - -bool operator>=( const Sequence::iterator &left, const Sequence::iterator &right ) -{ - return left.geq( right ); -} - -// const_iterator compares -bool operator==( const Sequence::const_iterator &left, const Sequence::const_iterator &right ) -{ - return left.eql( right ); -} - -bool operator!=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ) -{ - return left.neq( right ); -} - -bool operator<( const Sequence::const_iterator &left, const Sequence::const_iterator &right ) -{ - return left.lss( right ); -} - -bool operator>( const Sequence::const_iterator &left, const Sequence::const_iterator &right ) -{ - return left.gtr( right ); -} - -bool operator<=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ) -{ - return left.leq( right ); -} - -bool operator>=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ) -{ - return left.geq( right ); -} - -// For mappings: -bool operator==( const Mapping::iterator &left, const Mapping::iterator &right ) -{ - return left.eql( right ); -} - -bool operator!=( const Mapping::iterator &left, const Mapping::iterator &right ) -{ - return left.neq( right ); -} - -// now for const_iterator -bool operator==( const Mapping::const_iterator &left, const Mapping::const_iterator &right ) -{ - return left.eql( right ); -} - -bool operator!=( const Mapping::const_iterator &left, const Mapping::const_iterator &right ) -{ - return left.neq( right ); -} - -// TMM: 31May'01 - Added the #ifndef so I can exclude iostreams. -#ifndef CXX_NO_IOSTREAMS -// output - -std::ostream &operator<<( std::ostream &os, const Object &ob ) -{ - return( os << static_cast( ob.str() ) ); -} -#endif - -} // Py diff --git a/extern/CXX/Version.hxx b/extern/CXX/Version.hxx deleted file mode 100644 index ff78b1622f1d..000000000000 --- a/extern/CXX/Version.hxx +++ /dev/null @@ -1,46 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __PyCXX_version_hxx__ -#define __PyCXX_version_hxx__ - -#define PYCXX_VERSION_MAJOR 6 -#define PYCXX_VERSION_MINOR 2 -#define PYCXX_VERSION_PATCH 4 -#define PYCXX_MAKEVERSION( major, minor, patch ) ((major<<16)|(minor<<8)|(patch)) -#define PYCXX_VERSION PYCXX_MAKEVERSION( PYCXX_VERSION_MAJOR, PYCXX_VERSION_MINOR, PYCXX_VERSION_PATCH ) -#endif diff --git a/extern/CXX/WrapPython.h b/extern/CXX/WrapPython.h deleted file mode 100644 index 6a73545d2d3d..000000000000 --- a/extern/CXX/WrapPython.h +++ /dev/null @@ -1,71 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- - -#ifndef __PyCXX_wrap_python_hxx__ -#define __PyCXX_wrap_python_hxx__ - -// On some platforms we have to include time.h to get select defined -#if !defined(__WIN32__) && !defined(WIN32) && !defined(_WIN32) && !defined(_WIN64) -#include -#endif - -// Prevent multiple conflicting definitions of swab from stdlib.h and unistd.h -#if defined(__sun) || defined(sun) -#if defined(_XPG4) -#undef _XPG4 -#endif -#endif - -// Python.h will redefine these and generate warning in the process -#undef _XOPEN_SOURCE -#undef _POSIX_C_SOURCE - -// pull in python definitions -#include - -// fix issue with Python assuming that isspace, toupper etc are macros -#if defined(isspace) -#undef isspace -#undef isupper -#undef islower -#undef isalnum -#undef isalpha -#undef toupper -#undef tolower -#endif - -#endif diff --git a/extern/CXX/cxx_extensions.cxx b/extern/CXX/cxx_extensions.cxx deleted file mode 100644 index 898c9f4951b3..000000000000 --- a/extern/CXX/cxx_extensions.cxx +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "Python2/cxx_extensions.cxx" -#else -#include "Python3/cxx_extensions.cxx" -#endif diff --git a/extern/CXX/cxxextensions.c b/extern/CXX/cxxextensions.c deleted file mode 100644 index cfab556f059a..000000000000 --- a/extern/CXX/cxxextensions.c +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "Python2/cxxextensions.c" -#else -#include "Python3/cxxextensions.c" -#endif diff --git a/extern/CXX/cxxsupport.cxx b/extern/CXX/cxxsupport.cxx deleted file mode 100644 index 946e60dc0d92..000000000000 --- a/extern/CXX/cxxsupport.cxx +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) 1998 - 2007, The Regents of the University of California -// Produced at the Lawrence Livermore National Laboratory -// All rights reserved. -// -// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The -// full copyright notice is contained in the file COPYRIGHT located at the root -// of the PyCXX distribution. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the disclaimer below. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the disclaimer (as noted below) in the -// documentation and/or materials provided with the distribution. -// - Neither the name of the UC/LLNL nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF -// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//----------------------------------------------------------------------------- -#include "CXX/WrapPython.h" - -#if PY_MAJOR_VERSION == 2 -#include "Python2/cxxsupport.cxx" -#else -#include "Python3/cxxsupport.cxx" -#endif diff --git a/lib/matplotlib/tri/_tri.cpp b/lib/matplotlib/tri/_tri.cpp index 94dc2eb3e975..a4bfb77bcb7f 100644 --- a/lib/matplotlib/tri/_tri.cpp +++ b/lib/matplotlib/tri/_tri.cpp @@ -5,11 +5,12 @@ * undef_macros=['NDEBUG'] * to the appropriate make_extension call in setupext.py, and then rebuilding. */ +#define NO_IMPORT_ARRAY + #include "_tri.h" -#include "src/mplutils.h" +#include "_tri_wrapper.h" #include -#include #include #define MOVETO 1 @@ -174,8 +175,7 @@ void BoundingBox::add(const XY& point) void BoundingBox::expand(const XY& delta) { - if (!empty) - { + if (!empty) { lower -= delta; upper += delta; } @@ -218,7 +218,6 @@ void write_contour(const Contour& contour) - Triangulation::Triangulation(PyArrayObject* x, PyArrayObject* y, PyArrayObject* triangles, @@ -234,13 +233,11 @@ Triangulation::Triangulation(PyArrayObject* x, _edges(edges), _neighbors(neighbors) { - correct_triangles(); } Triangulation::~Triangulation() { - Py_XDECREF(_x); Py_XDECREF(_y); Py_XDECREF(_triangles); @@ -251,8 +248,6 @@ Triangulation::~Triangulation() void Triangulation::calculate_boundaries() { - - get_neighbors(); // Ensure _neighbors has been created. // Create set of all boundary TriEdges, which are those which do not @@ -309,7 +304,6 @@ void Triangulation::calculate_boundaries() void Triangulation::calculate_edges() { - Py_XDECREF(_edges); // Create set of all edges, storing them with start point index less than @@ -338,7 +332,6 @@ void Triangulation::calculate_edges() void Triangulation::calculate_neighbors() { - Py_XDECREF(_neighbors); // Create _neighbors array with shape (ntri,3) and initialise all to -1. @@ -380,90 +373,57 @@ void Triangulation::calculate_neighbors() // boundary edges, but the boundaries are calculated separately elsewhere. } -Py::Object Triangulation::calculate_plane_coefficients(const Py::Tuple &args) +void Triangulation::calculate_plane_coefficients( + PyArrayObject* z, PyArrayObject* plane_coefficients) { - - args.verify_length(1); - - PyArrayObject* z = (PyArrayObject*)PyArray_ContiguousFromObject( - args[0].ptr(), NPY_DOUBLE, 1, 1); - if (z == 0 || PyArray_DIM(z,0) != PyArray_DIM(_x,0)) { - Py_XDECREF(z); - throw Py::ValueError( - "z array must have same length as triangulation x and y arrays"); - } - - PyArrayObject* planes_array = 0; // Array to return. - - try - { - const double* zs = (const double*)PyArray_DATA(z); - - npy_intp dims[2] = {_ntri, 3}; - planes_array = (PyArrayObject*)PyArray_SimpleNew(2, dims, - NPY_DOUBLE); - double* planes = (double*)PyArray_DATA(planes_array); - const int* tris = get_triangles_ptr(); - const double* xs = (const double*)PyArray_DATA(_x); - const double* ys = (const double*)PyArray_DATA(_y); - for (int tri = 0; tri < _ntri; ++tri) - { - if (is_masked(tri)) - { - *planes++ = 0.0; - *planes++ = 0.0; - *planes++ = 0.0; - tris += 3; + const double* zs = (const double*)PyArray_DATA(z); + double* planes = (double*)PyArray_DATA(plane_coefficients); + const int* tris = get_triangles_ptr(); + const double* xs = (const double*)PyArray_DATA(_x); + const double* ys = (const double*)PyArray_DATA(_y); + for (int tri = 0; tri < _ntri; ++tri) { + if (is_masked(tri)) { + *planes++ = 0.0; + *planes++ = 0.0; + *planes++ = 0.0; + tris += 3; + } + else { + // Equation of plane for all points r on plane is r.normal = p + // where normal is vector normal to the plane, and p is a + // constant. Rewrite as + // r_x*normal_x + r_y*normal_y + r_z*normal_z = p + // and rearrange to give + // r_z = (-normal_x/normal_z)*r_x + (-normal_y/normal_z)*r_y + + // p/normal_z + XYZ point0(xs[*tris], ys[*tris], zs[*tris]); + tris++; + XYZ side01 = XYZ(xs[*tris], ys[*tris], zs[*tris]) - point0; + tris++; + XYZ side02 = XYZ(xs[*tris], ys[*tris], zs[*tris]) - point0; + tris++; + + XYZ normal = side01.cross(side02); + + if (normal.z == 0.0) { + // Normal is in x-y plane which means triangle consists of + // colinear points. To avoid dividing by zero, we use the + // Moore-Penrose pseudo-inverse. + double sum2 = (side01.x*side01.x + side01.y*side01.y + + side02.x*side02.x + side02.y*side02.y); + double a = (side01.x*side01.z + side02.x*side02.z) / sum2; + double b = (side01.y*side01.z + side02.y*side02.z) / sum2; + *planes++ = a; + *planes++ = b; + *planes++ = point0.z - a*point0.x - b*point0.y; } - else - { - // Equation of plane for all points r on plane is r.normal = p - // where normal is vector normal to the plane, and p is a - // constant. Rewrite as - // r_x*normal_x + r_y*normal_y + r_z*normal_z = p - // and rearrange to give - // r_z = (-normal_x/normal_z)*r_x + (-normal_y/normal_z)*r_y + - // p/normal_z - XYZ point0(xs[*tris], ys[*tris], zs[*tris]); - tris++; - XYZ side01 = XYZ(xs[*tris], ys[*tris], zs[*tris]) - point0; - tris++; - XYZ side02 = XYZ(xs[*tris], ys[*tris], zs[*tris]) - point0; - tris++; - - XYZ normal = side01.cross(side02); - - if (normal.z == 0.0) - { - // Normal is in x-y plane which means triangle consists of - // colinear points. To avoid dividing by zero, we use the - // Moore-Penrose pseudo-inverse. - double sum2 = (side01.x*side01.x + side01.y*side01.y + - side02.x*side02.x + side02.y*side02.y); - double a = (side01.x*side01.z + side02.x*side02.z) / sum2; - double b = (side01.y*side01.z + side02.y*side02.z) / sum2; - *planes++ = a; - *planes++ = b; - *planes++ = point0.z - a*point0.x - b*point0.y; - } - else - { - *planes++ = -normal.x / normal.z; // x - *planes++ = -normal.y / normal.z; // y - *planes++ = normal.dot(point0) / normal.z; // constant - } + else { + *planes++ = -normal.x / normal.z; // x + *planes++ = -normal.y / normal.z; // y + *planes++ = normal.dot(point0) / normal.z; // constant } } } - catch (...) - { - Py_DECREF(z); - Py_XDECREF(planes_array); - throw; - } - - Py_DECREF(z); - return Py::asObject((PyObject*)planes_array); } void Triangulation::correct_triangles() @@ -485,7 +445,6 @@ void Triangulation::correct_triangles() const Triangulation::Boundaries& Triangulation::get_boundaries() const { - if (_boundaries.empty()) const_cast(this)->calculate_boundaries(); return _boundaries; @@ -515,12 +474,11 @@ int Triangulation::get_edge_in_triangle(int tri, int point) const return -1; // point is not in triangle. } -Py::Object Triangulation::get_edges() +PyArrayObject* Triangulation::get_edges() { - if (_edges == 0) calculate_edges(); - return Py::asObject(Py::new_reference_to((PyObject*)_edges)); + return _edges; } int Triangulation::get_neighbor(int tri, int edge) const @@ -542,11 +500,11 @@ TriEdge Triangulation::get_neighbor_edge(int tri, int edge) const (edge+1)%3))); } -Py::Object Triangulation::get_neighbors() +PyArrayObject* Triangulation::get_neighbors() { - - if (_neighbors == 0) calculate_neighbors(); - return Py::asObject(Py::new_reference_to((PyObject*)_neighbors)); + if (_neighbors == 0) + calculate_neighbors(); + return _neighbors; } const int* Triangulation::get_neighbors_ptr() const @@ -590,56 +548,25 @@ const int* Triangulation::get_triangles_ptr() const return (const int*)PyArray_DATA(_triangles); } -void Triangulation::init_type() -{ - - - behaviors().name("Triangulation"); - behaviors().doc("Triangulation"); - - add_varargs_method("calculate_plane_coefficients", - &Triangulation::calculate_plane_coefficients, - "calculate_plane_coefficients(z)"); - add_noargs_method("get_edges", &Triangulation::get_edges, - "get_edges()"); - add_noargs_method("get_neighbors", &Triangulation::get_neighbors, - "get_neighbors()"); - add_varargs_method("set_mask", &Triangulation::set_mask, - "set_mask(mask)"); -} - bool Triangulation::is_masked(int tri) const { assert(tri >= 0 && tri < _ntri && "Triangle index out of bounds."); return _mask && *((bool*)PyArray_DATA(_mask) + tri); } -Py::Object Triangulation::set_mask(const Py::Tuple &args) +void Triangulation::set_mask(PyArrayObject* mask) { - - args.verify_length(1); - + // No longer need old mask, whether it was set or not. Py_XDECREF(_mask); - _mask = 0; - if (args[0] != Py::None()) - { - _mask = (PyArrayObject*)PyArray_ContiguousFromObject( - args[0].ptr(), NPY_BOOL, 1, 1); - if (_mask == 0 || PyArray_DIM(_mask,0) != PyArray_DIM(_triangles,0)) { - Py_XDECREF(_mask); - throw Py::ValueError( - "mask must be a 1D array with the same length as the triangles array"); - } - } + + _mask = mask; // Clear derived fields so they are recalculated when needed. - Py_XDECREF(_edges); + Py_XDECREF(_edges); _edges = 0; Py_XDECREF(_neighbors); _neighbors = 0; _boundaries.clear(); - - return Py::None(); } void Triangulation::write_boundaries() const @@ -658,21 +585,18 @@ void Triangulation::write_boundaries() const - -TriContourGenerator::TriContourGenerator(Py::Object triangulation, +TriContourGenerator::TriContourGenerator(PyObject* triangulation, PyArrayObject* z) : _triangulation(triangulation), _z(z), _interior_visited(2*get_triangulation().get_ntri()), _boundaries_visited(0), _boundaries_used(0) -{ - -} +{} TriContourGenerator::~TriContourGenerator() { - + Py_XDECREF(_triangulation); Py_XDECREF(_z); } @@ -705,9 +629,9 @@ void TriContourGenerator::clear_visited_flags(bool include_boundaries) } } -Py::Object TriContourGenerator::contour_to_segs(const Contour& contour) +PyObject* TriContourGenerator::contour_to_segs(const Contour& contour) { - Py::List segs(contour.size()); + PyObject* segs = PyList_New(contour.size()); for (Contour::size_type i = 0; i < contour.size(); ++i) { const ContourLine& line = contour[i]; npy_intp dims[2] = {static_cast(line.size()),2}; @@ -718,12 +642,16 @@ Py::Object TriContourGenerator::contour_to_segs(const Contour& contour) *p++ = it->x; *p++ = it->y; } - segs[i] = Py::asObject((PyObject*)py_line); + if (PyList_SetItem(segs, i, (PyObject*)py_line)) { + PyErr_SetString(PyExc_RuntimeError, + "Unable to set contour segments"); + return NULL; + } } return segs; } -Py::Object TriContourGenerator::contour_to_segs_and_kinds(const Contour& contour) +PyObject* TriContourGenerator::contour_to_segs_and_kinds(const Contour& contour) { Contour::const_iterator line; ContourLine::const_iterator point; @@ -753,19 +681,18 @@ Py::Object TriContourGenerator::contour_to_segs_and_kinds(const Contour& contour } } - Py::Tuple result(2); - result[0] = Py::asObject((PyObject*)segs); - result[1] = Py::asObject((PyObject*)kinds); + PyObject* result = PyTuple_New(2); + if (PyTuple_SetItem(result, 0, (PyObject*)segs) || + PyTuple_SetItem(result, 1, (PyObject*)kinds)) { + PyErr_SetString(PyExc_RuntimeError, + "Unable to set contour segments and kinds"); + return NULL; + } return result; } -Py::Object TriContourGenerator::create_contour(const Py::Tuple &args) +PyObject* TriContourGenerator::create_contour(const double& level) { - - args.verify_length(1); - - double level = (Py::Float)args[0]; - clear_visited_flags(false); Contour contour; @@ -775,14 +702,9 @@ Py::Object TriContourGenerator::create_contour(const Py::Tuple &args) return contour_to_segs(contour); } -Py::Object TriContourGenerator::create_filled_contour(const Py::Tuple &args) +PyObject* TriContourGenerator::create_filled_contour(const double& lower_level, + const double& upper_level) { - - args.verify_length(2); - - double lower_level = (Py::Float)args[0]; - double upper_level = (Py::Float)args[1]; - clear_visited_flags(true); Contour contour; @@ -1077,7 +999,7 @@ int TriContourGenerator::get_exit_edge(int tri, const Triangulation& TriContourGenerator::get_triangulation() const { - return *(Triangulation*)_triangulation.ptr(); + return *((PyTriangulation*)_triangulation)->ptr; } const double& TriContourGenerator::get_z(int point) const @@ -1087,21 +1009,6 @@ const double& TriContourGenerator::get_z(int point) const return ((const double*)PyArray_DATA(_z))[point]; } -void TriContourGenerator::init_type() -{ - - - behaviors().name("TriContourGenerator"); - behaviors().doc("TriContourGenerator"); - - add_varargs_method("create_contour", - &TriContourGenerator::create_contour, - "create_contour(level)"); - add_varargs_method("create_filled_contour", - &TriContourGenerator::create_filled_contour, - "create_filled_contour(lower_level, upper_level)"); -} - XY TriContourGenerator::interp(int point1, int point2, const double& level) const @@ -1118,19 +1025,16 @@ XY TriContourGenerator::interp(int point1, - -TrapezoidMapTriFinder::TrapezoidMapTriFinder(Py::Object triangulation) +TrapezoidMapTriFinder::TrapezoidMapTriFinder(PyObject* triangulation) : _triangulation(triangulation), _points(0), _tree(0) -{ - -} +{} TrapezoidMapTriFinder::~TrapezoidMapTriFinder() { - clear(); + Py_XDECREF(_triangulation); } bool @@ -1360,30 +1264,12 @@ TrapezoidMapTriFinder::clear() _tree = 0; } -Py::Object -TrapezoidMapTriFinder::find_many(const Py::Tuple& args) +PyArrayObject* +TrapezoidMapTriFinder::find_many(PyArrayObject* x, PyArrayObject* y) { - args.verify_length(2); - - // Check input arguments. - PyArrayObject* x = (PyArrayObject*)PyArray_ContiguousFromObject( - args[0].ptr(), NPY_DOUBLE, 0, 0); - PyArrayObject* y = (PyArrayObject*)PyArray_ContiguousFromObject( - args[1].ptr(), NPY_DOUBLE, 0, 0); - bool ok = (x != 0 && y != 0 && PyArray_NDIM(x) == PyArray_NDIM(y)); - int ndim = x == 0 ? 0 : PyArray_NDIM(x); - for (int i = 0; ok && i < ndim; ++i) - ok = (PyArray_DIM(x,i) == PyArray_DIM(y,i)); - - if (!ok) { - Py_XDECREF(x); - Py_XDECREF(y); - throw Py::ValueError("x and y must be array_like with same shape"); - } - // Create integer array to return. PyArrayObject* tri = (PyArrayObject*)PyArray_SimpleNew( - ndim, PyArray_DIMS(x), NPY_INT); + PyArray_NDIM(x), PyArray_DIMS(x), NPY_INT); // Fill returned array. double* x_ptr = (double*)PyArray_DATA(x); @@ -1393,9 +1279,7 @@ TrapezoidMapTriFinder::find_many(const Py::Tuple& args) while (tri_ptr < tri_end) *tri_ptr++ = find_one(XY(*x_ptr++, *y_ptr++)); - Py_XDECREF(x); - Py_XDECREF(y); - return Py::asObject((PyObject*)tri); + return tri; } int @@ -1449,58 +1333,31 @@ TrapezoidMapTriFinder::find_trapezoids_intersecting_edge( return true; } -Py::Object +PyObject* TrapezoidMapTriFinder::get_tree_stats() { - - NodeStats stats; _tree->get_stats(0, stats); - Py::List list(7); - list[0] = Py::Int(stats.node_count); - list[1] = Py::Int(static_cast(stats.unique_nodes.size())); - list[2] = Py::Int(stats.trapezoid_count); - list[3] = Py::Int(static_cast(stats.unique_trapezoid_nodes.size())); - list[4] = Py::Int(stats.max_parent_count); - list[5] = Py::Int(stats.max_depth); - list[6] = Py::Float(stats.sum_trapezoid_depth / stats.trapezoid_count); - return list; + return Py_BuildValue("[l,l,l,l,l,l,d]", + stats.node_count, + stats.unique_nodes.size(), + stats.trapezoid_count, + stats.unique_trapezoid_nodes.size(), + stats.max_parent_count, + stats.max_depth, + stats.sum_trapezoid_depth / stats.trapezoid_count); } const Triangulation& TrapezoidMapTriFinder::get_triangulation() const { - return *(Triangulation*)_triangulation.ptr(); + return *((PyTriangulation*)_triangulation)->ptr; } void -TrapezoidMapTriFinder::init_type() -{ - - - behaviors().name("TrapezoidMapTriFinder"); - behaviors().doc("TrapezoidMapTriFinder"); - - add_varargs_method("find_many", - &TrapezoidMapTriFinder::find_many, - "find_many(x,y)"); - add_noargs_method("get_tree_stats", - &TrapezoidMapTriFinder::get_tree_stats, - "get_tree_stats()"); - add_noargs_method("initialize", - &TrapezoidMapTriFinder::initialize, - "initialize()"); - add_noargs_method("print_tree", - &TrapezoidMapTriFinder::print_tree, - "print_tree()"); -} - -Py::Object TrapezoidMapTriFinder::initialize() { - - clear(); const Triangulation& triang = get_triangulation(); @@ -1584,22 +1441,16 @@ TrapezoidMapTriFinder::initialize() unsigned int nedges = _edges.size(); for (unsigned int index = 2; index < nedges; ++index) { if (!add_edge_to_tree(_edges[index])) - throw Py::RuntimeError("Triangulation is invalid"); + throw "Triangulation is invalid"; _tree->assert_valid(index == nedges-1); } - - return Py::None(); } -Py::Object +void TrapezoidMapTriFinder::print_tree() { - - assert(_tree != 0 && "Null Node tree"); _tree->print(); - - return Py::None(); } TrapezoidMapTriFinder::Edge::Edge(const Point* left_, @@ -2176,6 +2027,7 @@ TrapezoidMapTriFinder::Trapezoid::set_upper_right(Trapezoid* upper_right_) } + RandomNumberGenerator::RandomNumberGenerator(unsigned long seed) : _m(21870), _a(1291), _c(4621), _seed(seed % _m) {} @@ -2186,158 +2038,3 @@ RandomNumberGenerator::operator()(unsigned long max_value) _seed = (_seed*_a + _c) % _m; return (_seed*max_value) / _m; } - - - - - -#if PY_MAJOR_VERSION >= 3 -PyMODINIT_FUNC -PyInit__tri(void) -#else -PyMODINIT_FUNC -init_tri(void) -#endif -{ - import_array(); - - static TriModule* triModule = NULL; - triModule = new TriModule(); - - #if PY_MAJOR_VERSION >= 3 - return triModule->module().ptr(); - #endif -} - -TriModule::TriModule() - : Py::ExtensionModule("tri") -{ - Triangulation::init_type(); - TriContourGenerator::init_type(); - TrapezoidMapTriFinder::init_type(); - - add_varargs_method("Triangulation", &TriModule::new_triangulation, - "Create and return new C++ Triangulation object"); - add_varargs_method("TriContourGenerator", &TriModule::new_tricontourgenerator, - "Create and return new C++ TriContourGenerator object"); - add_varargs_method("TrapezoidMapTriFinder", - &TriModule::new_TrapezoidMapTriFinder, - "Create and return new C++ TrapezoidMapTriFinder object"); - - initialize("Module for unstructured triangular grids"); -} - -Py::Object TriModule::new_triangulation(const Py::Tuple &args) -{ - - args.verify_length(6); - - // x and y. - PyArrayObject* x = (PyArrayObject*)PyArray_ContiguousFromObject( - args[0].ptr(), NPY_DOUBLE, 1, 1); - PyArrayObject* y = (PyArrayObject*)PyArray_ContiguousFromObject( - args[1].ptr(), NPY_DOUBLE, 1, 1); - if (x == 0 || y == 0 || PyArray_DIM(x,0) != PyArray_DIM(y,0)) { - Py_XDECREF(x); - Py_XDECREF(y); - throw Py::ValueError("x and y must be 1D arrays of the same length"); - } - - // triangles. - PyArrayObject* triangles = (PyArrayObject*)PyArray_ContiguousFromObject( - args[2].ptr(), NPY_INT, 2, 2); - if (triangles == 0 || PyArray_DIM(triangles,1) != 3) { - Py_XDECREF(x); - Py_XDECREF(y); - Py_XDECREF(triangles); - throw Py::ValueError("triangles must be a 2D array of shape (?,3)"); - } - - // Optional mask. - PyArrayObject* mask = 0; - if (args[3].ptr() != 0 && args[3] != Py::None()) - { - mask = (PyArrayObject*)PyArray_ContiguousFromObject( - args[3].ptr(), NPY_BOOL, 1, 1); - if (mask == 0 || PyArray_DIM(mask,0) != PyArray_DIM(triangles,0)) { - Py_XDECREF(x); - Py_XDECREF(y); - Py_XDECREF(triangles); - Py_XDECREF(mask); - throw Py::ValueError( - "mask must be a 1D array with the same length as the triangles array"); - } - } - - // Optional edges. - PyArrayObject* edges = 0; - if (args[4].ptr() != 0 && args[4] != Py::None()) - { - edges = (PyArrayObject*)PyArray_ContiguousFromObject( - args[4].ptr(), NPY_INT, 2, 2); - if (edges == 0 || PyArray_DIM(edges,1) != 2) { - Py_XDECREF(x); - Py_XDECREF(y); - Py_XDECREF(triangles); - Py_XDECREF(mask); - Py_XDECREF(edges); - throw Py::ValueError("edges must be a 2D array with shape (?,2)"); - } - } - - // Optional neighbors. - PyArrayObject* neighbors = 0; - if (args[5].ptr() != 0 && args[5] != Py::None()) - { - neighbors = (PyArrayObject*)PyArray_ContiguousFromObject( - args[5].ptr(), NPY_INT, 2, 2); - if (neighbors == 0 || - PyArray_DIM(neighbors,0) != PyArray_DIM(triangles,0) || - PyArray_DIM(neighbors,1) != PyArray_DIM(triangles,1)) { - Py_XDECREF(x); - Py_XDECREF(y); - Py_XDECREF(triangles); - Py_XDECREF(mask); - Py_XDECREF(edges); - Py_XDECREF(neighbors); - throw Py::ValueError( - "neighbors must be a 2D array with the same shape as the triangles array"); - } - } - - return Py::asObject(new Triangulation(x, y, triangles, mask, edges, neighbors)); -} - -Py::Object TriModule::new_tricontourgenerator(const Py::Tuple &args) -{ - - args.verify_length(2); - - Py::Object tri = args[0]; - if (!Triangulation::check(tri)) - throw Py::ValueError("Expecting a C++ Triangulation object"); - - PyArrayObject* z = (PyArrayObject*)PyArray_ContiguousFromObject( - args[1].ptr(), NPY_DOUBLE, 1, 1); - if (z == 0 || - PyArray_DIM(z,0) != ((Triangulation*)tri.ptr())->get_npoints()) { - Py_XDECREF(z); - throw Py::ValueError( - "z must be a 1D array with the same length as the x and y arrays"); - } - - return Py::asObject(new TriContourGenerator(tri, z)); -} - -Py::Object -TriModule::new_TrapezoidMapTriFinder(const Py::Tuple &args) -{ - - args.verify_length(1); - - Py::Object triangulation = args[0]; - if (!Triangulation::check(triangulation)) - throw Py::ValueError("Expecting a C++ Triangulation object"); - - return Py::asObject(new TrapezoidMapTriFinder(triangulation)); -} diff --git a/lib/matplotlib/tri/_tri.h b/lib/matplotlib/tri/_tri.h index c923411d9900..a40c0fa673fc 100644 --- a/lib/matplotlib/tri/_tri.h +++ b/lib/matplotlib/tri/_tri.h @@ -63,10 +63,10 @@ #ifndef _TRI_H #define _TRI_H -#include "CXX/Extensions.hxx" -#include "CXX/Objects.hxx" +#include "Python.h" #include "numpy/arrayobject.h" +#include #include #include #include @@ -159,7 +159,7 @@ void write_contour(const Contour& contour); /* Triangulation with npoints points and ntri triangles. Derived fields are * calculated when they are first needed. */ -class Triangulation : public Py::PythonExtension +class Triangulation { public: /* A single boundary is a vector of the TriEdges that make up that boundary @@ -180,7 +180,9 @@ class Triangulation : public Py::PythonExtension * once. * neighbors: Optional int array of shape (ntri,3) indicating which * triangles are the neighbors of which TriEdges, or -1 if - * there is no such neighbor. */ + * there is no such neighbor. + * Argument reference counts are not incremented in the constructor, but + * are decremented when no longer needed. */ Triangulation(PyArrayObject* x, PyArrayObject* y, PyArrayObject* triangles, @@ -188,14 +190,16 @@ class Triangulation : public Py::PythonExtension PyArrayObject* edges, PyArrayObject* neighbors); - virtual ~Triangulation(); + ~Triangulation(); /* Calculate plane equation coefficients for all unmasked triangles from * the point (x,y) coordinates and point z-array of shape (npoints) passed - * in via the args. Returned array has shape (npoints,3) and allows + * in via the args. Returned array must have shape (npoints,3) and allows * z-value at (x,y) coordinates in triangle tri to be calculated using - * z = array[tri,0]*x + array[tri,1]*y + array[tri,2]. */ - Py::Object calculate_plane_coefficients(const Py::Tuple &args); + * z = array[tri,0]*x + array[tri,1]*y + array[tri,2]. + * Does not alter reference counts of z or plane_coefficients. */ + void calculate_plane_coefficients(PyArrayObject* z, + PyArrayObject* plane_coefficients); // Return the boundaries collection, creating it if necessary. const Boundaries& get_boundaries() const; @@ -205,8 +209,9 @@ class Triangulation : public Py::PythonExtension int& boundary, int& edge) const; - // Return the edges array, creating it if necessary. - Py::Object get_edges(); + /* Return a borrowed reference to the edges array, creating it if + * necessary. */ + PyArrayObject* get_edges(); /* Return the triangle index of the neighbor of the specified triangle * edge. */ @@ -216,8 +221,9 @@ class Triangulation : public Py::PythonExtension * or TriEdge(-1,-1) if there is no such neighbor. */ TriEdge get_neighbor_edge(int tri, int edge) const; - // Return the neighbors array, creating it if necessary. - Py::Object get_neighbors(); + /* Return a borrowed reference to the neighbors array, creating it if + * necessary. */ + PyArrayObject* get_neighbors(); // Return the number of points in this triangulation. int get_npoints() const; @@ -233,16 +239,14 @@ class Triangulation : public Py::PythonExtension // Return the coordinates of the specified point index. XY get_point_coords(int point) const; - // CXX initialisation function. - static void init_type(); - // Indicates if the specified triangle is masked or not. bool is_masked(int tri) const; /* Set or clear the mask array. Clears various derived fields so they are * recalculated when next needed. - * args[0]: mask, either Py::None or boolean array of shape (ntri). */ - Py::Object set_mask(const Py::Tuple &args); + * mask: New reference to bool array of shape (ntri) indicating which + * triangles are masked, or 0 to clear mask. */ + void set_mask(PyArrayObject* mask); // Debug function to write boundaries. void write_boundaries() const; @@ -326,37 +330,36 @@ class Triangulation : public Py::PythonExtension - // Contour generator for a triangulation. -class TriContourGenerator : public Py::PythonExtension +class TriContourGenerator { public: /* Constructor. * triangulation: Triangulation to generate contours for. * z: Double array of shape (npoints) of z-values at triangulation - * points. */ - TriContourGenerator(Py::Object triangulation, + * points. + * Argument reference counts are not incremented in the constructor, but + * are decremented when no longer needed. */ + TriContourGenerator(PyObject* triangulation, PyArrayObject* z); - virtual ~TriContourGenerator(); + ~TriContourGenerator(); /* Create and return a non-filled contour. * level: Contour level. - * Returns python list [segs0, segs1, ...] where + * Returns reference to new python list [segs0, segs1, ...] where * segs0: double array of shape (?,2) of point coordinates of first * contour line, etc. */ - Py::Object create_contour(const Py::Tuple &args); + PyObject* create_contour(const double& level); /* Create and return a filled contour. * lower_level: Lower contour level. * upper_level: Upper contour level. - * Returns python tuple (segs, kinds) where + * Returns reference to new python tuple (segs, kinds) where * segs: double array of shape (n_points,2) of all point coordinates, * kinds: ubyte array of shape (n_points) of all point code types. */ - Py::Object create_filled_contour(const Py::Tuple &args); - - // CXX initialisation function. - static void init_type(); + PyObject* create_filled_contour(const double& lower_level, + const double& upper_level); private: typedef Triangulation::Boundary Boundary; @@ -368,16 +371,16 @@ class TriContourGenerator : public Py::PythonExtension void clear_visited_flags(bool include_boundaries); /* Convert a non-filled Contour from C++ to Python. - * Returns python list [segs0, segs1, ...] where + * Returns reference to new python list [segs0, segs1, ...] where * segs0: double array of shape (?,2) of point coordinates of first * contour line, etc. */ - Py::Object contour_to_segs(const Contour& contour); + PyObject* contour_to_segs(const Contour& contour); /* Convert a filled Contour from C++ to Python. - * Returns python tuple (segs, kinds) where + * Returns reference to new python tuple (segs, kinds) where * segs: double array of shape (n_points,2) of all point coordinates, * kinds: ubyte array of shape (n_points) of all point code types. */ - Py::Object contour_to_segs_and_kinds(const Contour& contour); + PyObject* contour_to_segs_and_kinds(const Contour& contour); /* Return the point on the specified TriEdge that intersects the specified * level. */ @@ -465,7 +468,7 @@ class TriContourGenerator : public Py::PythonExtension // Variables shared with python, always set. - Py::Object _triangulation; + PyObject* _triangulation; PyArrayObject* _z; // double array (npoints). // Variables internal to C++ only. @@ -481,7 +484,6 @@ class TriContourGenerator : public Py::PythonExtension - /* TriFinder class implemented using the trapezoid map algorithm from the book * "Computational Geometry, Algorithms and Applications", second edition, by * M. de Berg, M. van Kreveld, M. Overmars and O. Schwarzkopf. @@ -509,22 +511,27 @@ class TriContourGenerator : public Py::PythonExtension * colinear points but only in the simplest of cases. No explicit testing of * the validity of the triangulation is performed as this is a computationally * more complex task than the trifinding itself. */ -class TrapezoidMapTriFinder : public Py::PythonExtension +class TrapezoidMapTriFinder { public: /* Constructor. A separate call to initialize() is required to initialize * the object before use. - * triangulation: Triangulation to find triangles in. */ - TrapezoidMapTriFinder(Py::Object triangulation); + * triangulation: Triangulation to find triangles in. + * Triangulation reference count is not incremented in the constructor, but + * is decremented when no longer needed. */ + TrapezoidMapTriFinder(PyObject* triangulation); - virtual ~TrapezoidMapTriFinder(); + ~TrapezoidMapTriFinder(); /* Return an array of triangle indices. Takes any-shaped arrays x and y of * point coordinates, and returns an array of the same shape containing the - * indices of the triangles at those points. */ - Py::Object find_many(const Py::Tuple& args); + * indices of the triangles at those points. + * Argument reference counts are not modified, return is a reference to a + * new array. */ + PyArrayObject* find_many(PyArrayObject* x, PyArrayObject* y); - /* Return a python list containing the following statistics about the tree: + /* Return a reference to a new python list containing the following + * statistics about the tree: * 0: number of nodes (tree size) * 1: number of unique nodes (number of unique Node objects in tree) * 2: number of trapezoids (tree leaf nodes) @@ -535,17 +542,14 @@ class TrapezoidMapTriFinder : public Py::PythonExtension * comparisons needed to search through the tree) * 6: mean of all trapezoid depths (one more than the average number of * comparisons needed to search through the tree) */ - Py::Object get_tree_stats(); - - // CXX initialisation function. - static void init_type(); + PyObject* get_tree_stats(); /* Initialize this object before use. May be called multiple times, if, * for example, the triangulation is changed by setting the mask. */ - Py::Object initialize(); + void initialize(); // Print the search tree as text to stdout; useful for debug purposes. - Py::Object print_tree(); + void print_tree(); private: /* A Point consists of x,y coordinates as well as the index of a triangle @@ -786,7 +790,7 @@ class TrapezoidMapTriFinder : public Py::PythonExtension // Variables shared with python, always set. - Py::Object _triangulation; + PyObject* _triangulation; // Variables internal to C++ only. Point* _points; // Array of all points in triangulation plus corners of @@ -800,6 +804,7 @@ class TrapezoidMapTriFinder : public Py::PythonExtension }; + /* Linear congruential random number generator. Edges in the triangulation are * randomly shuffled before being added to the trapezoid map. Want the * shuffling to be identical across different operating systems and the same @@ -822,18 +827,4 @@ class RandomNumberGenerator unsigned long _seed; }; - - -// The extension module. -class TriModule : public Py::ExtensionModule -{ -public: - TriModule(); - -private: - Py::Object new_triangulation(const Py::Tuple &args); - Py::Object new_tricontourgenerator(const Py::Tuple &args); - Py::Object new_TrapezoidMapTriFinder(const Py::Tuple &args); -}; - #endif diff --git a/lib/matplotlib/tri/_tri_wrapper.cpp b/lib/matplotlib/tri/_tri_wrapper.cpp new file mode 100644 index 000000000000..ca20960db5c2 --- /dev/null +++ b/lib/matplotlib/tri/_tri_wrapper.cpp @@ -0,0 +1,573 @@ +#include "_tri_wrapper.h" +#include "src/mplutils.h" +#include "src/py_exceptions.h" + + +/* Triangulation */ + +static PyTypeObject PyTriangulationType; + +static PyObject* PyTriangulation_new(PyTypeObject* type, PyObject* args, PyObject* kwds) +{ + PyTriangulation* self; + self = (PyTriangulation*)type->tp_alloc(type, 0); + self->ptr = NULL; + return (PyObject*)self; +} + +const char* PyTriangulation_init__doc__ = + "Triangulation(x, y, triangles, mask, edges, neighbors)\n" + "\n" + "Create a new C++ Triangulation object\n" + "This should not be called directly, instead use the python class\n" + "matplotlib.tri.Triangulation instead.\n"; + +static int PyTriangulation_init(PyTriangulation* self, PyObject* args, PyObject* kwds) +{ + PyObject* x_arg; + PyObject* y_arg ; + PyObject* triangles_arg; + PyObject* mask_arg; + PyObject* edges_arg; + PyObject* neighbors_arg; + if (!PyArg_ParseTuple(args, "OOOOOO", &x_arg, &y_arg, &triangles_arg, + &mask_arg, &edges_arg, &neighbors_arg)) { + return -1; + } + + // x and y. + PyArrayObject* x = (PyArrayObject*)PyArray_ContiguousFromObject( + x_arg, NPY_DOUBLE, 1, 1); + PyArrayObject* y = (PyArrayObject*)PyArray_ContiguousFromObject( + y_arg, NPY_DOUBLE, 1, 1); + if (x == 0 || y == 0 || PyArray_DIM(x,0) != PyArray_DIM(y,0)) { + Py_XDECREF(x); + Py_XDECREF(y); + PyErr_SetString(PyExc_ValueError, + "x and y must be 1D arrays of the same length"); + } + + // triangles. + PyArrayObject* triangles = (PyArrayObject*)PyArray_ContiguousFromObject( + triangles_arg, NPY_INT, 2, 2); + if (triangles == 0 || PyArray_DIM(triangles,1) != 3) { + Py_XDECREF(x); + Py_XDECREF(y); + Py_XDECREF(triangles); + PyErr_SetString(PyExc_ValueError, + "triangles must be a 2D array of shape (?,3)"); + } + + // Optional mask. + PyArrayObject* mask = 0; + if (mask_arg != 0 && mask_arg != Py_None) + { + mask = (PyArrayObject*)PyArray_ContiguousFromObject( + mask_arg, NPY_BOOL, 1, 1); + if (mask == 0 || PyArray_DIM(mask,0) != PyArray_DIM(triangles,0)) { + Py_XDECREF(x); + Py_XDECREF(y); + Py_XDECREF(triangles); + Py_XDECREF(mask); + PyErr_SetString(PyExc_ValueError, + "mask must be a 1D array with the same length as the triangles array"); + } + } + + // Optional edges. + PyArrayObject* edges = 0; + if (edges_arg != 0 && edges_arg != Py_None) + { + edges = (PyArrayObject*)PyArray_ContiguousFromObject( + edges_arg, NPY_INT, 2, 2); + if (edges == 0 || PyArray_DIM(edges,1) != 2) { + Py_XDECREF(x); + Py_XDECREF(y); + Py_XDECREF(triangles); + Py_XDECREF(mask); + Py_XDECREF(edges); + PyErr_SetString(PyExc_ValueError, + "edges must be a 2D array with shape (?,2)"); + } + } + + // Optional neighbors. + PyArrayObject* neighbors = 0; + if (neighbors_arg != 0 && neighbors_arg != Py_None) + { + neighbors = (PyArrayObject*)PyArray_ContiguousFromObject( + neighbors_arg, NPY_INT, 2, 2); + if (neighbors == 0 || + PyArray_DIM(neighbors,0) != PyArray_DIM(triangles,0) || + PyArray_DIM(neighbors,1) != PyArray_DIM(triangles,1)) { + Py_XDECREF(x); + Py_XDECREF(y); + Py_XDECREF(triangles); + Py_XDECREF(mask); + Py_XDECREF(edges); + Py_XDECREF(neighbors); + PyErr_SetString(PyExc_ValueError, + "neighbors must be a 2D array with the same shape as the triangles array"); + } + } + + CALL_CPP_INIT("Triangulation", + (self->ptr = new Triangulation(x, y, triangles, mask, edges, + neighbors))); + return 0; +} + +static void PyTriangulation_dealloc(PyTriangulation* self) +{ + delete self->ptr; + Py_TYPE(self)->tp_free((PyObject *)self); +} + +const char* PyTriangulation_calculate_plane_coefficients__doc__ = + "calculate_plane_coefficients(z, plane_coefficients)\n" + "\n" + "Calculate plane equation coefficients for all unmasked triangles"; + +static PyObject* PyTriangulation_calculate_plane_coefficients(PyTriangulation* self, PyObject* args, PyObject* kwds) +{ + PyObject* z_arg; + if (!PyArg_ParseTuple(args, "O:calculate_plane_coefficients", &z_arg)) { + return NULL; + } + + PyArrayObject* z = (PyArrayObject*)PyArray_ContiguousFromObject( + z_arg, NPY_DOUBLE, 1, 1); + if (z == 0 || PyArray_DIM(z,0) != self->ptr->get_npoints()) { + Py_XDECREF(z); + PyErr_SetString(PyExc_ValueError, + "z array must have same length as triangulation x and y arrays"); + } + + npy_intp dims[2] = {self->ptr->get_ntri(), 3}; + PyArrayObject* result = (PyArrayObject*)PyArray_SimpleNew( + 2, dims, NPY_DOUBLE); + + CALL_CPP_CLEANUP("calculate_plane_coefficients", + (self->ptr->calculate_plane_coefficients(z, result)), + Py_XDECREF(z); Py_XDECREF(result)); + + Py_XDECREF(z); + return (PyObject*)result; +} + +const char* PyTriangulation_get_edges__doc__ = + "get_edges()\n" + "\n" + "Return edges array"; + +static PyObject* PyTriangulation_get_edges(PyTriangulation* self, PyObject* args, PyObject* kwds) +{ + PyArrayObject* result; + CALL_CPP("get_edges", (result = self->ptr->get_edges())); + Py_XINCREF(result); + return (PyObject*)result; +} + +const char* PyTriangulation_get_neighbors__doc__ = + "get_neighbors()\n" + "\n" + "Return neighbors array"; + +static PyObject* PyTriangulation_get_neighbors(PyTriangulation* self, PyObject* args, PyObject* kwds) +{ + PyArrayObject* result; + CALL_CPP("get_neighbors", (result = self->ptr->get_neighbors())); + Py_XINCREF(result); + return (PyObject*)result; +} + +const char* PyTriangulation_set_mask__doc__ = + "set_mask(mask)\n" + "\n" + "Set or clear the mask array."; + +static PyObject* PyTriangulation_set_mask(PyTriangulation* self, PyObject* args, PyObject* kwds) +{ + PyObject* mask_arg; + if (!PyArg_ParseTuple(args, "O:set_mask", &mask_arg)) { + return NULL; + } + + // Optional mask. + PyArrayObject* mask = 0; + if (mask_arg != 0 && mask_arg != Py_None) + { + mask = (PyArrayObject*)PyArray_ContiguousFromObject( + mask_arg, NPY_BOOL, 1, 1); + if (mask == 0 || PyArray_DIM(mask,0) != self->ptr->get_ntri()) { + Py_XDECREF(mask); + PyErr_SetString(PyExc_ValueError, + "mask must be a 1D array with the same length as the triangles array"); + } + } + + CALL_CPP("set_mask", (self->ptr->set_mask(mask))); + + Py_RETURN_NONE; +} + +static PyTypeObject* PyTriangulation_init_type(PyObject* m, PyTypeObject* type) +{ + static PyMethodDef methods[] = { + {"calculate_plane_coefficients", (PyCFunction)PyTriangulation_calculate_plane_coefficients, METH_VARARGS, PyTriangulation_calculate_plane_coefficients__doc__}, + {"get_edges", (PyCFunction)PyTriangulation_get_edges, METH_NOARGS, PyTriangulation_get_edges__doc__}, + {"get_neighbors", (PyCFunction)PyTriangulation_get_neighbors, METH_NOARGS, PyTriangulation_get_neighbors__doc__}, + {"set_mask", (PyCFunction)PyTriangulation_set_mask, METH_VARARGS, PyTriangulation_set_mask__doc__}, + {NULL} + }; + + memset(type, 0, sizeof(PyTypeObject)); + type->tp_name = "matplotlib._tri.Triangulation"; + type->tp_doc = PyTriangulation_init__doc__; + type->tp_basicsize = sizeof(PyTriangulation); + type->tp_dealloc = (destructor)PyTriangulation_dealloc; + type->tp_flags = Py_TPFLAGS_DEFAULT; + type->tp_methods = methods; + type->tp_new = PyTriangulation_new; + type->tp_init = (initproc)PyTriangulation_init; + + if (PyType_Ready(type) < 0) { + return NULL; + } + + if (PyModule_AddObject(m, "Triangulation", (PyObject*)type)) { + return NULL; + } + + return type; +} + + +/* TriContourGenerator */ + +static PyTypeObject PyTriContourGeneratorType; + +static PyObject* PyTriContourGenerator_new(PyTypeObject* type, PyObject* args, PyObject* kwds) +{ + PyTriContourGenerator* self; + self = (PyTriContourGenerator*)type->tp_alloc(type, 0); + self->ptr = NULL; + return (PyObject*)self; +} + +const char* PyTriContourGenerator_init__doc__ = + "TriContourGenerator(triangulation, z)\n" + "\n" + "Create a new C++ TriContourGenerator object\n" + "This should not be called directly, instead use the functions\n" + "matplotlib.axes.tricontour and tricontourf instead.\n"; + +static int PyTriContourGenerator_init(PyTriContourGenerator* self, PyObject* args, PyObject* kwds) +{ + PyObject* triangulation; + PyObject* z_arg; + if (!PyArg_ParseTuple(args, "O!O", &PyTriangulationType, &triangulation, + &z_arg)) { + return -1; + } + Py_INCREF(triangulation); + + int npoints = ((PyTriangulation*)triangulation)->ptr->get_npoints(); + + PyArrayObject* z = (PyArrayObject*)PyArray_ContiguousFromObject( + z_arg, NPY_DOUBLE, 1, 1); + if (z == 0 && PyArray_DIM(z,0) != npoints) { + Py_DECREF(triangulation); + Py_XDECREF(z); + PyErr_SetString(PyExc_ValueError, + "z must be a 1D array with the same length as the x and y arrays"); + } + + CALL_CPP_INIT("TriContourGenerator", + (self->ptr = new TriContourGenerator(triangulation, z))); + + return 0; +} + +static void PyTriContourGenerator_dealloc(PyTriContourGenerator* self) +{ + delete self->ptr; + Py_TYPE(self)->tp_free((PyObject *)self); +} + +const char* PyTriContourGenerator_create_contour__doc__ = + "create_contour(level)\n" + "\n" + "Create and return a non-filled contour."; + +static PyObject* PyTriContourGenerator_create_contour(PyTriContourGenerator* self, PyObject* args, PyObject* kwds) +{ + double level; + if (!PyArg_ParseTuple(args, "d:create_contour", &level)) { + return NULL; + } + + PyObject* result; + CALL_CPP("get_edges", (result = self->ptr->create_contour(level))); + return result; +} + +const char* PyTriContourGenerator_create_filled_contour__doc__ = + "create_filled_contour(lower_level, upper_level)\n" + "\n" + "Create and return a filled contour"; + +static PyObject* PyTriContourGenerator_create_filled_contour(PyTriContourGenerator* self, PyObject* args, PyObject* kwds) +{ + double lower_level, upper_level; + if (!PyArg_ParseTuple(args, "dd:create_contour", &lower_level, &upper_level)) { + return NULL; + } + + PyObject* result; + CALL_CPP("get_edges", + (result = self->ptr->create_filled_contour(lower_level, + upper_level))); + return result; +} + +static PyTypeObject* PyTriContourGenerator_init_type(PyObject* m, PyTypeObject* type) +{ + static PyMethodDef methods[] = { + {"create_contour", (PyCFunction)PyTriContourGenerator_create_contour, METH_VARARGS, PyTriContourGenerator_create_contour__doc__}, + {"create_filled_contour", (PyCFunction)PyTriContourGenerator_create_filled_contour, METH_VARARGS, PyTriContourGenerator_create_filled_contour__doc__}, + {NULL} + }; + + memset(type, 0, sizeof(PyTypeObject)); + type->tp_name = "matplotlib._tri.TriContourGenerator"; + type->tp_doc = PyTriContourGenerator_init__doc__; + type->tp_basicsize = sizeof(PyTriContourGenerator); + type->tp_dealloc = (destructor)PyTriContourGenerator_dealloc; + type->tp_flags = Py_TPFLAGS_DEFAULT; + type->tp_methods = methods; + type->tp_new = PyTriContourGenerator_new; + type->tp_init = (initproc)PyTriContourGenerator_init; + + if (PyType_Ready(type) < 0) { + return NULL; + } + + if (PyModule_AddObject(m, "TriContourGenerator", (PyObject*)type)) { + return NULL; + } + + return type; +} + + +/* TrapezoidMapTriFinder */ + +static PyTypeObject PyTrapezoidMapTriFinderType; + +static PyObject* PyTrapezoidMapTriFinder_new(PyTypeObject* type, PyObject* args, PyObject* kwds) +{ + PyTrapezoidMapTriFinder* self; + self = (PyTrapezoidMapTriFinder*)type->tp_alloc(type, 0); + self->ptr = NULL; + return (PyObject*)self; +} + +const char* PyTrapezoidMapTriFinder_init__doc__ = + "TrapezoidMapTriFinder(triangulation)\n" + "\n" + "Create a new C++ TrapezoidMapTriFinder object\n" + "This should not be called directly, instead use the python class\n" + "matplotlib.tri.TrapezoidMapTriFinder instead.\n"; + +static int PyTrapezoidMapTriFinder_init(PyTrapezoidMapTriFinder* self, PyObject* args, PyObject* kwds) +{ + PyObject* triangulation; + if (!PyArg_ParseTuple(args, "O!", &PyTriangulationType, &triangulation)) { + return -1; + } + Py_INCREF(triangulation); + + CALL_CPP_INIT("TrapezoidMapTriFinder", + (self->ptr = new TrapezoidMapTriFinder(triangulation))); + return 0; +} + +static void PyTrapezoidMapTriFinder_dealloc(PyTrapezoidMapTriFinder* self) +{ + delete self->ptr; + Py_TYPE(self)->tp_free((PyObject *)self); +} + +const char* PyTrapezoidMapTriFinder_find_many__doc__ = + "find_many(x, y)\n" + "\n" + "Find indices of triangles containing the point coordinates (x, y)"; + +static PyObject* PyTrapezoidMapTriFinder_find_many(PyTrapezoidMapTriFinder* self, PyObject* args, PyObject* kwds) +{ + PyObject* x_arg; + PyObject* y_arg; + if (!PyArg_ParseTuple(args, "OO:find_many", &x_arg, &y_arg)) { + return NULL; + } + + PyArrayObject* x = (PyArrayObject*)PyArray_ContiguousFromObject( + x_arg, NPY_DOUBLE, 0, 0); + PyArrayObject* y = (PyArrayObject*)PyArray_ContiguousFromObject( + y_arg, NPY_DOUBLE, 0, 0); + + bool ok = (x != 0 && y != 0 && PyArray_NDIM(x) == PyArray_NDIM(y)); + int ndim = (x == 0 ? 0 : PyArray_NDIM(x)); + for (int i = 0; ok && i < ndim; ++i) + ok = (PyArray_DIM(x,i) == PyArray_DIM(y,i)); + + if (!ok) { + Py_XDECREF(x); + Py_XDECREF(y); + PyErr_SetString(PyExc_ValueError, + "x and y must be array_like with same shape"); + } + + PyArrayObject* result; + CALL_CPP_CLEANUP("find_many", + (result = self->ptr->find_many(x, y)), + Py_XDECREF(x); Py_XDECREF(y)); + + Py_XDECREF(x); + Py_XDECREF(y); + return (PyObject*)result; +} + +const char* PyTrapezoidMapTriFinder_get_tree_stats__doc__ = + "get_tree_stats()\n" + "\n" + "Return statistics about the tree used by the trapezoid map"; + +static PyObject* PyTrapezoidMapTriFinder_get_tree_stats(PyTrapezoidMapTriFinder* self, PyObject* args, PyObject* kwds) +{ + PyObject* result; + CALL_CPP("get_tree_stats", (result = self->ptr->get_tree_stats())); + return result; +} + +const char* PyTrapezoidMapTriFinder_initialize__doc__ = + "initialize()\n" + "\n" + "Initialize this object, creating the trapezoid map from the triangulation"; + +static PyObject* PyTrapezoidMapTriFinder_initialize(PyTrapezoidMapTriFinder* self, PyObject* args, PyObject* kwds) +{ + CALL_CPP("initialize", (self->ptr->initialize())); + Py_RETURN_NONE; +} + +const char* PyTrapezoidMapTriFinder_print_tree__doc__ = + "print_tree()\n" + "\n" + "Print the search tree as text to stdout; useful for debug purposes"; + +static PyObject* PyTrapezoidMapTriFinder_print_tree(PyTrapezoidMapTriFinder* self, PyObject* args, PyObject* kwds) +{ + CALL_CPP("print_tree", (self->ptr->print_tree())); + Py_RETURN_NONE; +} + +static PyTypeObject* PyTrapezoidMapTriFinder_init_type(PyObject* m, PyTypeObject* type) +{ + static PyMethodDef methods[] = { + {"find_many", (PyCFunction)PyTrapezoidMapTriFinder_find_many, METH_VARARGS, PyTrapezoidMapTriFinder_find_many__doc__}, + {"get_tree_stats", (PyCFunction)PyTrapezoidMapTriFinder_get_tree_stats, METH_NOARGS, PyTrapezoidMapTriFinder_get_tree_stats__doc__}, + {"initialize", (PyCFunction)PyTrapezoidMapTriFinder_initialize, METH_NOARGS, PyTrapezoidMapTriFinder_initialize__doc__}, + {"print_tree", (PyCFunction)PyTrapezoidMapTriFinder_print_tree, METH_NOARGS, PyTrapezoidMapTriFinder_print_tree__doc__}, + {NULL} + }; + + memset(type, 0, sizeof(PyTypeObject)); + type->tp_name = "matplotlib._tri.TrapezoidMapTriFinder"; + type->tp_doc = PyTrapezoidMapTriFinder_init__doc__; + type->tp_basicsize = sizeof(PyTrapezoidMapTriFinder); + type->tp_dealloc = (destructor)PyTrapezoidMapTriFinder_dealloc; + type->tp_flags = Py_TPFLAGS_DEFAULT; + type->tp_methods = methods; + type->tp_new = PyTrapezoidMapTriFinder_new; + type->tp_init = (initproc)PyTrapezoidMapTriFinder_init; + + if (PyType_Ready(type) < 0) { + return NULL; + } + + if (PyModule_AddObject(m, "TrapezoidMapTriFinder", (PyObject*)type)) { + return NULL; + } + + return type; +} + + +/* Module */ + +extern "C" { + +struct module_state +{ +/* The Sun compiler can't handle empty structs */ +#if defined(__SUNPRO_C) || defined(_MSC_VER) + int _dummy; +#endif +}; + +#if PY3K +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "_tri", + NULL, + sizeof(struct module_state), + NULL, + NULL, + NULL, + NULL, + NULL +}; + +#define INITERROR return NULL + +PyMODINIT_FUNC PyInit__tri(void) + +#else +#define INITERROR return + +PyMODINIT_FUNC init_tri(void) +#endif + +{ + PyObject *m; + +#if PY3K + m = PyModule_Create(&moduledef); +#else + m = Py_InitModule3("_tri", NULL, NULL); +#endif + + if (m == NULL) { + INITERROR; + } + + if (!PyTriangulation_init_type(m, &PyTriangulationType)) { + INITERROR; + } + if (!PyTriContourGenerator_init_type(m, &PyTriContourGeneratorType)) { + INITERROR; + } + if (!PyTrapezoidMapTriFinder_init_type(m, &PyTrapezoidMapTriFinderType)) { + INITERROR; + } + + import_array(); + +#if PY3K + return m; +#endif +} + +} // extern "C" diff --git a/lib/matplotlib/tri/_tri_wrapper.h b/lib/matplotlib/tri/_tri_wrapper.h new file mode 100644 index 000000000000..9cd9d8b56c9a --- /dev/null +++ b/lib/matplotlib/tri/_tri_wrapper.h @@ -0,0 +1,24 @@ +#ifndef _TRI_WRAPPER_H +#define _TRI_WRAPPER_H + +#include "_tri.h" + +typedef struct +{ + PyObject_HEAD; + Triangulation* ptr; +} PyTriangulation; + +typedef struct +{ + PyObject_HEAD; + TriContourGenerator* ptr; +} PyTriContourGenerator; + +typedef struct +{ + PyObject_HEAD; + TrapezoidMapTriFinder* ptr; +} PyTrapezoidMapTriFinder; + +#endif // _TRI_WRAPPER_H diff --git a/setup.py b/setup.py index 7005c58e8962..5ff3357fc704 100644 --- a/setup.py +++ b/setup.py @@ -69,7 +69,6 @@ setupext.Pytz(), setupext.Tornado(), setupext.Pyparsing(), - setupext.CXX(), setupext.LibAgg(), setupext.FreeType(), setupext.FT2Font(), diff --git a/setupext.py b/setupext.py index 19ec6e54604d..06ad614cb4d0 100755 --- a/setupext.py +++ b/setupext.py @@ -840,76 +840,6 @@ def get_install_requires(self): return ['numpy>=1.6'] -class CXX(SetupPackage): - name = 'pycxx' - - def check(self): - if PY3: - # There is no version of PyCXX in the wild that will work - # with Python 3.x and matplotlib, since they lack support - # for the buffer object. - self.__class__.found_external = False - return ("Official versions of PyCXX are not compatible " - "with matplotlib on Python 3.x, since they lack " - "support for the buffer object. Using local " - "copy") - - self.__class__.found_external = True - old_stdout = sys.stdout - if PY3: - sys.stdout = io.StringIO() - else: - sys.stdout = io.BytesIO() - - try: - import CXX - except ImportError: - self.__class__.found_external = False - return "Couldn't import. Using local copy." - finally: - sys.stdout = old_stdout - - try: - return self._check_for_pkg_config( - 'PyCXX', 'CXX/Extensions.hxx', min_version='6.2.4') - except CheckFailed as e: - # It's ok to just proceed here, since the `import CXX` - # worked above, and PyCXX (at least upstream) ensures that - # its header files are on the default distutils include - # path (either in a standard C place such as /usr/include, - # or in /usr/include/pythonX.Y. - return 'Using system CXX (version unknown, no pkg-config info)' - - def add_flags(self, ext): - if self.found_external and not 'sdist' in sys.argv: - support_dir = os.path.normpath( - os.path.join( - sys.prefix, - 'share', - 'python%d.%d' % ( - sys.version_info[0], sys.version_info[1]), - 'CXX')) - if not os.path.exists(support_dir): - # On Fedora 17, these files are installed in /usr/share/CXX - support_dir = '/usr/src/CXX' - ext.sources.extend([ - os.path.join(support_dir, x) for x in - ['cxxsupport.cxx', 'cxx_extensions.cxx', - 'IndirectPythonInterface.cxx', - 'cxxextensions.c']]) - pkg_config.setup_extension(ext, 'PyCXX') - else: - ext.include_dirs.append('extern') - ext.sources.extend(glob.glob('extern/CXX/*.cxx')) - ext.sources.extend(glob.glob('extern/CXX/*.c')) - ext.define_macros.append(('PYCXX_ISO_CPP_LIB', '1')) - if PY3: - ext.define_macros.append(('PYCXX_PYTHON_2TO3', '1')) - if not (sys.platform == 'win32' and win32_compiler == 'msvc'): - ext.libraries.append('stdc++') - ext.libraries.append('m') - - class LibAgg(SetupPackage): name = 'libagg' @@ -1171,11 +1101,11 @@ class Tri(SetupPackage): def get_extension(self): sources = [ "lib/matplotlib/tri/_tri.cpp", + "lib/matplotlib/tri/_tri_wrapper.cpp", "src/mplutils.cpp" ] ext = make_extension('matplotlib._tri', sources) Numpy().add_flags(ext) - CXX().add_flags(ext) return ext