[C++-sig] Boost.Python: How to fill a passed in buffer in Python

Ehsan Pi ehsanpii at gmail.com
Tue May 1 21:53:19 CEST 2012


Hello forum,

I have a buffer in C++ that I need to fill in Python. The Address of the
buffer is obtained through the GetAddress method which returns a void
pointer to the buffer address.

    #include <boost/smart_ptr/shared_ptr.hpp>
    class Foo
    {
    public:
        Foo(const unsigned int length)
        {
            m_buffer = boost::shared_ptr< unsigned char >( new unsigned
char[ length ] );
        }

        ~Foo(){}

        void* GetAddress( ) const
        {
            // cast for the sake of this question
            return reinterpret_cast< void* >( m_buffer.get() );
        }

    private:
        boost::shared_ptr< unsigned char > m_buffer;
        Foo();
        Foo(const Foo&);
    };

--------------------
Using Py++ I can generate the Boost.Python wrapper to export the class to
Python as follows:

    #include "boost/python.hpp"
    #include "foo.hpp"

    namespace bp = boost::python;

    BOOST_PYTHON_MODULE(MyWrapper){
        { //::Foo
            typedef bp::class_< Foo, boost::noncopyable > Foo_exposer_t;
            Foo_exposer_t Foo_exposer = Foo_exposer_t( "Foo", bp::init<
unsigned int >(( bp::arg("length") )) );
            bp::scope Foo_scope( Foo_exposer );
            bp::implicitly_convertible< unsigned int const, Foo >();
            { //::Foo::GetAddress

                typedef void * ( ::Foo::*GetAddress_function_type )(  )
const;

                Foo_exposer.def(
                    "GetAddress"
                    , GetAddress_function_type( &::Foo::GetAddress )
                    , bp::return_value_policy< bp::return_opaque_pointer
>() );

            }
        }
    }

--------------------
In Python, the output of the GetAddress is a void * to the memory address:

    >>> import MyWrapper
    >>> foo = MyWrapper.Foo(100)
    >>> address = foo.GetAddress()
    >>> print address
    <void * object at 0x01E200B0>
    >>>

My question is can I fill the buffer in Python, and if so how?

Thanks a lot,
Ehsan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20120501/612922ef/attachment.html>


More information about the Cplusplus-sig mailing list