[C++-sig] Extracting C++ objects of different types from a Python list

Craig Finch oanjao at yahoo.com
Wed Aug 8 17:41:26 CEST 2007


Chris,
Your suggestion worked for me.  I constructed a simple but complete
example of how to handle objects of different types when bringing a
Boost.python list into C++ for processing.  An explanation and the
necessary files are posted on my software development blog at

http://www.shocksolution.com/blog/2007/08/08/mixing-objects-of-different-types-in-a-boostpython-list/

for anyone else who wants to know how to do this.  Thanks guys!

   Craig

--- Christopher Woods <chryswoods at gmail.com> wrote:

>   Hi Craig,
> 
> I've played with your example and I've got it to work by changing
> your
> extract<BaseClass> and extract<BaseClass&> into extract<BaseClass*>
> and extract<const BaseClass*>. In the first case (extract<BaseClass>)
> you were extracting the object in the list into a *copy*, which was
> of
> type BaseClass, so the "Useless base class" function of that copy was
> then called. By extracting into a pointer (via extract<BaseClass*>)
> you aren't performing a copy, and you obtain a polymorphic pointer to
> the original object.
> 
> As for the typeid part of the example, I don't know why typeid gets
> it
> wrong when you use extract<BaseClass&>. I had to change this to
> extract<const BaseClass*> and then do a typeid of the dereference of
> the resulting polymorphic pointer.
> 
> Here is the modified version of 'setList' that worked on my box
> (linux, gcc 3.4, python 2.3);
> 
> ==============================
> void Importer::setList (list l) {
>    BaseClass *o;
>    int len = extract<int>(l.attr("__len__")());
> 
>    for (int i=0; i<len; i++) {
>        std::cout << typeid( *(extract <const BaseClass*> (l[i]))
> ).name() << std::endl;
> 
>        o = extract <BaseClass*> (l[i]);
>        o->evaluate();
>    }
> }
> ==============================
> 
> This gave output;
> 
> ==============================
> 1A
> Index is 3
> 1B
> Value is 5.234
> ==============================
> 
>   I hope this helps,
> 
>   Christopher
> 


--------------
Please reply to cfinch at ieee.org


       
____________________________________________________________________________________
Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. 
http://answers.yahoo.com/dir/?link=list&sid=396545433



More information about the Cplusplus-sig mailing list