[C++-sig] Typecasting

David Sveningsson ext at sidvind.com
Thu Dec 14 13:45:51 CET 2006

Hi, I'm back again with another question. I am exposing some C++ classes
to python using boost.

A have a class that is exposed to python. The class has a virtual
function that takes a pointer to a baseclass. This baseclass has a
function that returns the type of the class. By looking at the type one
can typecast into the corresponding class.

Now, I want to expose this behavior to python. I have a wrapper class to
expose the first class. It uses the get_override function to call the
function in python. So far it works. I can instantiate the class in
python and the method is called.

The problem is what to do next. I can look at the type function and
determine what type of class it is but whatever is passed into the
function is always a baseclass in python. I need to convert the class
into the right class.

All classes are exposed to python.

Some code:

Python wrapper object:

class PyObj: public Object, public wrapper<Object> {
        PyObj(const Object&){
        void notify(Event* evt){

Event class:

class Event: public Object {
        Event(Event_t type){ _type = type; }
        Event_t                type(){ return _type; }
        Event_t             _type;

Derived event:

class EventKeyboard: public Event {
        EventKeyboard() : Event( EVT_KEYBOARD ){}
        int     keycode(){ return _keycode; }
        int     _keycode;

Python code (only relevant part)

class Foo (Core.Object):
    def notify(self,a):
        if a.type() == Core.Event_t.EVT_KEYBOARD:
            print a.keycode()

            # Does not work, method not defined

            a.__class__ = Core.EventKeyboard
            print a.keycode()

            # This gives this error:
            # Boost.Python.ArgumentError: Python argument types in
            #     EventKeyboard.keycode(EventKeyboard)
            # did not match C++ signature:
            #     keycode(EventKeyboard {lvalue})


//*David Sveningsson [eXt]*

Freelance coder | Game Development Student

Thou shalt make thy program's purpose and structure clear to thy fellow man by using the One True Brace Style, even if thou likest it not, for thy creativity is better used in solving problems than in creating beautiful new impediments to understanding.

More information about the Cplusplus-sig mailing list