How to access c++ object methods from inside vector with SWIG Python
Question: I have two C++ classes: Foo and Bar. The constructor for Foo looks like this:

    
    
    Foo(std::vector<Bar *> * bars);
    

The constructor for Bar and one of its member functions are the following:

    
    
    Bar(int data)
    int getData()
    

In my interface file I have:

    
    
    %module mySwig
    %{
    #include "Foo.h"
    #include "Bar.h"
    #include <vector>
    %}
    
    %include "Foo.h"
    %include "Bar.h"
    %include "std_vector.i"
    namespace std {
        %template(VectorOfBars) vector<Bar *>;
    }
    

So then in python I do the following:

    
    
    import mySwig
    myBar = mySwig.Bar(5)
    

And now I need to create a `std::vector<Bar *> *` object to pass into the Foo
constructor, so I try the following:

    
    
    vector = mySwig.VectorOfBars()
    vector.push_back(myBar)
    

To test if this was successful I try:

    
    
    print vector
    print vector[0]
    print "data: vector[0].getData()
    

If the result of the third print out is still "5" then it was successful, but
instead I get what I'm assuming is a pointer value instead

    
    
    <mySwig.VectorOfBars; proxy of <Swig Object of type 'std::vector< Bar *,std::allocator< Bar * > > *' at 0xb6a9c4d0> >
    <mySwig.Bar; proxy of <Swig Object of type 'std::vector< Bar * >::value_type' at 0xb6a9c3b0> >
    3069958048
    

What am I doing wrong? How can I create the vector of Bar pointer objects that
I need to pass in to make a Foo object? Why am I getting a pointer value back
instead of the actual value?


Answer: I figured it out! The problem was that the type `<mySwig.Bar; proxy of <Swig
Object of type 'std::vector< Bar * >::value_type' at 0xb6a9c3b0> >` translates
to a `Bar *` and not a `Bar` object. Normally SWIG handles pointers for you
but in this case it didn't so when I called a method on the `Bar *` object it
gave me back bogus data.

In reality this is exactly what I needed to pass to the Foo constructor. I was
just mistaken in thinking that SWIG would automatically dereference the
pointer to Bar so that I could access its `data` attribute. When I changed the
template declaration from

    
    
    %template(VectorOfBars) vector<Bar *>;
    

to the line

    
    
    %template(VectorOfBars) vector<Bar>;
    

then I was able to access `data` but then it was incorrect for passing to
Foo's constructor. I had it right all along.

