2
0
mirror of https://github.com/boostorg/python.git synced 2026-01-26 18:52:26 +00:00

Compare commits

..

9 Commits

Author SHA1 Message Date
Ralf W. Grosse-Kunstleve
f5a66ee1c6 Join ralf_grosse_kunstleve with HEAD
[SVN r9444]
2001-03-05 20:01:01 +00:00
Ralf W. Grosse-Kunstleve
eaef174f14 gen_extclass.py: "T" replaced by "Held" to reduce chances of name clashes.
[SVN r9384]
2001-03-03 02:45:39 +00:00
Ralf W. Grosse-Kunstleve
ab120dac4f Better error messages ("Incomplete pickle support").
[SVN r9363]
2001-02-28 19:53:35 +00:00
Ralf W. Grosse-Kunstleve
dc20d643fc Enhanced pickle safety measures.
[SVN r9358]
2001-02-27 18:56:57 +00:00
Ralf W. Grosse-Kunstleve
0178f5fc0c Fix memory leak (new bound_function() -> bound_function::create()).
Unrelated: ref in global_*_reduce() do not need to be static.


[SVN r9347]
2001-02-27 01:37:32 +00:00
Ralf W. Grosse-Kunstleve
1b4721f58e bug fix for auto_pickle logic.
[SVN r9315]
2001-02-23 08:39:05 +00:00
Ralf W. Grosse-Kunstleve
abbf219e75 Safer pickle support (explicit auto_pickle parameter)
[SVN r9313]
2001-02-22 20:47:36 +00:00
Ralf W. Grosse-Kunstleve
d8d2a900f6 Add examples that were meant to go here in the first place, but
were accidentally added to the main branch.


[SVN r9022]
2001-02-08 01:51:09 +00:00
nobody
9e9c7ce571 This commit was manufactured by cvs2svn to create branch
'unlabeled-1.2.8'.

[SVN r8365]
2000-11-30 04:53:34 +00:00
7 changed files with 4959 additions and 180 deletions

73
build/gcc.mak Normal file
View File

@@ -0,0 +1,73 @@
# Revision History
# 04 Mar 01 Changed library name to libboost_python.a, various cleanups,
# attempted Cygwin compatibility. Still needs testing on Linux
# (David Abrahams)
LIBSRC = \
classes.cpp \
conversions.cpp \
extension_class.cpp \
functions.cpp \
init_function.cpp \
module_builder.cpp \
objects.cpp \
types.cpp
LIBOBJ = $(LIBSRC:.cpp=.o)
OBJ = $(LIBOBJ)
PYTHON_INC=$(ROOT)/usr/local/include/python2.0
# libpython2.0.dll
ifeq "$(OS)" "Windows_NT"
ROOT=c:/cygnus
INC = -Ic:/cygnus/usr/include/g++-3 -Ic:/cygnus/usr/include -Ic:/boost -I$(PYTHON_INC)
MODULE_EXTENSION=dll
PYTHON_LIB=c:/cygnus/usr/local/lib/python2.0/config/libpython2.0.dll.a
else
INC = -I$(PYTHON_INC)
MODULE_EXTENSION=so
endif
%.o: ../src/%.cpp
g++ -fPIC -Wall -W $(INC) -o $*.o -c $<
%.d: ../src/%.cpp
@echo creating $@
@set -e; g++ -M $(INC) -c $< \
| sed 's/\($*\)\.o[ :]*/\1.o $@ : /g' > $@; \
[ -s $@ ] || rm -f $@
PYTHON = python
test: comprehensive.o libboost_python.a
g++ $(CXXFLAGS) -shared -o ../test/boost_python_test.$(MODULE_EXTENSION) comprehensive.o -L. -lboost_python $(PYTHON_LIB)
$(PYTHON) ../test/comprehensive.py
comprehensive.o: ../test/comprehensive.cpp
g++ $(CXXFLAGS) --template-depth-32 -fPIC -Wall -W $(INC) -o $*.o -c $<
example1: example1.o libboost_python.a
g++ $(CXXFLAGS) -shared -o ../example/hellomodule.$(MODULE_EXTENSION) example1.o -L. -lboost_python $(PYTHON_LIB)
$(PYTHON) ../example/test_example1.py
example1.o: ../example/example1.cpp
g++ $(CXXFLAGS) --template-depth-32 -fPIC -Wall -W $(INC) -o $*.o -c $<
clean:
rm -rf *.o *.$(MODULE_EXTENSION) *.a *.d *.pyc *.bak a.out
libboost_python.a: $(LIBOBJ)
rm -f libboost_python.a
ar cq libboost_python.a $(LIBOBJ)
DEP = $(OBJ:.o=.d)
ifneq "$(MAKECMDGOALS)" "clean"
include $(DEP)
endif

View File

