Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

#38 dynamic_cast functionality

open
nobody
None
5
2012-12-21
2006-06-23
James Bigler
No

I was informed from the mailing list that I should
submit a feature request
(http://sourceforge.net/mailarchive/message.php?msg_id=16824592).

Here's what I need.

I have a class:

class Light {
public:
virtual void stuff() {}
};

And a child class:

class BetterLight: public Light {
public:
virtual void stuff() {}
virtual void morestuff() {}
};

I then have a container class:

class LightSet {
public:
void add(Point* p) {
lights.push_back(p);
}
Light* getLight(int which) {
return lights[which];
}
private:
vector<Light*> lights;
};

================================
Now in my python code I have this:

from lights import *
light = BetterLight()
set = LightSet()
set.add(light)
light_out = set.getLight(0)
print(light_out)
<Light; proxy of C++ Light instance at 0x80d1c40>

================================
I want to be able to make light_out into a BetterLight"
if it was one.

OK, so in order to do this I had to extend the Light
class with this:

%{
#include <Light.h>
#include <BetterLight.h>
%}

%include <Light.h>
%include <BetterLight.h>

%extend Light {
Manta::BetterLight* asBetterLight() {
return dynamic_cast<BetterLight*>(self);
}
};

I had to make sure I grouped the parent and child class
in the same inclusion block, because the extend
function would place any code right after the block
where the parent was included.

It seems as though this sort of thing could be handled
automatically. I believe class heritage is maintained
by swig. Whenever a child class is seen and any of the
descendants are wrapped, the descendants could be
extended to support the cast operation.

Alternatively you could place static functions in the
child:

%extend BetterLight {
static BetterLight* fromLight(Light* parent) {
return dynamic_cast<BetterLight*>(parent);
}
};

Perhaps this could be added as an optional feature to SWIG.

Thanks,
James

Discussion