Boost.Python: How to fill a passed in buffer in Python
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
On Tue, May 1, 2012 at 10:53 PM, Ehsan Pi <ehsanpii@gmail.com> wrote:
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?
Easily: using ctypes module. As in previous cases, search py++ documentation for ctypes, as it produces some integration code. HTH, Roman
participants (2)
-
Ehsan Pi -
Roman Yakovenko