Hi,
I am trying to return a new Python buffer that is a view to internals of
my Message object. My understanding is that in such case, I should use
return_internal_reference<> to make the return value hold reference to
the Message class because of this bit of PyBuffer_FromMemory() docs:
"The caller is responsible for ensuring that the memory buffer, passed
in as ptr, is not deallocated while the returned buffer object exists."

The problem is that whatever approach I could think of results into
uncompilable code. (See the attached file.) I am using Boost 1.37.0.

Is there any other way that I can do this?

--
VH
#define BOOST_PYTHON_STATIC_MODULE
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>

namespace py = boost::python;


struct Message
{
    char const * data () const { return buf; }
    size_t size () const { return 10; }
    char buf[10];
};


// error C2027: use of undefined type
// 
'boost::python::detail::reference_existing_object_requires_a_pointer_or_reference_return_type<R>
py::object
get_buffer_impl_1 (boost::shared_ptr<Message> const & msg)
{
    py::handle<> h (
        ::PyBuffer_FromMemory (
            const_cast<char *>(msg->data ()),
            msg->size ()));
    py::object o (h);
    return o;
}


// pointer_holder.hpp(176) : error C2535:
// 
'boost::python::objects::pointer_holder<Pointer,Value>::pointer_holder(Pointer)'
 :
// member function already defined or declared
::PyObject *
get_buffer_impl_2 (boost::shared_ptr<Message> const & msg)
{
    return ::PyBuffer_FromMemory (
        const_cast<char *>(msg->data ()),
        msg->size ());
}


void
dec_ref (::PyObject * o)
{
    Py_XDECREF (o);
}


// Same error as the 1st attempt:
// error C2027: use of undefined type
// 
'boost::python::detail::reference_existing_object_requires_a_pointer_or_reference_return_type<R>'
boost::shared_ptr< ::PyObject>
get_buffer_impl_3 (boost::shared_ptr<Message> const & msg)
{
    return boost::shared_ptr< ::PyObject> (
        ::PyBuffer_FromMemory (
            const_cast<char *>(msg->data ()),
            msg->size ()),
        dec_ref);
}


BOOST_PYTHON_MODULE(M)
{
    py::class_<Message, boost::noncopyable>
        ("Message", py::no_init)
        .def ("get_buffer_1", &get_buffer_impl_1,
            py::return_internal_reference<1> ())
        .def ("get_buffer_2", &get_buffer_impl_2,
            py::return_internal_reference<1> ())
        .def ("get_buffer_3", &get_buffer_impl_3,
            py::return_internal_reference<1> ())
        ;
}

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to