[C++-sig] Abstract class instances to-python conversion

Jim Bosch talljimbo at gmail.com
Sat Jul 30 23:47:45 CEST 2011


On 07/30/2011 01:15 PM, Valentin Perrelle wrote:
> Hi,
>
> I'm currently embedding and extending Python using Boost.Python. I'm
> trying to expose some c++ library (OIS) classes to my Python scripts.
> This library mainly exposes abstract classes since the actual
> implementation are derived classes specialized for each operating system.
>
> So, i have to wrap those abstract classes. Then, eventually i will
> convert some existing C++ object of this class to its Python equivalent.
> Ideally, I would think that the HeldType is a pointer to the existing
> C++ object. There is no pointer managment problem since the lifetime of
> the object is greater than the execution time of the script.
>

In this case, I don't you need to specify a HeldType, because that only 
affects what happens when you construct the object in Python, and you 
aren't every doing that.  But you do need to specify "noncopyable" if 
the class doesn't have a copy constructor...

> There is probably something i don't understand in the design of
> Boost.Python. At this point, my problem is that i need a to_python
> conversion which requires the abscence of noncopyable attribute which
> then implies to be able to build an instance of the object (which i
> cannot provide since the class is abstract, and i don't have any
> concrete derived class). I don't yet understand why holding a pointer in
> the Python object requires the ability to build instances of the wrapped
> class. The exact compile-time error i get is:
>
> boost_1_44/boost/python/object/pointer_holder.hpp:194:14: error: cannot
> allocate an object of abstract type 'OIS::Keyboard'
>

Why do you think you can't have noncopyable?  You can certainly support 
some to-python conversions (including the one you've invoked below with 
"ptr(keyboard)") on a noncopyable class.  Are you hoping to support some 
specific one, or is this the root of your misunderstanding?

Anyhow, I'd recommend trying

class_<Keyboard, noncopyable>("Keyboard", no_init);

with the rest of what you have.

Good luck!

Jim Bosch




>
> BOOST_PYTHON_MODULE(OIS)
> {
> class_<Keyboard, Keyboard*>("Keyboard", no_init);
> }
>
> Python init:
>
> try {
> PyImport_AppendInittab("OIS", PyInit_OIS);
> Py_InitializeEx(0);
>
> object main(import("__main__"));
> dict globals(main.attr("__dict__"));
> globals["keyboard"] = ptr(keyboard);
> }
> catch (error_already_set&) {
> PyErr_Print();
> }


More information about the Cplusplus-sig mailing list