我想知道是否可以在 Python 中填充缓冲区(具有以下条件),如果可以,如何?
我有一个 C++ 缓冲区,我需要填写 Python。缓冲区的地址是通过GetAddress
返回指向缓冲区地址的void 指针的方法获得的。
#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&);
};
使用 Py++,我可以生成 Boost.Python 包装器以将类导出到 Python,如下所示:
#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 >() );
}
}
}
在 Python 中,GetAddress 的输出是指向内存地址的 void *:
>>> import MyWrapper
>>> foo = MyWrapper.Foo(100)
>>> address = foo.GetAddress()
>>> print address
<void * object at 0x01E200B0>
>>>
问题是 Python 不允许我对 void * 地址对象做任何事情。如果我尝试访问缓冲区中的第二个元素,则以下操作均无效:
>>> address + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'void *' and 'int'
>>> address[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'void *' object is unsubscriptable
>>>
环境:Visual Studio 2008、Boost 1.44、gcc-xml 0.9.0、py++ 1.0.0、pygccxml 1.1.0、Python 2.6.6