logo       

derived types: msg#00192

programming.swig

Subject: derived types

Hi,

I am trying to wrap a simple class hierarchy where a derived class contains a pointer to a derived type,
and then access the data as a derived type.

The C++ class hierarchy:
#ifndef test_class_h
#define test_class_h

#include <utility>

class Base {
public:
int foo;
Base(int foo_);
};

class Derived: public Base {
public:
int bar;
Derived(int foo_, int bar_);
};

class TestBase {
public:
Base *base;
TestBase(Base *base_);
};

class TestDerived2: public TestBase {
public:
TestDerived2(Derived *derived_);
};
#endif

A working C++ test program:

#include <stdio.h>
#include "test_class.h"
int main(void) {
Base b = Base(4);
Derived d = Derived(4, 5);
TestDerived2 t2 = TestDerived2(&d);
Derived *d3 = (Derived *)(t2.base);
printf("foo=%d\n", d3->foo);
printf("bar=%d\n", d3->bar);
}

I am trying to do the equivalent in the wrapped class; here is my swig wrapper:
%module test_class
%{
#include "test_class.h"
%}
%include "test_class.h"

(the Python module is built using -python -c++ -shadow with SWIG-1.3.21)

The python test program:
import test_class
b = test_class.Base(4)
d = test_class.Derived(4, 5)
t2 = test_class.TestDerived2(d)
derived = test_class.DerivedPtr(t2.base.this)
print dir(derived)
print derived.foo
print derived.bar

Unfortunately, attempting to access the bar attribute reports:
TypeError: Type error. Got _p_Base, expected _p_Derived

I've confirmed (yuck) that explictly changing the type of t2.base.this to a _p_Derived (by string replacement) works
fine. So I'm guessing that my attempt at casting isn't the right method. I'm also guessing the %pointer_cast and %pointer_class aren't
the right approach. Is this some other (swig-elegant) way of casting from a Base to Derived type?

Dave

_______________________________________________
Swig maillist - Swig@xxxxxxxxxxxxxxx
http://mailman.cs.uchicago.edu/mailman/listinfo/swig



<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise