2
0
mirror of https://github.com/boostorg/python.git synced 2026-01-19 16:32:16 +00:00

char conversions

Handle dangling references


[SVN r13164]
This commit is contained in:
Dave Abrahams
2002-03-10 06:41:04 +00:00
parent be6016a972
commit c170b1b83e
2 changed files with 78 additions and 0 deletions

View File

@@ -8,6 +8,8 @@
#include <boost/python/class.hpp>
#include <boost/ref.hpp>
#include <boost/python/ptr.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/reference_existing_object.hpp>
using namespace boost::python;
@@ -48,6 +50,16 @@ void apply_void_X_ref(PyObject* f, X& x)
returning<void>::call(f, boost::ref(x));
}
X& apply_X_ref_pyobject(PyObject* f, PyObject* obj)
{
return returning<X&>::call(f, obj);
}
X* apply_X_ptr_pyobject(PyObject* f, PyObject* obj)
{
return returning<X*>::call(f, obj);
}
void apply_void_X_cref(PyObject* f, X const& x)
{
returning<void>::call(f, boost::cref(x));
@@ -63,6 +75,21 @@ void apply_void_X_deep_ptr(PyObject* f, X* x)
returning<void>::call(f, x);
}
char const* apply_cstring_cstring(PyObject* f, char const* s)
{
return returning <char const*>::call(f, s);
}
char const* apply_cstring_pyobject(PyObject* f, PyObject* s)
{
return returning <char const*>::call(f, s);
}
char apply_char_char(PyObject* f, char c)
{
return returning <char>::call(f, c);
}
int X::counter;
BOOST_PYTHON_MODULE_INIT(callbacks_ext)
@@ -75,6 +102,17 @@ BOOST_PYTHON_MODULE_INIT(callbacks_ext)
.def("apply_void_X_cref", apply_void_X_cref)
.def("apply_void_X_ptr", apply_void_X_ptr)
.def("apply_void_X_deep_ptr", apply_void_X_deep_ptr)
.def("apply_X_ptr_pyobject", apply_X_ptr_pyobject
, return_value_policy<reference_existing_object>())
.def("apply_X_ref_pyobject", apply_X_ref_pyobject
, return_value_policy<reference_existing_object>())
.def("apply_cstring_cstring", apply_cstring_cstring)
.def("apply_cstring_pyobject", apply_cstring_pyobject)
.def("apply_char_char", apply_char_char)
.add(
class_<X>("X")
.def_init(args<int>())

View File

@@ -66,6 +66,46 @@
44
>>> last_x.value()
43
>>> y = apply_X_ref_pyobject(identity, x)
>>> assert y.value() == x.value()
>>> increment(x)
>>> assert y.value() == x.value()
>>> y = apply_X_ptr_pyobject(identity, x)
>>> assert y.value() == x.value()
>>> increment(x)
>>> assert y.value() == x.value()
>>> y = apply_X_ptr_pyobject(identity, None)
>>> y
>>> def new_x(ignored):
... return X(666)
...
>>> try: apply_X_ref_pyobject(new_x, 1)
... except ReferenceError: pass
... else: print 'no error'
>>> try: apply_X_ptr_pyobject(new_x, 1)
... except ReferenceError: pass
... else: print 'no error'
>>> try: apply_cstring_cstring(identity, 'hello')
... except ReferenceError: pass
... else: print 'no error'
>>> apply_char_char(identity, 'x')
'x'
>>> apply_cstring_pyobject(identity, 'hello')
'hello'
>>> apply_cstring_pyobject(identity, None)
>>> apply_char_char(identity, 'x')
'x'
'''
def run(args = None):