[C++-sig] converting a PyObject into its C-Type
Jim Bosch
talljimbo at gmail.com
Fri Aug 27 19:16:22 CEST 2010
On 08/27/2010 01:35 AM, Erik Tuerke wrote:
> Hi!
>
> I am trying to convert a PyObject into its C-Type. The thing is, i have
> a function which takes a PyObject but i need to convert the PyObject
> into its respective C-Type.
>
> For example i have a python class:
>
> class_<isis::util::fvector4, _Vector4<float> >("py_fvector4",
> init<float, float, float, float>())
> .def( init<>())
> .def("__setitem__", &_Vector4<float>::setItem)
> .def("__getitem__", &_Vector4<float>::getItem)
> ;
>
> How can i convert the PyObject "py_fvector4" back into its C-Type
> _Vector4 (or isis::util::fvector4) ?
>
> Thanks for your help and best regards!
>
Construct a boost::python::object from your PyObject*, and use extract():
namespace bp = boost::python;
void func(PyObject * arg);
bp::object p(bp::handle<>(bp::borrowed(arg)));
_Vector4<float> & v = bp::extract< _Vector4<float> >(arg);
}
This should also raise a TypeError if arg doesn't contain the
appropriate C++ type.
By the way, Boost.Python can also wrap functions taking bp::object
arguments, and that might be cleaner than a raw PyObject *.
HTH!
Jim Bosch
More information about the Cplusplus-sig
mailing list