@@ -1,180 +0,0 @@
23 October 2003
Fixed bug where a class would appear more than one in the generated code.
6 October 2003
Fixed bug reported by Niall Douglas (using his patch) about UniqueInt not
appearing correctly with --multiple.
Added precompiled header support on windows systems (using #pragma hdrstop).
Suggested by Niall Douglas.
Fixed a bug with -I directive and AllFromHeader. Reported by Scott Snyder.
4 October 2003
Added return_self, thanks for Niall Douglas for pointing out that it was
missing.
Added --file-list, where you can pass a file where the pyste files are listed
one per line. Also suggested by Niall Douglas.
Documentation has been finally updated, after a long wait. Please let me know
if you spot any mistake!
2 October 2003
Scott Snyder found a typo in ClassExporter that prevented -= and *= operators
from being exported. Thanks Scott!
20 September 2003
Added return_by_value in the list of policies supported. Thanks to Niall
Douglas for the remainder.
19 September 2003
Better support for unnamed enums, plus they are by default exported to the
parent's namespace. Normal enums can have the same behaviour using the function
export_values on the Enum object. Feature requested by Niall Douglas.
10 September 2003
A new variable is accessible in the Pyste files: INTERFACE_FILE contains the
full path of the pyste file.
4 September 2003
Now it is possible to override protected and private pure virtual functions
in Python, as requested by Roman Yakovenko.
23 August 2003
Fixed bug where some Imports where not writing their include files.
Now whenever the declarations change, the cache files are rebuilt
automatically.
19 August 2003
Fixed a bug related to the generation of the bases<> template.
17 August 2003
Added support for insertion of user code in the generated code.
16 August 2003
Applied a patch by Gottfried Ganssauge that adds exception specifiers to
wrapper functions and pointer declarations. Thanks a lot Gottfried!!
Applied a patch by Prabhu Ramachandran that fixes ae problem with the
pure virtual method generation. Thanks again Prabhu!
10 August 2003
Support for incremental generation of the code has been added. This changes
how --multiple works; documentation of this new feature will follow. Thanks
to Prabhu Ramachandran, that saw the need for this feature and discussed a
solution.
Automatically convert \ to / in Windows systems before passing the paths to
gccxml.
Fixed a bug reported by Prabhu Ramachandran, where in some classes the virtual
methods were being definied incorrectly. Thanks a lot Prabhu!
7 July 2003
Applied 2 patches by Prabhu Ramachandran: a fix in the new --multiple method,
and two new functions "hold_with_shared_ptr" and its counterpart for auto_ptr.
Thanks a lot Prabhu!
Fixed a bug where the macro BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID was being
called multiple times for the same type.
Thanks to Gottfried Ganßauge for reporting this!
Fixed bug where using AllFromHeader didn't use bases<> when exporting
hierarchies.
Fixed the staticmethod bug.
5 July 2003
Changed how --multiple works: now it generates one cpp file for each pyste
file, makeing easier to integrate Pyste with build systems.
4 July 2003
Applied patch that solved a bug in ClassExporter and added a distutils install
script (install/setup.py), both contributed by Prabhu Ramachandran.
Thanks Prabhu!
2 July 2003
Jim Wilson found a bug where types like "char**" were being interpreted as
"char*". Thanks Jim!
16 June 2003
Thanks to discussions with David Abrahams and Roman Sulzhyk, some behaviours
have changed:
- If you export a derived class without exporting its base classes, the derived
class will explicitly export the bases's methods and attributes. Before, if
you were interested in the bases's methods, you had to export the base
classes too.
- Added a new function, no_override. When a member function is specified as
"no_override", no virtual wrappers are generated for it, improving
performance and letting the code more clean.
- There was a bug in which the policy of virtual member functions was being
ignored (patch by Roman Sulzhyk).
Thanks again to Roman Sulzhyk for the patches and discussion in the c++-sig.
4 June 2003
Major improvements in memory usage.
3 June 2003
Appliced a patch from Giulio Eulisse that allows unnamed enumerations to be
exported with an AllFromHeader construct. Thanks a lot Giulio!
2 June 2003
Added a new construct, add_method. See documentation.
23 May 2003
Support for global variables added.
Various bug fixes.
08 May 2003
Fixed bug where in a certain cases the GCCXMLParser would end up with multiple
declarations of the same class
22 Apr 2003
- Now shows a warning when the user tries to export a forward-declared class.
Forward-declared classes are ignored by the AllFromHeader construct.
- Fixed a bug where classes, functions and enums where being exported, even if
excluded from a AllFromHeader construct.
16 Apr 2003
Added a more generic (but ugly) code to declare the smart pointer converters.
07 Apr 2003
- Removed the warnings about forward declarations: it was not accurate enough.
Another strategy must be thought of.
- Fixed bug in the --multiple mode, where the order of the class instantiations
could end up wrong.
- Lots of fixes in the documentation, pointed out by Dirk Gerrits. Thanks Dirk!
- Fixed support for the return_opaque_pointer policy (the support macro was not
being declared).
06 Apr 2003
Support for the improved static data members support of Boost.Python.
05 Apr 2003
New option for generating the bindings: --multiple.
02 Apr 2003
Forward declarations are now detected and a warning is generated.
24 Mar 2003
Default policy for functions/methods that return const T& is now
return_value_policy<copy_const_reference>().
22 Mar 2003
Exporting virtual methods of the base classes in the derived classes too.
21 Mar 2003
Added manual support for boost::shared_ptr and std::auto_ptr (see doc).
19 Mar 2003
Added support for int, double, float and long operators acting as expected in
python.
14 Mar 2003
Fixed bug: Wrappers for protected and virtual methods were not being generated.

931
src/classes.cpp Normal file
View File

@@ -0,0 +1,931 @@
// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and
// distribute this software is granted provided this copyright notice appears
// in all copies. This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
// The author gratefully acknowleges the support of Dragon Systems, Inc., in
// producing this work.
//
// Revision History:
// 04 Mar 01 Rolled in const_cast from Dragon fork (Dave Abrahams)
// 03 Mar 01 added: pickle safety measures (Ralf W. Grosse-Kunstleve)
// 03 Mar 01 bug fix: use bound_function::create() (instead of new bound_function)
#include <boost/python/classes.hpp>
#include <boost/python/detail/functions.hpp>
#include <boost/python/detail/singleton.hpp>
#include <cstddef>
#include <boost/python/callback.hpp>
#include <cstring>
#include <boost/python/module_builder.hpp>
namespace boost { namespace python {
namespace detail {
void enable_named_method(boost::python::detail::class_base* type_obj, const char* name);
}
namespace {
// Add the name of the module currently being loaded to the name_space with the
// key "__module__". If no module is being loaded, or if name_space already has
// a key "__module", has no effect. This is not really a useful public
// interface; it's just used for class_t<>::class_t() below.
void add_current_module_name(dictionary&);
bool is_prefix(const char* s1, const char* s2);
bool is_special_name(const char* name);
void enable_special_methods(boost::python::detail::class_base* derived, const tuple& bases, const dictionary& name_space);
void report_ignored_exception(PyObject* source)
{
// This bit of code copied wholesale from classobject.c in the Python source.
PyObject *f, *t, *v, *tb;
PyErr_Fetch(&t, &v, &tb);
f = PySys_GetObject(const_cast<char*>("stderr"));
if (f != NULL)
{
PyFile_WriteString(const_cast<char*>("Exception "), f);
if (t) {
PyFile_WriteObject(t, f, Py_PRINT_RAW);
if (v && v != Py_None) {
PyFile_WriteString(const_cast<char*>(": "), f);
PyFile_WriteObject(v, f, 0);
}
}
PyFile_WriteString(const_cast<char*>(" in "), f);
PyFile_WriteObject(source, f, 0);
PyFile_WriteString(const_cast<char*>(" ignored\n"), f);
PyErr_Clear(); /* Just in case */
}
Py_XDECREF(t);
Py_XDECREF(v);
Py_XDECREF(tb);
}
//
// pickle support courtesy of "Ralf W. Grosse-Kunstleve" <rwgk@cci.lbl.gov>
//
PyObject* class_reduce(PyObject* klass)
{
return PyObject_GetAttrString(klass, const_cast<char*>("__name__"));
}
ref global_class_reduce()
{
return ref(detail::new_wrapped_function(class_reduce));
}
tuple instance_reduce(PyObject* obj)
{
ref instance_class(PyObject_GetAttrString(obj, const_cast<char*>("__class__")));
ref getinitargs(PyObject_GetAttrString(obj, const_cast<char*>("__getinitargs__")),
ref::null_ok);
PyErr_Clear();
ref initargs;
if (getinitargs.get() != 0)
{
initargs = ref(PyEval_CallObject(getinitargs.get(), NULL));
initargs = ref(PySequence_Tuple(initargs.get()));
}
else
{
initargs = ref(PyTuple_New(0));
}
ref getstate(PyObject_GetAttrString(obj, const_cast<char*>("__getstate__")),
ref::null_ok);
PyErr_Clear();
ref dict(PyObject_GetAttrString(obj, const_cast<char*>("__dict__")), ref::null_ok);
PyErr_Clear();
if (getstate.get() != 0)
{
if (dict.get() != 0 && dictionary(dict).size() > 0)
{
ref getstate_manages_dict(PyObject_GetAttrString(instance_class.get(), const_cast<char*>("__getstate_manages_dict__")), ref::null_ok);
PyErr_Clear();
if (getstate_manages_dict.get() == 0)
{
PyErr_SetString(PyExc_RuntimeError, "Incomplete pickle support (__getstate_manages_dict__ not set)");
throw error_already_set();
}
}
ref state = ref(PyEval_CallObject(getstate.get(), NULL));
return tuple(instance_class, initargs, state);
}
if (getinitargs.get() == 0)
{
ref dict_defines_state(PyObject_GetAttrString(instance_class.get(), const_cast<char*>("__dict_defines_state__")), ref::null_ok);
PyErr_Clear();
if (dict_defines_state.get() == 0)
{
PyErr_SetString(PyExc_RuntimeError, "Incomplete pickle support (__dict_defines_state__ not set)");
throw error_already_set();
}
}
if (dict.get() != 0 && dictionary(dict).size() > 0)
{
return tuple(instance_class, initargs, dict);
}
return tuple(instance_class, initargs);
}
ref global_instance_reduce()
{
return ref(detail::new_wrapped_function(instance_reduce));
}
}
namespace detail {
class_base::class_base(PyTypeObject* meta_class_obj, string name, tuple bases, const dictionary& name_space)
: type_object_base(meta_class_obj),
m_name(name),
m_bases(bases),
m_name_space(name_space)
{
this->tp_name = const_cast<char*>(name.c_str());
enable(type_object_base::getattr);
enable(type_object_base::setattr);
add_current_module_name(m_name_space);
static const boost::python::string docstr("__doc__", boost::python::string::interned);
if (PyDict_GetItem(m_name_space.get(), docstr.get())== 0)
{
PyDict_SetItem(m_name_space.get(), docstr.get(), Py_None);
}
enable_special_methods(this, bases, name_space);
}
void class_base::add_base(ref base)
{
tuple new_bases(m_bases.size() + 1);
for (std::size_t i = 0; i < m_bases.size(); ++i)
new_bases.set_item(i, m_bases[i]);
new_bases.set_item(m_bases.size(), base);
m_bases = new_bases;
}
PyObject* class_base::getattr(const char* name)
{
if (!BOOST_CSTD_::strcmp(name, "__dict__"))
{
PyObject* result = m_name_space.get();
Py_INCREF(result);
return result;
}
if (!BOOST_CSTD_::strcmp(name, "__bases__"))
{
PyObject* result = m_bases.get();
Py_INCREF(result);
return result;
}
if (!BOOST_CSTD_::strcmp(name, "__name__"))
{
PyObject* result = m_name.get();
Py_INCREF(result);
return result;
}
// pickle support courtesy of "Ralf W. Grosse-Kunstleve" <rwgk@cci.lbl.gov>
if (!BOOST_CSTD_::strcmp(name, "__safe_for_unpickling__"))
{
return PyInt_FromLong(1);
}
if (!BOOST_CSTD_::strcmp(name, "__reduce__"))
{
ref target(as_object(this), ref::increment_count);
return bound_function::create(target, global_class_reduce());
}
ref local_attribute = m_name_space.get_item(string(name).reference());
if (local_attribute.get())
return local_attribute.release();
// In case there are no bases...
PyErr_SetString(PyExc_AttributeError, name);
// Check bases
for (std::size_t i = 0; i < m_bases.size(); ++i)
{
if (PyErr_ExceptionMatches(PyExc_AttributeError))
PyErr_Clear(); // we're going to try a base class
else if (PyErr_Occurred())
break; // Other errors count, though!
PyObject* base_attribute = PyObject_GetAttrString(m_bases[i].get(), const_cast<char*>(name));
if (base_attribute != 0)
{
// Unwind the actual underlying function from unbound Python class
// methods in case of multiple inheritance from real Python
// classes. Python stubbornly insists that the first argument to a
// method must be a true Python instance object otherwise. Do not
// unwrap bound methods; that would interfere with intended semantics.
if (PyMethod_Check(base_attribute)
&& reinterpret_cast<PyMethodObject*>(base_attribute)->im_self == 0)
{
PyObject* function
= reinterpret_cast<PyMethodObject*>(base_attribute)->im_func;
Py_INCREF(function);
Py_DECREF(base_attribute);
return function;
}
else
{
return base_attribute;
}
}
}
return 0;
}
// Mostly copied wholesale from Python's classobject.c
PyObject* class_base::repr() const
{
PyObject *mod = PyDict_GetItemString(
m_name_space.get(), const_cast<char*>("__module__"));
unsigned long address = reinterpret_cast<unsigned long>(this);
string result = (mod == NULL || !PyString_Check(mod))
? string("<extension class %s at %lx>") % tuple(m_name, address)
: string("<extension class %s.%s at %lx>") % tuple(ref(mod, ref::increment_count), m_name, address);
return result.reference().release();
}
int class_base::setattr(const char* name, PyObject* value)
{
if (is_special_name(name)
&& BOOST_CSTD_::strcmp(name, "__doc__") != 0
&& BOOST_CSTD_::strcmp(name, "__name__") != 0)
{
boost::python::string message("Special attribute names other than '__doc__' and '__name__' are read-only, in particular: ");
PyErr_SetObject(PyExc_TypeError, (message + name).get());
throw error_already_set();
}
if (PyCallable_Check(value))
detail::enable_named_method(this, name);
return PyDict_SetItemString(
m_name_space.reference().get(), const_cast<char*>(name), value);
}
bool class_base::initialize_instance(instance* obj, PyObject* args, PyObject* keywords)
{
// Getting the init function off the obj should result in a
// bound method.
PyObject* const init_function = obj->getattr("__init__", false);
if (init_function == 0)
{
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear(); // no __init__? That's legal.
}
else {
return false; // Something else? Keep the error
}
}
else
{
// Manage the reference to the bound function
ref init_function_holder(init_function);
// Declare a ref to manage the result of calling __init__ (which should be None).
ref init_result(
PyEval_CallObjectWithKeywords(init_function, args, keywords));
}
return true;
}
void class_base::instance_dealloc(PyObject* obj) const
{
Py_INCREF(obj); // This allows a __del__ function to revive the obj
PyObject* exc_type;
PyObject* exc_value;
PyObject* exc_traceback;
PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
// This scope ensures that the reference held by del_function doesn't release
// the last reference and delete the object recursively (infinitely).
{
ref del_function;
try {
instance* const target = boost::python::downcast<boost::python::instance>(obj);
del_function = ref(target->getattr("__del__", false), ref::null_ok);
}
catch(...) {
}
if (del_function.get() != 0)
{
ref result(PyEval_CallObject(del_function.get(), (PyObject *)NULL), ref::null_ok);
if (result.get() == NULL)
report_ignored_exception(del_function.get());
}
}
PyErr_Restore(exc_type, exc_value, exc_traceback);
if (--obj->ob_refcnt <= 0)
delete_instance(obj);
}
}
instance::instance(PyTypeObject* class_)
: boost::python::detail::base_object<PyObject>(class_)
{
}
instance::~instance()
{
}
PyObject* instance::getattr(const char* name, bool use_special_function)
{
if (!BOOST_CSTD_::strcmp(name, "__dict__"))
{
if (PyEval_GetRestricted()) {
PyErr_SetString(PyExc_RuntimeError,
"instance.__dict__ not accessible in restricted mode");
return 0;
}
Py_INCREF(m_name_space.get());
return m_name_space.get();
}
if (!BOOST_CSTD_::strcmp(name, "__class__"))
{
Py_INCREF(this->ob_type);
return as_object(this->ob_type);
}
if (!BOOST_CSTD_::strcmp(name, "__reduce__"))
{
return detail::bound_function::create(ref(this, ref::increment_count), global_instance_reduce());
}
ref local_attribute = m_name_space.get_item(string(name).reference());
if (local_attribute.get())
return local_attribute.release();
// Check its class.
PyObject* function =
PyObject_GetAttrString(as_object(this->ob_type), const_cast<char*>(name));
if (function == 0 && !use_special_function)
{
return 0;
}
ref class_attribute;
if (function != 0)
{
// This will throw if the attribute wasn't found
class_attribute = ref(function);
}
else
{
// Clear the error while we try special methods method (if any).
PyErr_Clear();
// First we try the special method that comes from concatenating
// "__getattr__" and <name> and 2 trailing underscores. This is an
// extension to regular Python class functionality.
const string specific_getattr_name(detail::getattr_string() + name + "__");
PyObject* getattr_method = PyObject_GetAttr(
as_object(this->ob_type), specific_getattr_name.get());
// Use just the first arg to PyEval_CallFunction if found
char* arg_format = const_cast<char*>("(O)");
// Try for the regular __getattr__ method if not found
if (getattr_method == 0)
{
PyErr_Clear();
getattr_method = PyObject_GetAttrString(
as_object(this->ob_type), const_cast<char*>("__getattr__"));
// Use both args to PyEval_CallFunction
arg_format = const_cast<char*>("(Os)");
}
// If there is no such method, throw now.
if (PyErr_Occurred())
{
PyErr_SetString(PyExc_AttributeError, name);
return 0;
}
// Take ownership of the method
ref owner(getattr_method);
// Call it to get the attribute.
return PyEval_CallFunction(getattr_method, arg_format, this, name);
}
if (!PyCallable_Check(class_attribute.get()))
{
PyErr_Clear();
return class_attribute.release();
}
else
{
return detail::bound_function::create(ref(this, ref::increment_count), class_attribute);
}
}
// instance::setattr_dict
//
// Implements setattr() functionality for the "__dict__" attribute
//
int instance::setattr_dict(PyObject* value)
{
if (PyEval_GetRestricted())
{
PyErr_SetString(PyExc_RuntimeError,
"__dict__ not accessible in restricted mode");
return -1;
}
if (value == 0 || !PyDict_Check(value))
{
PyErr_SetString(PyExc_TypeError,
"__dict__ must be set to a dictionary");
return -1;
}
m_name_space = dictionary(ref(value, ref::increment_count));
return 0;
}
// instance::setattr -
//
// Implements the setattr() and delattr() functionality for our own instance
// objects, using the standard Python interface: if value == 0, we are deleting
// the attribute, and returns 0 unless an error occurred.
int instance::setattr(const char* name, PyObject* value)
{
if (BOOST_CSTD_::strcmp(name, "__class__") == 0)
{
PyErr_SetString(PyExc_TypeError, "__class__ attribute is read-only");
throw error_already_set();
}
if (BOOST_CSTD_::strcmp(name, "__dict__") == 0)
return setattr_dict(value);
// Try to find an appropriate "specific" setter or getter method, either
// __setattr__<name>__(value) or __delattr__<name>__(). This is an extension
// to regular Python class functionality.
const string& base_name = value ? detail::setattr_string() : detail::delattr_string();
const string specific_method_name(base_name + name + "__");
ref special_method(
PyObject_GetAttr(as_object(this->ob_type), specific_method_name.get()),
ref::null_ok);
PyObject* result_object = 0;
if (special_method.get() != 0)
{
// The specific function was found; call it now. Note that if value is
// not included in the format string, it is ignored.
char* format_string = const_cast<char*>(value ? "(OO)" : "(O)");
result_object = PyEval_CallFunction(special_method.get(), format_string, this, value);
}
else
{
// If not found, try the usual __setattr__(name, value) or
// __delattr__(name) functions.
PyErr_Clear();
special_method.reset(
PyObject_GetAttr(as_object(this->ob_type), base_name.get()),
ref::null_ok);
if (special_method.get() != 0)
{
// The special function was found; call it now. Note that if value
// is not included in the format string, it is ignored.
char* format_string = const_cast<char*>(value ? "(OsO)" : "(Os)");
result_object = PyEval_CallFunction(
special_method.get(), format_string, this, name, value);
}
}
// If we found an appropriate special method, handle the return value.
if (special_method.get() != 0)
{
ref manage_result(result_object);
return 0;
}
PyErr_Clear(); // Nothing was found; clear the python error state
if (value == 0) // Try to remove the attribute from our name space
{
const int result = PyDict_DelItemString(m_name_space.reference().get(),
const_cast<char*>(name));
if (result < 0)
{
PyErr_Clear();
PyErr_SetString(PyExc_AttributeError, "delete non-existing instance attribute");
}
return result;
}
else // Change the specified item in our name space
{
return PyDict_SetItemString(m_name_space.reference().get(),
const_cast<char*>(name), value);
}
}
PyObject* instance::call(PyObject* args, PyObject* keywords)
{
return PyEval_CallObjectWithKeywords(
ref(getattr("__call__")).get(), // take possession of the result from getattr()
args, keywords);
}
PyObject* instance::repr()
{
return callback<PyObject*>::call_method(this, "__repr__");
}
int instance::compare(PyObject* other)
{
return callback<int>::call_method(this, "__cmp__", other);
}
PyObject* instance::str()
{
return callback<PyObject*>::call_method(this, "__str__");
}
long instance::hash()
{
return callback<long>::call_method(this, "__hash__");
}
int instance::length()
{
return callback<int>::call_method(this, "__len__");
}
PyObject* instance::get_subscript(PyObject* key)
{
return callback<PyObject*>::call_method(this, "__getitem__", key);
}
void instance::set_subscript(PyObject* key, PyObject* value)
{
if (value == 0)
callback<void>::call_method(this, "__delitem__", key);
else
callback<void>::call_method(this, "__setitem__", key, value);
}
PyObject* instance::get_slice(int start, int finish)
{
return callback<PyObject*>::call_method(this, "__getslice__", start, finish);
}
void instance::set_slice(int start, int finish, PyObject* value)
{
if (value == 0)
callback<void>::call_method(this, "__delslice__", start, finish);
else
callback<void>::call_method(this, "__setslice__", start, finish, value);
}
PyObject* instance::add(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__add__", other);
}
PyObject* instance::subtract(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__sub__", other);
}
PyObject* instance::multiply(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__mul__", other);
}
PyObject* instance::divide(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__div__", other);
}
PyObject* instance::remainder(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__mod__", other);
}
PyObject* instance::divmod(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__divmod__", other);
}
PyObject* instance::power(PyObject* exponent, PyObject* modulus)
{
if (as_object(modulus->ob_type) == Py_None)
return callback<PyObject*>::call_method(this, "__pow__", exponent);
else
return callback<PyObject*>::call_method(this, "__pow__", exponent, modulus);
}
PyObject* instance::negative()
{
return callback<PyObject*>::call_method(this, "__neg__");
}
PyObject* instance::positive()
{
return callback<PyObject*>::call_method(this, "__pos__");
}
PyObject* instance::absolute()
{
return callback<PyObject*>::call_method(this, "__abs__");
}
int instance::nonzero()
{
return callback<bool>::call_method(this, "__nonzero__");
}
PyObject* instance::invert()
{
return callback<PyObject*>::call_method(this, "__invert__");
}
PyObject* instance::lshift(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__lshift__", other);
}
PyObject* instance::rshift(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__rshift__", other);
}
PyObject* instance::do_and(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__and__", other);
}
PyObject* instance::do_xor(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__xor__", other);
}
PyObject* instance::do_or(PyObject* other)
{
return callback<PyObject*>::call_method(this, "__or__", other);
}
int instance::coerce(PyObject** x, PyObject** y)
{
assert(this == *x);
// Coerce must return a tuple
tuple result(callback<tuple>::call_method(this, "__coerce__", *y));
*x = result[0].release();
*y = result[1].release();
return 0;
}
PyObject* instance::as_int()
{
return callback<PyObject*>::call_method(this, "__int__");
}
PyObject* instance::as_long()
{
return callback<PyObject*>::call_method(this, "__long__");
}
PyObject* instance::as_float()
{
return callback<PyObject*>::call_method(this, "__float__");
}
PyObject* instance::oct()
{
return callback<PyObject*>::call_method(this, "__oct__");
}
PyObject* instance::hex()
{
return callback<PyObject*>::call_method(this, "__hex__");
}
namespace {
struct named_capability
{
const char* name;
detail::type_object_base::capability capability;
};
const named_capability enablers[] =
{
{ "__hash__", detail::type_object_base::hash },
{ "__cmp__", detail::type_object_base::compare },
{ "__repr__", detail::type_object_base::repr },
{ "__str__", detail::type_object_base::str },
{ "__call__", detail::type_object_base::call },
{ "__getattr__", detail::type_object_base::getattr },
{ "__setattr__", detail::type_object_base::setattr },
{ "__len__", detail::type_object_base::mapping_length },
{ "__len__", detail::type_object_base::sequence_length },
{ "__getitem__", detail::type_object_base::mapping_subscript },
{ "__getitem__", detail::type_object_base::sequence_item },
{ "__setitem__", detail::type_object_base::mapping_ass_subscript },
{ "__setitem__", detail::type_object_base::sequence_ass_item },
{ "__delitem__", detail::type_object_base::mapping_ass_subscript },
{ "__delitem__", detail::type_object_base::sequence_ass_item },
{ "__getslice__", detail::type_object_base::sequence_slice },
{ "__setslice__", detail::type_object_base::sequence_ass_slice },
{ "__delslice__", detail::type_object_base::sequence_ass_slice },
{ "__add__", detail::type_object_base::number_add },
{ "__sub__", detail::type_object_base::number_subtract },
{ "__mul__", detail::type_object_base::number_multiply },
{ "__div__", detail::type_object_base::number_divide },
{ "__mod__", detail::type_object_base::number_remainder },
{ "__divmod__", detail::type_object_base::number_divmod },
{ "__pow__", detail::type_object_base::number_power },
{ "__neg__", detail::type_object_base::number_negative },
{ "__pos__", detail::type_object_base::number_positive },
{ "__abs__", detail::type_object_base::number_absolute },
{ "__nonzero__", detail::type_object_base::number_nonzero },
{ "__invert__", detail::type_object_base::number_invert },
{ "__lshift__", detail::type_object_base::number_lshift },
{ "__rshift__", detail::type_object_base::number_rshift },
{ "__and__", detail::type_object_base::number_and },
{ "__xor__", detail::type_object_base::number_xor },
{ "__or__", detail::type_object_base::number_or },
{ "__coerce__", detail::type_object_base::number_coerce },
{ "__int__", detail::type_object_base::number_int },
{ "__long__", detail::type_object_base::number_long },
{ "__float__", detail::type_object_base::number_float },
{ "__oct__", detail::type_object_base::number_oct },
{ "__hex__", detail::type_object_base::number_hex }
};
bool is_prefix(const char* s1, const char* s2)
{
while (*s1 != 0 && *s2 != 0 && *s1 == *s2)
++s1, ++s2;
return *s1 == 0;
}
bool is_special_name(const char* name)
{
if (name[0] != '_' || name[1] != '_' || name[2] == 0 || name[3] == 0)
return false;
std::size_t name_length = BOOST_CSTD_::strlen(name);
return name[name_length - 1] == '_' && name[name_length - 2] == '_';
}
}
namespace detail {
// Enable the special handler for methods of the given name, if any.
void enable_named_method(boost::python::detail::class_base* type_obj, const char* name)
{
const std::size_t num_enablers = sizeof(enablers) / sizeof(enablers[0]);
// Make sure this ends with "__" since we'll only compare the head of the
// string. This is done to make the __getattr__<name>__/__setattr__<name>__
// extension work.
if (!is_special_name(name))
return;
for (std::size_t i = 0; i < num_enablers; ++i)
{
if (is_prefix(enablers[i].name + 2, name + 2))
{
type_obj->enable(enablers[i].capability);
}
}
}
}
namespace {
// Enable any special methods which are enabled in the base class.
void enable_special_methods(boost::python::detail::class_base* derived, const tuple& bases, const dictionary& name_space)
{
for (std::size_t i = 0; i < bases.size(); ++i)
{
PyObject* base = bases[i].get();
for (std::size_t n = 0; n < PY_ARRAY_LENGTH(enablers); ++n)
{
ref attribute(
PyObject_GetAttrString(base, const_cast<char*>(enablers[n].name)),
ref::null_ok);
PyErr_Clear();
if (attribute.get() != 0 && PyCallable_Check(attribute.get()))
detail::add_capability(enablers[n].capability, derived);
}
}
list keys(name_space.keys());
for (std::size_t j = 0, len = keys.size(); j < len; ++j)
{
string name_obj(keys.get_item(j));
const char* name = name_obj.c_str();
if (!is_special_name(name))
continue;
for (std::size_t i = 0; i < PY_ARRAY_LENGTH(enablers); ++i)
{
if (is_prefix(enablers[i].name + 2, name + 2))
{
detail::add_capability(enablers[i].capability, derived);
}
}
}
}
void add_current_module_name(dictionary& name_space)
{
static string module_key("__module__", string::interned);
// If the user didn't specify a __module__ attribute already
if (name_space.get_item(module_key).get() == 0)
{
if (module_builder::initializing())
{
// The global __name__ is not properly set in this case
name_space.set_item(module_key, module_builder::name());
}
else
{
// Get the module name from the global __name__
PyObject *globals = PyEval_GetGlobals();
if (globals != NULL)
{
PyObject *module_name = PyDict_GetItemString(globals, const_cast<char*>("__name__"));
if (module_name != NULL)
name_space.set_item(module_key, module_name);
}
}
}
}
}
void adjust_slice_indices(PyObject* obj, int& start, int& finish)
{
int length = callback<int>::call_method(obj, "__len__");
// This is standard Python class behavior.
if (start < 0)
start += length;
if (finish < 0)
finish += length;
// This is not
if (start < 0)
start = 0;
if (finish < 0)
finish = 0;
}
namespace detail {
const string& setattr_string()
{
static string x("__setattr__", string::interned);
return x;
}
const string& getattr_string()
{
static string x("__getattr__", string::interned);
return x;
}
const string& delattr_string()
{
static string x("__delattr__", string::interned);
return x;
}
}
}} // namespace boost::python

683
src/extension_class.cpp Normal file
View File

@@ -0,0 +1,683 @@
// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and
// distribute this software is granted provided this copyright notice appears
// in all copies. This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
// The author gratefully acknowleges the support of Dragon Systems, Inc., in
// producing this work.
//
// Revision History:
// 04 Mar 01 Use PyObject_INIT() instead of trying to hand-initialize (David Abrahams)
#include <boost/python/detail/extension_class.hpp>
#include <cstring>
#include <boost/utility.hpp>
namespace boost { namespace python {
namespace detail {
struct operator_dispatcher
: public PyObject
{
static PyTypeObject type_obj;
static PyNumberMethods number_methods;
static operator_dispatcher* create(const ref& o, const ref& s);
ref m_object;
ref m_self;
// data members for allocation/deallocation optimization
operator_dispatcher* m_free_list_link;
static operator_dispatcher* free_list;
private:
// only accessible through create()
operator_dispatcher(const ref& o, const ref& s);
};
operator_dispatcher* operator_dispatcher::free_list = 0;
}}} // namespace boost::python::detail
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
inline PyObject* to_python(boost::python::detail::operator_dispatcher* n) { return n; }
BOOST_PYTHON_END_CONVERSION_NAMESPACE
namespace boost { namespace python {
tuple standard_coerce(ref l, ref r)
{
// Introduced sequence points for exception-safety.
ref first(detail::operator_dispatcher::create(l, l));
ref second(r->ob_type == &detail::operator_dispatcher::type_obj
? r
: ref(detail::operator_dispatcher::create(r, ref())));
return tuple(first, second);
}
namespace detail {
enum { unwrap_exception_code = -1000 };
int unwrap_args(PyObject* left, PyObject* right, PyObject*& self, PyObject*& other)
{
if (left->ob_type != &operator_dispatcher::type_obj ||
right->ob_type != &operator_dispatcher::type_obj)
{
PyErr_SetString(PyExc_RuntimeError, "operator_dispatcher::unwrap_args(): expecting operator_dispatcher arguments only!");
return unwrap_exception_code;
}
typedef reference<operator_dispatcher> DPtr;
DPtr lwrapper(static_cast<operator_dispatcher*>(left), DPtr::increment_count);
DPtr rwrapper(static_cast<operator_dispatcher*>(right), DPtr::increment_count);
if (lwrapper->m_self.get() != 0)
{
self = lwrapper->m_self.get();
other = rwrapper->m_object.get();
return 0;
}
else
{
self = rwrapper->m_self.get();
other = lwrapper->m_object.get();
return 1;
}
}
int unwrap_pow_args(PyObject* left, PyObject* right, PyObject* m,
PyObject*& self, PyObject*& first, PyObject*& second)
{
if (left->ob_type != &operator_dispatcher::type_obj ||
right->ob_type != &operator_dispatcher::type_obj ||
m->ob_type != &operator_dispatcher::type_obj)
{
PyErr_SetString(PyExc_RuntimeError, "operator_dispatcher::unwrap_pow_args(): expecting operator_dispatcher arguments only!");
return unwrap_exception_code;
}
typedef reference<operator_dispatcher> DPtr;
DPtr lwrapper(static_cast<operator_dispatcher*>(left), DPtr::increment_count);
DPtr rwrapper(static_cast<operator_dispatcher*>(right), DPtr::increment_count);
DPtr mwrapper(static_cast<operator_dispatcher*>(m), DPtr::increment_count);
if (lwrapper->m_self.get() != 0)
{
self = lwrapper->m_self.get();
first = rwrapper->m_object.get();
second = mwrapper->m_object.get();
return 0;
}
else if (rwrapper->m_self.get() != 0)
{
self = rwrapper->m_self.get();
first = lwrapper->m_object.get();
second = mwrapper->m_object.get();
return 1;
}
else
{
self = mwrapper->m_self.get();
first = lwrapper->m_object.get();
second = rwrapper->m_object.get();
return 2;
}
}
extension_instance* get_extension_instance(PyObject* p)
{
// The object's type will just be some class_t<extension_instance> object,
// but if its meta-type is right, then it is an extension_instance.
if (p->ob_type->ob_type != extension_meta_class())
{
PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name);
throw boost::python::argument_error();
}
return static_cast<extension_instance*>(p);
}
void
extension_instance::add_implementation(std::auto_ptr<instance_holder_base> holder)
{
for (held_objects::const_iterator p = m_wrapped_objects.begin();
p != m_wrapped_objects.end(); ++p)
{
if (typeid(*holder) == typeid(**p))
{
PyErr_SetString(PyExc_RuntimeError, "Base class already initialized");
throw error_already_set();
}
}
m_wrapped_objects.push_back(holder.release());
}
extension_instance::extension_instance(PyTypeObject* class_)
: instance(class_)
{
}
extension_instance::~extension_instance()
{
for (held_objects::const_iterator p = m_wrapped_objects.begin(),
finish = m_wrapped_objects.end();
p != finish; ++p)
{
delete *p;
}
}
meta_class<extension_instance>* extension_meta_class()
{
static meta_class<extension_instance> result;
return &result;
}
typedef class_t<extension_instance> extension_class_t;
bool is_subclass(const extension_class_t* derived,
const PyObject* possible_base)
{
tuple bases = derived->bases();
for (std::size_t i = 0, size = bases.size(); i < size; ++i)
{
const PyObject* base = bases[i].get();
if (base == possible_base)
return true;
if (base->ob_type == extension_meta_class())
{
const extension_class_t* base_class = downcast<const extension_class_t>(base);
if (is_subclass(base_class, possible_base))
return true;
}
}
return false;
}
// Return true iff obj is an obj of target_class
bool is_instance(extension_instance* obj,
class_t<extension_instance>* target_class)
{
if (obj->ob_type == target_class)
return true;
else
{
return is_subclass(
downcast<class_t<extension_instance> >(obj->ob_type).get(),
as_object(target_class));
}
}
void two_string_error(PyObject* exception_object, const char* format, const char* s1, const char* s2)
{
char buffer[256];
std::size_t format_length = BOOST_CSTD_::strlen(format);
std::size_t length1 = BOOST_CSTD_::strlen(s1);
std::size_t length2 = BOOST_CSTD_::strlen(s2);
std::size_t additional_length = length1 + length2;
if (additional_length + format_length > format_length - 1)
{
std::size_t difference = sizeof(buffer) - 1 - additional_length;
length1 -= difference / 2;
additional_length -= difference / 2;
}
sprintf(buffer, format, length1, s1, length2, s2);
PyErr_SetString(exception_object, buffer);
if (exception_object == PyExc_TypeError)
throw argument_error();
else
throw error_already_set();
}
// This is called when an attempt has been made to convert the given obj to
// a C++ type for which it doesn't have any obj data. In that case, either
// the obj was not derived from the target_class, or the appropriate
// __init__ function wasn't called to initialize the obj data of the target class.
void report_missing_instance_data(
extension_instance* obj, // The object being converted
class_t<extension_instance>* target_class, // the extension class of the C++ type
const std::type_info& target_typeid, // The typeid of the C++ type
bool target_is_ptr)
{
char buffer[256];
if (is_instance(obj, target_class))
{
if (target_is_ptr)
{
two_string_error(PyExc_RuntimeError,
"Object of extension class '%.*s' does not wrap <%.*s>.",
obj->ob_type->tp_name, target_typeid.name());
}
else
{
const char message[] = "__init__ function for extension class '%.*s' was never called.";
sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1,
target_class->tp_name);
}
PyErr_SetString(PyExc_RuntimeError, buffer);
}
else if (target_class == 0)
{
const char message[] = "Cannot convert to <%.*s>; its Python class was never created or has been deleted.";
sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, target_typeid.name());
PyErr_SetString(PyExc_RuntimeError, buffer);
}
else
{
two_string_error(PyExc_TypeError, "extension class '%.*s' is not convertible into '%.*s'.",
obj->ob_type->tp_name, target_class->tp_name);
}
}
void report_missing_instance_data(
extension_instance* obj, // The object being converted
class_t<extension_instance>* target_class, // the extension class of the C++ type
const std::type_info& target_typeid) // The typeid of the C++ type
{
report_missing_instance_data(obj, target_class, target_typeid, false);
}
void report_missing_ptr_data(
extension_instance* obj, // The object being converted
class_t<extension_instance>* target_class, // the extension class of the C++ type
const std::type_info& target_typeid) // The typeid of the C++ type
{
report_missing_instance_data(obj, target_class, target_typeid, true);
}
void report_missing_class_object(const std::type_info& info)
{
char buffer[256];
const char message[] = "Cannot convert <%.*s> to python; its Python class was never created or has been deleted.";
sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, info.name());
PyErr_SetString(PyExc_RuntimeError, buffer);
throw error_already_set();
}
void report_released_smart_pointer(const std::type_info& info)
{
char buffer[256];
const char message[] = "Converting from python, pointer or smart pointer to <%.*s> is NULL.";
sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, info.name());
PyErr_SetString(PyExc_RuntimeError, buffer);
throw argument_error();
}
read_only_setattr_function::read_only_setattr_function(const char* name)
: m_name(name)
{
}
PyObject* read_only_setattr_function::do_call(PyObject* /*args*/, PyObject* /*keywords*/) const
{
PyErr_SetObject(PyExc_AttributeError, ("'" + m_name + "' attribute is read-only").get());
return 0;
}
const char* read_only_setattr_function::description() const
{
return "uncallable";
}
extension_class_base::extension_class_base(const char* name)
: class_t<extension_instance>(
extension_meta_class(), string(name), tuple(), dictionary())
{
}
// This function is used in from_python() to convert wrapped classes that are
// related by inheritance. The problem is this: although C++ provides all necessary
// conversion operators, source and target of a conversion must be known at compile
// time. However, in Python we want to convert classes at runtime. The solution is to
// generate conversion functions at compile time, register them within the appropriate
// class objects and call them when a particular runtime conversion is required.
// If functions for any possible conversion have to be stored, their number will grow
// qudratically. To reduce this number, we actually store only conversion functions
// between adjacent levels in the inheritance tree. By traversing the tree recursively,
// we can build any allowed conversion as a concatenation of simple conversions. This
// traversal is done in the functions try_base_class_conversions() and
// try_derived_class_conversions(). If a particular conversion is impossible, all
// conversion functions will return a NULL pointer.
// The function extract_object_from_holder() attempts to actually extract the pointer
// to the contained object from an instance_holder_base (a wrapper class). A conversion
// of the held object to 'T *' is allowed when the conversion
// 'dynamic_cast<instance_holder<T> *>(an_instance_holder_base)' succeeds.
void* extension_class_base::try_class_conversions(instance_holder_base* object) const
{
void* result = try_derived_class_conversions(object);
if (result)
return result;
if (!object->held_by_value())
return try_base_class_conversions(object);
else
return 0;
}
void* extension_class_base::try_base_class_conversions(instance_holder_base* object) const
{
for (std::size_t i = 0; i < base_classes().size(); ++i)
{
if (base_classes()[i].convert == 0)
continue;
void* result1 = base_classes()[i].class_object->extract_object_from_holder(object);
if (result1)
return (*base_classes()[i].convert)(result1);
void* result2 = base_classes()[i].class_object->try_base_class_conversions(object);
if (result2)
return (*base_classes()[i].convert)(result2);
}
return 0;
}
void* extension_class_base::try_derived_class_conversions(instance_holder_base* object) const
{
for (std::size_t i = 0; i < derived_classes().size(); ++i)
{
void* result1 = derived_classes()[i].class_object->extract_object_from_holder(object);
if (result1)
return (*derived_classes()[i].convert)(result1);
void* result2 = derived_classes()[i].class_object->try_derived_class_conversions(object);
if (result2)
return (*derived_classes()[i].convert)(result2);
}
return 0;
}
void extension_class_base::add_method(function* method, const char* name)
{
add_method(reference<function>(method), name);
}
void extension_class_base::add_method(reference<function> method, const char* name)
{
// Add the attribute to the computed target
function::add_to_namespace(method, name, this->dict().get());
// If it is a special member function it should be enabled both here and there.
detail::enable_named_method(this, name);
}
void extension_class_base::add_constructor_object(function* init_fn)
{
add_method(init_fn, "__init__");
}
void extension_class_base::add_setter_method(function* setter_, const char* name)
{
reference<function> setter(setter_);
add_method(setter, (detail::setattr_string() + name + "__").c_str());
}
void extension_class_base::add_getter_method(function* getter_, const char* name)
{
reference<function> getter(getter_);
add_method(getter, (detail::getattr_string() + name + "__").c_str());
}
void extension_class_base::set_attribute(const char* name, PyObject* x_)
{
ref x(x_);
set_attribute(name, x);
}
void extension_class_base::set_attribute(const char* name, ref x)
{
dict().set_item(string(name), x);
if (PyCallable_Check(x.get()))
detail::enable_named_method(this, name);
}
operator_dispatcher::operator_dispatcher(const ref& o, const ref& s)
: m_object(o), m_self(s), m_free_list_link(0)
{
PyObject* self = this;
PyObject_INIT(self, &type_obj);
}
operator_dispatcher*
operator_dispatcher::create(const ref& object, const ref& self)
{
operator_dispatcher* const result = free_list;
if (result == 0)
return new operator_dispatcher(object, self);
free_list = result->m_free_list_link;
result->m_object = object;
result->m_self = self;
PyObject* result_as_pyobject = result;
PyObject_INIT(result_as_pyobject, &type_obj);
return result;
}
extern "C"
{
void operator_dispatcher_dealloc(PyObject* self)
{
operator_dispatcher* obj = static_cast<operator_dispatcher*>(self);
obj->m_free_list_link = operator_dispatcher::free_list;
operator_dispatcher::free_list = obj;
obj->m_object.reset();
obj->m_self.reset();
}
int operator_dispatcher_coerce(PyObject** l, PyObject** r)
{
Py_INCREF(*l);
try
{
*r = operator_dispatcher::create(ref(*r, ref::increment_count), ref());
}
catch(...)
{
handle_exception();
return -1;
}
return 0;
}
#define PY_DEFINE_OPERATOR(id, symbol) \
PyObject* operator_dispatcher_call_##id(PyObject* left, PyObject* right) \
{ \
/* unwrap the arguments from their OperatorDispatcher */ \
PyObject* self; \
PyObject* other; \
int reverse = unwrap_args(left, right, self, other); \
if (reverse == unwrap_exception_code) \
return 0; \
\
/* call the function */ \
PyObject* result = \
PyEval_CallMethod(self, \
const_cast<char*>(reverse ? "__r" #id "__" : "__" #id "__"), \
const_cast<char*>("(O)"), \
other); \
if (result == 0 && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError)) \
{ \
PyErr_Clear(); \
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for " #symbol); \
} \
return result; \
}
PY_DEFINE_OPERATOR(add, +)
PY_DEFINE_OPERATOR(sub, -)
PY_DEFINE_OPERATOR(mul, *)
PY_DEFINE_OPERATOR(div, /)
PY_DEFINE_OPERATOR(mod, %)
PY_DEFINE_OPERATOR(divmod, divmod)
PY_DEFINE_OPERATOR(lshift, <<)
PY_DEFINE_OPERATOR(rshift, >>)
PY_DEFINE_OPERATOR(and, &)
PY_DEFINE_OPERATOR(xor, ^)
PY_DEFINE_OPERATOR(or, |)
/* coercion rules for heterogeneous pow():
pow(Foo, int): left, right coerced; m: None => reverse = 0
pow(int, Foo): left, right coerced; m: None => reverse = 1
pow(Foo, int, int): left, right, m coerced => reverse = 0
pow(int, Foo, int): left, right, m coerced => reverse = 1
pow(int, int, Foo): left, right, m coerced => reverse = 2
pow(Foo, Foo, int): left, right coerced; m coerced twice => reverse = 0
pow(Foo, int, Foo): left, right, m coerced => reverse = 0
pow(int, Foo, Foo): left, right, m coerced => reverse = 1
*/
PyObject* operator_dispatcher_call_pow(PyObject* left, PyObject* right, PyObject* m)
{
int reverse;
PyObject* self;
PyObject* first;
PyObject* second;
if (m->ob_type == Py_None->ob_type)
{
reverse = unwrap_args(left, right, self, first);
second = m;
}
else
{
reverse = unwrap_pow_args(left, right, m, self, first, second);
}
if (reverse == unwrap_exception_code)
return 0;
// call the function
PyObject* result =
PyEval_CallMethod(self,
const_cast<char*>((reverse == 0)
? "__pow__"
: (reverse == 1)
? "__rpow__"
: "__rrpow__"),
const_cast<char*>("(OO)"),
first, second);
if (result == 0 &&
(PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_TypeError) ||
PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError)))
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for pow()");
}
return result;
}
int operator_dispatcher_call_cmp(PyObject* left, PyObject* right)
{
// unwrap the arguments from their OperatorDispatcher
PyObject* self;
PyObject* other;
int reverse = unwrap_args(left, right, self, other);
if (reverse == unwrap_exception_code)
return -1;
// call the function
PyObject* result =
PyEval_CallMethod(self,
const_cast<char*>(reverse ? "__rcmp__" : "__cmp__"),
const_cast<char*>("(O)"),
other);
if (result == 0)
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for cmp() or <");
return -1;
}
else
{
try
{
return BOOST_PYTHON_CONVERSION::from_python(result, type<int>());
}
catch(...)
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "cmp() didn't return int");
return -1;
}
}
}
} // extern "C"
PyTypeObject operator_dispatcher::type_obj =
{
PyObject_HEAD_INIT(&PyType_Type)
0,
const_cast<char*>("operator_dispatcher"),
sizeof(operator_dispatcher),
0,
&operator_dispatcher_dealloc,
0,
0,
0,
&operator_dispatcher_call_cmp,
0,
&operator_dispatcher::number_methods,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
};
PyNumberMethods operator_dispatcher::number_methods =
{
&operator_dispatcher_call_add,
&operator_dispatcher_call_sub,
&operator_dispatcher_call_mul,
&operator_dispatcher_call_div,
&operator_dispatcher_call_mod,
&operator_dispatcher_call_divmod,
&operator_dispatcher_call_pow,
0,
0,
0,
0,
0,
&operator_dispatcher_call_lshift,
&operator_dispatcher_call_rshift,
&operator_dispatcher_call_and,
&operator_dispatcher_call_xor,
&operator_dispatcher_call_or,
&operator_dispatcher_coerce,
0,
0,
0,
0,
0
};
} // namespace detail
}} // namespace boost::python

876
src/gen_extclass.py Normal file
View File

@@ -0,0 +1,876 @@
from gen_function import *
import string
def gen_extclass(args):
return (
"""// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and
// distribute this software is granted provided this copyright notice appears
// in all copies. This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
// The author gratefully acknowleges the support of Dragon Systems, Inc., in
// producing this work.
//
// This file automatically generated for %d-argument constructors by
// gen_extclass.python
#ifndef EXTENSION_CLASS_DWA052000_H_
# define EXTENSION_CLASS_DWA052000_H_
# include <boost/python/detail/config.hpp>
# include <boost/python/classes.hpp>
# include <vector>
# include <boost/python/detail/none.hpp>
# include <boost/python/objects.hpp>
# include <boost/python/detail/functions.hpp>
# include <memory>
# include <boost/python/detail/init_function.hpp>
# include <typeinfo>
# include <boost/smart_ptr.hpp>
# include <boost/type_traits.hpp>
namespace boost { namespace python {
// forward declarations
template <long which, class operand> struct operators;
template <class T> struct left_operand;
template <class T> struct right_operand;
enum without_downcast_t { without_downcast };
namespace detail {
// forward declarations
class extension_instance;
class extension_class_base;
template <class T> class instance_holder;
template <class T, class U> class instance_value_holder;
template <class ref, class T> class instance_ptr_holder;
template <class Specified> struct operand_select;
template <long> struct choose_op;
template <long> struct choose_rop;
template <long> struct choose_unary_op;
template <long> struct define_operator;
meta_class<extension_instance>* extension_meta_class();
extension_instance* get_extension_instance(PyObject* p);
void report_missing_instance_data(extension_instance*, class_t<extension_instance>*, const std::type_info&);
void report_missing_ptr_data(extension_instance*, class_t<extension_instance>*, const std::type_info&);
void report_missing_class_object(const std::type_info&);
void report_released_smart_pointer(const std::type_info&);
template <class T>
T* check_non_null(T* p)
{
if (p == 0)
report_released_smart_pointer(typeid(T));
return p;
}
template <class Held> class held_instance;
typedef void* (*conversion_function_ptr)(void*);
struct base_class_info
{
base_class_info(extension_class_base* t, conversion_function_ptr f)
:class_object(t), convert(f)
{}
extension_class_base* class_object;
conversion_function_ptr convert;
};
typedef base_class_info derived_class_info;
struct add_operator_base;
class extension_class_base : public class_t<extension_instance>
{
public:
extension_class_base(const char* name);
public:
// the purpose of try_class_conversions() and its related functions
// is explained in extclass.cpp
void* try_class_conversions(instance_holder_base*) const;
void* try_base_class_conversions(instance_holder_base*) const;
void* try_derived_class_conversions(instance_holder_base*) const;
void set_attribute(const char* name, PyObject* x);
void set_attribute(const char* name, ref x);
private:
virtual void* extract_object_from_holder(instance_holder_base* v) const = 0;
virtual std::vector<base_class_info> const& base_classes() const = 0;
virtual std::vector<derived_class_info> const& derived_classes() const = 0;
protected:
friend struct add_operator_base;
void add_method(reference<function> method, const char* name);
void add_method(function* method, const char* name);
void add_constructor_object(function*);
void add_setter_method(function*, const char* name);
void add_getter_method(function*, const char* name);
};
template <class T>
class class_registry
{
public:
static extension_class_base* class_object()
{ return static_class_object; }
// Register/unregister the Python class object corresponding to T
static void register_class(extension_class_base*);
static void unregister_class(extension_class_base*);
// Establish C++ inheritance relationships
static void register_base_class(base_class_info const&);
static void register_derived_class(derived_class_info const&);
// Query the C++ inheritance relationships
static std::vector<base_class_info> const& base_classes();
static std::vector<derived_class_info> const& derived_classes();
private:
static extension_class_base* static_class_object;
static std::vector<base_class_info> static_base_class_info;
static std::vector<derived_class_info> static_derived_class_info;
};
template <bool is_pointer>
struct is_null_helper
{
template <class Ptr>
static bool test(Ptr x) { return x == 0; }
};
template <>
struct is_null_helper<false>
{
template <class Ptr>
static bool test(const Ptr& x) { return x.get() == 0; }
};
template <class Ptr>
bool is_null(const Ptr& x)
{
return is_null_helper<(is_pointer<Ptr>::value)>::test(x);
};
}}} // namespace boost::python::detail
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
// This class' only job is to define from_python and to_python converters for T
// and U. T is the class the user really intends to wrap. U is a class derived
// from T with some virtual function overriding boilerplate, or if there are no
// virtual functions, U = held_instance<T>.
template <class T, class U = boost::python::detail::held_instance<T> >
class python_extension_class_converters
{
public:
// Get an object which can be used to convert T to/from python. This is used
// as a kind of concept check by the global template
//
// PyObject* to_python(const T& x)
//
// below this class, to prevent the confusing messages that would otherwise
// pop up. Now, if T hasn't been wrapped as an extension class, the user
// will see an error message about the lack of an eligible
// py_extension_class_converters() function.
friend python_extension_class_converters py_extension_class_converters(boost::python::type<T>)
{
return python_extension_class_converters();
}
// This is a member function because in a conforming implementation, friend
// funcitons defined inline in the class body are all instantiated as soon
// as the enclosing class is instantiated. If T is not copyable, that causes
// a compiler error. Instead, we access this function through the global
// template
//
// PyObject* to_python(const T& x)
//
// defined below this class. Since template functions are instantiated only
// on demand, errors will be avoided unless T is noncopyable and the user
// writes code which causes us to try to copy a T.
PyObject* to_python(const T& x) const
{
boost::python::reference<boost::python::detail::extension_instance> result(create_instance());
result->add_implementation(
std::auto_ptr<boost::python::detail::instance_holder_base>(
new boost::python::detail::instance_value_holder<T,U>(result.get(), x)));
return result.release();
}
friend
T* non_null_from_python(PyObject* obj, boost::python::type<T*>)
{
// downcast to an extension_instance, then find the actual T
boost::python::detail::extension_instance* self = boost::python::detail::get_extension_instance(obj);
typedef std::vector<boost::python::detail::instance_holder_base*>::const_iterator iterator;
for (iterator p = self->wrapped_objects().begin();
p != self->wrapped_objects().end(); ++p)
{
boost::python::detail::instance_holder<T>* held = dynamic_cast<boost::python::detail::instance_holder<T>*>(*p);
if (held != 0)
return held->target();
// see extclass.cpp for an explanation of try_class_conversions()
void* target = boost::python::detail::class_registry<T>::class_object()->try_class_conversions(*p);
if(target)
return static_cast<T*>(target);
}
boost::python::detail::report_missing_instance_data(self, boost::python::detail::class_registry<T>::class_object(), typeid(T));
throw boost::python::argument_error();
}
// Convert to T*
friend T* from_python(PyObject* obj, boost::python::type<T*>)
{
if (obj == Py_None)
return 0;
else
return non_null_from_python(obj, boost::python::type<T*>());
}
// Extract from obj a mutable reference to the PtrType object which is holding a T.
template <class PtrType>
static PtrType& smart_ptr_reference(PyObject* obj, boost::python::type<PtrType>)
{
// downcast to an extension_instance, then find the actual T
boost::python::detail::extension_instance* self = boost::python::detail::get_extension_instance(obj);
typedef std::vector<boost::python::detail::instance_holder_base*>::const_iterator iterator;
for (iterator p = self->wrapped_objects().begin();
p != self->wrapped_objects().end(); ++p)
{
boost::python::detail::instance_ptr_holder<PtrType, T>* held =
dynamic_cast<boost::python::detail::instance_ptr_holder<PtrType, T>*>(*p);
if (held != 0)
return held->ptr();
}
boost::python::detail::report_missing_ptr_data(self, boost::python::detail::class_registry<T>::class_object(), typeid(T));
throw boost::python::argument_error();
}
// Extract from obj a constant reference to the PtrType object which is holding a T.
// If obj is None, the reference denotes a default-constructed PtrType
template <class PtrType>
static const PtrType& smart_ptr_value(PyObject* obj, boost::python::type<PtrType>)
{
if (obj == Py_None)
{
static PtrType null_ptr;
return null_ptr;
}
return smart_ptr_reference(obj, boost::python::type<PtrType>());
}
template <class PtrType>
static PyObject* smart_ptr_to_python(PtrType x)
{
if (boost::python::detail::is_null(x))
{
return boost::python::detail::none();
}
boost::python::reference<boost::python::detail::extension_instance> result(create_instance());
result->add_implementation(
std::auto_ptr<boost::python::detail::instance_holder_base>(
new boost::python::detail::instance_ptr_holder<PtrType,T>(x)));
return result.release();
}
static boost::python::reference<boost::python::detail::extension_instance> create_instance()
{
PyTypeObject* class_object = boost::python::detail::class_registry<T>::class_object();
if (class_object == 0)
boost::python::detail::report_missing_class_object(typeid(T));
return boost::python::reference<boost::python::detail::extension_instance>(
new boost::python::detail::extension_instance(class_object));
}
// Convert to const T*
friend const T* from_python(PyObject* p, boost::python::type<const T*>)
{ return from_python(p, boost::python::type<T*>()); }
// Convert to const T* const&
friend const T* from_python(PyObject* p, boost::python::type<const T*const&>)
{ return from_python(p, boost::python::type<const T*>()); }
// Convert to T* const&
friend T* from_python(PyObject* p, boost::python::type<T* const&>)
{ return from_python(p, boost::python::type<T*>()); }
// Convert to T&
friend T& from_python(PyObject* p, boost::python::type<T&>)
{ return *boost::python::detail::check_non_null(non_null_from_python(p, boost::python::type<T*>())); }
// Convert to const T&
friend const T& from_python(PyObject* p, boost::python::type<const T&>)
{ return from_python(p, boost::python::type<T&>()); }
// Convert to T
friend const T& from_python(PyObject* p, boost::python::type<T>)
{ return from_python(p, boost::python::type<T&>()); }
friend std::auto_ptr<T>& from_python(PyObject* p, boost::python::type<std::auto_ptr<T>&>)
{ return smart_ptr_reference(p, boost::python::type<std::auto_ptr<T> >()); }
friend const std::auto_ptr<T>& from_python(PyObject* p, boost::python::type<std::auto_ptr<T> >)
{ return smart_ptr_value(p, boost::python::type<std::auto_ptr<T> >()); }
friend const std::auto_ptr<T>& from_python(PyObject* p, boost::python::type<const std::auto_ptr<T>&>)
{ return smart_ptr_value(p, boost::python::type<std::auto_ptr<T> >()); }
friend PyObject* to_python(std::auto_ptr<T> x)
{ return smart_ptr_to_python(x); }
friend boost::shared_ptr<T>& from_python(PyObject* p, boost::python::type<boost::shared_ptr<T>&>)
{ return smart_ptr_reference(p, boost::python::type<boost::shared_ptr<T> >()); }
friend const boost::shared_ptr<T>& from_python(PyObject* p, boost::python::type<boost::shared_ptr<T> >)
{ return smart_ptr_value(p, boost::python::type<boost::shared_ptr<T> >()); }
friend const boost::shared_ptr<T>& from_python(PyObject* p, boost::python::type<const boost::shared_ptr<T>&>)
{ return smart_ptr_value(p, boost::python::type<boost::shared_ptr<T> >()); }
friend PyObject* to_python(boost::shared_ptr<T> x)
{ return smart_ptr_to_python(x); }
};
// Convert T to_python, instantiated on demand and only if there isn't a
// non-template overload for this function. This version is the one invoked when
// T is a wrapped class. See the first 2 functions declared in
// python_extension_class_converters above for more info.
template <class T>
PyObject* to_python(const T& x)
{
return py_extension_class_converters(boost::python::type<T>()).to_python(x);
}
BOOST_PYTHON_END_CONVERSION_NAMESPACE
namespace boost { namespace python {
BOOST_PYTHON_IMPORT_CONVERSION(python_extension_class_converters);
namespace detail {
template <class T> class instance_holder;
class read_only_setattr_function : public function
{
public:
read_only_setattr_function(const char* name);
PyObject* do_call(PyObject* args, PyObject* keywords) const;
const char* description() const;
private:
string m_name;
};
template <class From, class To>
struct define_conversion
{
static void* upcast_ptr(void* v)
{
return static_cast<To*>(static_cast<From*>(v));
}
static void* downcast_ptr(void* v)
{
return dynamic_cast<To*>(static_cast<From*>(v));
}
};
// An easy way to make an extension base class which wraps T. Note that Python
// subclasses of this class will simply be class_t<extension_instance> objects.
//
// U should be a class derived from T which overrides virtual functions with
// boilerplate code to call back into Python. See extclass_demo.h for examples.
//
// U is optional, but you won't be able to override any member functions in
// Python which are called from C++ if you don't supply it. If you just want to
// be able to use T in python without overriding member functions, you can omit
// U.
template <class T, class U = held_instance<T> >
class extension_class
: public python_extension_class_converters<T, U>, // This generates the to_python/from_python functions
public extension_class_base
{
public:
typedef T wrapped_type;
typedef U callback_type;
// Construct with a name that comes from typeid(T).name(). The name only
// affects the objects of this class are represented through repr()
extension_class();
// Construct with the given name. The name only affects the objects of this
// class are represented through repr()
extension_class(const char* name);
~extension_class();
// define constructors
""" % args
+ gen_function(
""" template <%(class A%n%:, %)>
inline void def(constructor<%(A%n%:, %)>)
// The following incantation builds a signature1, signature2,... object. It
// should _all_ get optimized away.
{ add_constructor(
%(prepend(type<A%n>::id(),
%) signature0()%()%));
}
""", args)
+
"""
// export homogeneous operators (type of both lhs and rhs is 'operator')
// usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub), Foo>());
// export homogeneous operators (type of both lhs and rhs is 'T const&')
// usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub)>());
template <long which, class Operand>
inline void def(operators<which,Operand>)
{
typedef typename operand_select<Operand>::template wrapped<T>::type true_operand;
def_operators(operators<which,true_operand>());
}
// export heterogeneous operators (type of lhs: 'left', of rhs: 'right')
// usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub), Foo>(),
// boost::python::right_operand<int const&>());
// export heterogeneous operators (type of lhs: 'T const&', of rhs: 'right')
// usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub)>(),
// boost::python::right_operand<int const&>());
template <long which, class Left, class Right>
inline void def(operators<which,Left>, right_operand<Right> r)
{
typedef typename operand_select<Left>::template wrapped<T>::type true_left;
def_operators(operators<which,true_left>(), r);
}
// export heterogeneous reverse-argument operators
// (type of lhs: 'left', of rhs: 'right')
// usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub), Foo>(),
// boost::python::left_operand<int const&>());
// export heterogeneous reverse-argument operators
// (type of lhs: 'left', of rhs: 'T const&')
// usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub)>(),
// boost::python::left_operand<int const&>());
template <long which, class Left, class Right>
inline void def(operators<which,Right>, left_operand<Left> l)
{
typedef typename operand_select<Right>::template wrapped<T>::type true_right;
def_operators(operators<which,true_right>(), l);
}
// define a function that passes Python arguments and keywords
// to C++ verbatim (as a 'tuple const&' and 'dictionary const&'
// respectively). This is useful for manual argument passing.
// It's also the only possibility to pass keyword arguments to C++.
// Fn must have a signatur that is compatible to
// PyObject* (*)(PyObject* aTuple, PyObject* aDictionary)
template <class Fn>
inline void def_raw(Fn fn, const char* name)
{
this->add_method(new_raw_arguments_function(fn), name);
}
// define member functions. In fact this works for free functions, too -
// they act like static member functions, or if they start with the
// appropriate self argument (as a pointer), they can be used just like
// ordinary member functions -- just like Python!
template <class Fn>
inline void def(Fn fn, const char* name)
{
this->add_method(new_wrapped_function(fn), name);
}
// Define a virtual member function with a default implementation.
// default_fn should be a function which provides the default implementation.
// Be careful that default_fn does not in fact call fn virtually!
template <class Fn, class DefaultFn>
inline void def(Fn fn, const char* name, DefaultFn default_fn)
{
this->add_method(new_virtual_function(type<T>(), fn, default_fn), name);
}
// Provide a function which implements x.<name>, reading from the given
// member (pm) of the T obj
template <class MemberType>
inline void def_getter(MemberType T::*pm, const char* name)
{
this->add_getter_method(new getter_function<T, MemberType>(pm), name);
}
// Provide a function which implements assignment to x.<name>, writing to
// the given member (pm) of the T obj
template <class MemberType>
inline void def_setter(MemberType T::*pm, const char* name)
{
this->add_setter_method(new setter_function<T, MemberType>(pm), name);
}
// Expose the given member (pm) of the T obj as a read-only attribute
template <class MemberType>
inline void def_readonly(MemberType T::*pm, const char* name)
{
this->add_setter_method(new read_only_setattr_function(name), name);
this->def_getter(pm, name);
}
// Expose the given member (pm) of the T obj as a read/write attribute
template <class MemberType>
inline void def_read_write(MemberType T::*pm, const char* name)
{
this->def_getter(pm, name);
this->def_setter(pm, name);
}
// define the standard coercion needed for operator overloading
void def_standard_coerce();
// declare the given class a base class of this one and register
// up and down conversion functions
template <class S, class V>
void declare_base(extension_class<S, V>* base)
{
// see extclass.cpp for an explanation of why we need to register
// conversion functions
base_class_info baseInfo(base,
&define_conversion<S, T>::downcast_ptr);
class_registry<T>::register_base_class(baseInfo);
add_base(ref(as_object(base), ref::increment_count));
derived_class_info derivedInfo(this,
&define_conversion<T, S>::upcast_ptr);
class_registry<S>::register_derived_class(derivedInfo);
}
// declare the given class a base class of this one and register
// only up conversion function
template <class S, class V>
void declare_base(extension_class<S, V>* base, without_downcast_t)
{
// see extclass.cpp for an explanation of why we need to register
// conversion functions
base_class_info baseInfo(base, 0);
class_registry<T>::register_base_class(baseInfo);
add_base(ref(as_object(base), ref::increment_count));
derived_class_info derivedInfo(this,
&define_conversion<T, S>::upcast_ptr);
class_registry<S>::register_derived_class(derivedInfo);
}
private: // types
typedef instance_value_holder<T,U> holder;
private: // extension_class_base virtual function implementations
std::vector<base_class_info> const& base_classes() const;
std::vector<derived_class_info> const& derived_classes() const;
void* extract_object_from_holder(instance_holder_base* v) const;
private: // Utility functions
template <long which, class Operand>
inline void def_operators(operators<which,Operand>)
{
def_standard_coerce();
// for some strange reason, this prevents MSVC from having an
// "unrecoverable block scoping error"!
typedef choose_op<(which & op_add)> choose_add;
choose_op<(which & op_add)>::template args<Operand>::add(this);
choose_op<(which & op_sub)>::template args<Operand>::add(this);
choose_op<(which & op_mul)>::template args<Operand>::add(this);
choose_op<(which & op_div)>::template args<Operand>::add(this);
choose_op<(which & op_mod)>::template args<Operand>::add(this);
choose_op<(which & op_divmod)>::template args<Operand>::add(this);
choose_op<(which & op_pow)>::template args<Operand>::add(this);
choose_op<(which & op_lshift)>::template args<Operand>::add(this);
choose_op<(which & op_rshift)>::template args<Operand>::add(this);
choose_op<(which & op_and)>::template args<Operand>::add(this);
choose_op<(which & op_xor)>::template args<Operand>::add(this);
choose_op<(which & op_or)>::template args<Operand>::add(this);
choose_unary_op<(which & op_neg)>::template args<Operand>::add(this);
choose_unary_op<(which & op_pos)>::template args<Operand>::add(this);
choose_unary_op<(which & op_abs)>::template args<Operand>::add(this);
choose_unary_op<(which & op_invert)>::template args<Operand>::add(this);
choose_unary_op<(which & op_int)>::template args<Operand>::add(this);
choose_unary_op<(which & op_long)>::template args<Operand>::add(this);
choose_unary_op<(which & op_float)>::template args<Operand>::add(this);
choose_op<(which & op_cmp)>::template args<Operand>::add(this);
choose_unary_op<(which & op_str)>::template args<Operand>::add(this);
}
template <long which, class Left, class Right>
inline void def_operators(operators<which,Left>, right_operand<Right>)
{
def_standard_coerce();
choose_op<(which & op_add)>::template args<Left,Right>::add(this);
choose_op<(which & op_sub)>::template args<Left,Right>::add(this);
choose_op<(which & op_mul)>::template args<Left,Right>::add(this);
choose_op<(which & op_div)>::template args<Left,Right>::add(this);
choose_op<(which & op_mod)>::template args<Left,Right>::add(this);
choose_op<(which & op_divmod)>::template args<Left,Right>::add(this);
choose_op<(which & op_pow)>::template args<Left,Right>::add(this);
choose_op<(which & op_lshift)>::template args<Left,Right>::add(this);
choose_op<(which & op_rshift)>::template args<Left,Right>::add(this);
choose_op<(which & op_and)>::template args<Left,Right>::add(this);
choose_op<(which & op_xor)>::template args<Left,Right>::add(this);
choose_op<(which & op_or)>::template args<Left,Right>::add(this);
choose_op<(which & op_cmp)>::template args<Left,Right>::add(this);
}
template <long which, class Left, class Right>
inline void def_operators(operators<which,Right>, left_operand<Left>)
{
def_standard_coerce();
choose_rop<(which & op_add)>::template args<Left,Right>::add(this);
choose_rop<(which & op_sub)>::template args<Left,Right>::add(this);
choose_rop<(which & op_mul)>::template args<Left,Right>::add(this);
choose_rop<(which & op_div)>::template args<Left,Right>::add(this);
choose_rop<(which & op_mod)>::template args<Left,Right>::add(this);
choose_rop<(which & op_divmod)>::template args<Left,Right>::add(this);
choose_rop<(which & op_pow)>::template args<Left,Right>::add(this);
choose_rop<(which & op_lshift)>::template args<Left,Right>::add(this);
choose_rop<(which & op_rshift)>::template args<Left,Right>::add(this);
choose_rop<(which & op_and)>::template args<Left,Right>::add(this);
choose_rop<(which & op_xor)>::template args<Left,Right>::add(this);
choose_rop<(which & op_or)>::template args<Left,Right>::add(this);
choose_rop<(which & op_cmp)>::template args<Left,Right>::add(this);
}
template <class signature>
void add_constructor(signature sig)
{
this->add_constructor_object(init_function<holder>::create(sig));
}
};
// A simple wrapper over a T which allows us to use extension_class<T> with a
// single template parameter only. See extension_class<T>, above.
template <class Held>
class held_instance : public Held
{
// There are no member functions: we want to avoid inadvertently overriding
// any virtual functions in Held.
public:"""
+ gen_functions("""%{
template <%(class A%n%:, %)>%}
held_instance(PyObject*%(, A%n% a%n%)) : Held(%(a%n%:, %)) {}""", args)
+ """
};
// Abstract base class for all obj holders. Base for template class
// instance_holder<>, below.
class instance_holder_base
{
public:
virtual ~instance_holder_base() {}
virtual bool held_by_value() = 0;
};
// Abstract base class which holds a Held, somehow. Provides a uniform way to
// get a pointer to the held object
template <class Held>
class instance_holder : public instance_holder_base
{
public:
virtual Held*target() = 0;
};
// Concrete class which holds a Held by way of a wrapper class Wrapper. If Held
// can be constructed with arguments (A1...An), Wrapper must have a
// corresponding constructor for arguments (PyObject*, A1...An). Wrapper is
// neccessary to implement virtual function callbacks (there must be a
// back-pointer to the actual Python object so that we can call any
// overrides). held_instance (above) is used as a default Wrapper class when
// there are no virtual functions.
template <class Held, class Wrapper>
class instance_value_holder : public instance_holder<Held>
{
public:
Held* target() { return &m_held; }
Wrapper* value_target() { return &m_held; }
"""
+ gen_functions("""%{
template <%(class A%n%:, %)>%}
instance_value_holder(extension_instance* p%(, A%n a%n%)) :
m_held(p%(, a%n%)) {}""", args)
+ """
public: // implementation of instance_holder_base required interface
bool held_by_value() { return true; }
private:
Wrapper m_held;
};
// Concrete class which holds a HeldType by way of a (possibly smart) pointer
// PtrType. By default, these are only generated for PtrType ==
// std::auto_ptr<HeldType> and PtrType == boost::shared_ptr<HeldType>.
template <class PtrType, class HeldType>
class instance_ptr_holder : public instance_holder<HeldType>
{
public:
HeldType* target() { return &*m_ptr; }
PtrType& ptr() { return m_ptr; }
instance_ptr_holder(PtrType ptr) : m_ptr(ptr) {}
public: // implementation of instance_holder_base required interface
bool held_by_value() { return false; }
private:
PtrType m_ptr;
};
class extension_instance : public instance
{
public:
extension_instance(PyTypeObject* class_);
~extension_instance();
void add_implementation(std::auto_ptr<instance_holder_base> holder);
typedef std::vector<instance_holder_base*> held_objects;
const held_objects& wrapped_objects() const
{ return m_wrapped_objects; }
private:
held_objects m_wrapped_objects;
};
//
// Template function implementations
//
template <class T, class U>
extension_class<T, U>::extension_class()
: extension_class_base(typeid(T).name())
{
class_registry<T>::register_class(this);
}
template <class T, class U>
extension_class<T, U>::extension_class(const char* name)
: extension_class_base(name)
{
class_registry<T>::register_class(this);
}
template <class T, class U>
void extension_class<T, U>::def_standard_coerce()
{
ref coerce_fct = dict().get_item(string("__coerce__"));
if(coerce_fct.get() == 0) // not yet defined
this->def(&standard_coerce, "__coerce__");
}
template <class T, class U>
inline
std::vector<base_class_info> const&
extension_class<T, U>::base_classes() const
{
return class_registry<T>::base_classes();
}
template <class T, class U>
inline
std::vector<derived_class_info> const&
extension_class<T, U>::derived_classes() const
{
return class_registry<T>::derived_classes();
}
template <class T, class U>
void* extension_class<T, U>::extract_object_from_holder(instance_holder_base* v) const
{
instance_holder<T>* held = dynamic_cast<instance_holder<T>*>(v);
if(held)
return held->target();
return 0;
}
template <class T, class U>
extension_class<T, U>::~extension_class()
{
class_registry<T>::unregister_class(this);
}
template <class T>
inline void class_registry<T>::register_class(extension_class_base* p)
{
// You're not expected to create more than one of these!
assert(static_class_object == 0);
static_class_object = p;
}
template <class T>
inline void class_registry<T>::unregister_class(extension_class_base* p)
{
// The user should be destroying the same object they created.
assert(static_class_object == p);
(void)p; // unused in shipping version
static_class_object = 0;
}
template <class T>
void class_registry<T>::register_base_class(base_class_info const& i)
{
static_base_class_info.push_back(i);
}
template <class T>
void class_registry<T>::register_derived_class(derived_class_info const& i)
{
static_derived_class_info.push_back(i);
}
template <class T>
std::vector<base_class_info> const& class_registry<T>::base_classes()
{
return static_base_class_info;
}
template <class T>
std::vector<derived_class_info> const& class_registry<T>::derived_classes()
{
return static_derived_class_info;
}
//
// Static data member declaration.
//
template <class T>
extension_class_base* class_registry<T>::static_class_object;
template <class T>
std::vector<base_class_info> class_registry<T>::static_base_class_info;
template <class T>
std::vector<derived_class_info> class_registry<T>::static_derived_class_info;
}}} // namespace boost::python::detail
#endif // EXTENSION_CLASS_DWA052000_H_
""")
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
args = 5
else:
args = int(sys.argv[1])
print gen_extclass(args)

1202
test/comprehensive.cpp Normal file

File diff suppressed because it is too large Load Diff

1194
test/comprehensive.py Normal file

File diff suppressed because it is too large Load Diff