SwigPyIterator value is always base class
<p>I have classes A, B, C in C++. B and C are derived from A. And I have function in c++ returns vector of B and C: like <code>std::vector&lt;A*&gt; getAllObjects()</code>. I use swig to generate Python wrapper. Then I call getAllObjects() in Python as below:</p>

<pre><code>objects = getAllObjects()
for obj in objects:
    if isinstance(obj, B):
        print("OK")
    elif isinstance(obj, C):
        print("OK")
</code></pre>

<p>The object I get from iterator is instance A, but it should be B or C. How to resolve the problem?</p>

<p>You need <em>something</em> more to go on than just a type hierarchy. Typically in a Python/SWIG scenario one of the following is sufficient:</p>

<ol>
<li>a <code>virtual</code> function in the base class (i.e. RTTI)</li>
<li>some member variable or function that somehow identifies the most derived type of a given instance (e.g. a common pattern in C is to include the first field of a struct being some kind of type identifier).</li>
<li>some kind of hook at object creation time, for example if you know that all instances will be Python created/owned</li>
</ol>

<p>I'm working to the assumption that the first type is sufficient, but even for other cases it's not hard to adapt. </p>

<p>To illustrate this I wrote the following header file:</p>

<pre class="lang-cpp prettyprint-override"><code>class A {
public:
  virtual ~A() {}
};

class B : public A {
};

class C: public A {
};
</code></pre>

<p>Given this header file, in pure C++ we can do the following, making use of RTTI:</p>

<pre class="lang-cpp prettyprint-override"><code>#include "test.hh"
#include &lt;typeinfo&gt;
#include &lt;iostream&gt;

int main() {
  const auto&amp; t1 = typeid(A);
  const auto&amp; t2 = typeid(B);
  const auto&amp; t3 = typeid(C);
  A *a = new A;
  A *b = new B;
  A *c = new C;
  const auto&amp; at = typeid(*a);
  const auto&amp; bt = typeid(*b);
  const auto&amp; ct = typeid(*c);

  std::cout &lt;&lt; t1.name() &lt;&lt; "\n";
  std::cout &lt;&lt; t2.name() &lt;&lt; "\n";
  std::cout &lt;&lt; t3.name() &lt;&lt; "\n";
  std::cout &lt;&lt; at.name() &lt;&lt; "\n";
  std::cout &lt;&lt; bt.name() &lt;&lt; "\n";
  std::cout &lt;&lt; ct.name() &lt;&lt; "\n";
}
</code></pre>

<p>This illustrates that the problem we're trying to solve (what type is it really?) is in fact solvable using standard C++.</p>

<p>It's worth noting at this point that the problem is made slightly more complicated by the use of the <code>std::vector</code> iteration instead of just a function that returns a single <code>A*</code>. If we were just working with the return value of a function we'd write a <code>typemap(out)</code>. In the case of the <code>std::vector&lt;A*&gt;</code> however it is possible to customise the behaviour of the iteration returning and insert extra code to make sure Python is aware of the derived type and not just the base. SWIG has a type traits mechanism that most of the standard containers use to help them with common uses (e.g. iteration) without excessive duplication. (For reference this is in std_common.i I think).</p>

<p>So the basic plan is to hook into the output of the iteration process (<code>SwigPyIterator</code>, implemented as <code>SwigPyIteratorClosed_T</code> in this case), using the traits types that SWIG introduces for customising this. Inside that hook, instead of blindly using the SWIG type info for <code>A*</code> we'll use <code>typeid</code> to lookup the type dynamically in a <code>std::map</code>. This map is maintained internally to the module. If we find anything in that map we'll use it to return a more derived Python object, as a Python programmer would expect. Finally we need to register the types in the map at initialisation time. </p>

<p>So my interface ended up looking like this:</p>

<pre class="lang-cpp prettyprint-override"><code>%module test

%{
#include "test.hh"
#include &lt;vector&gt;
#include &lt;map&gt;
#include &lt;string&gt;
#include &lt;typeindex&gt; // C++11! - see: http://stackoverflow.com/a/9859605/168175
%}

%include &lt;std_vector.i&gt;

%{
namespace {
  // Internal only, store the type mappings
  std::map&lt;std::type_index, swig_type_info*&gt; aheirarchy;
}

namespace swig {
  // Forward declare traits, the fragments they're from won't be there yet
  template &lt;class Type&gt; struct traits_from_ptr;
  template &lt;class Type&gt;
  inline swig_type_info *type_info();

  template &lt;&gt; struct traits_from_ptr&lt;A&gt; {
    static PyObject *from(A *val, int owner = 0) {
      auto ty = aheirarchy[typeid(*val)];
      if (!ty) {
        // if there's nothing in the map, do what SWIG would have done
        ty = type_info&lt;A&gt;();
      }
      return SWIG_NewPointerObj(val, ty, owner);
    }
  };
}
%}

%template(AList) std::vector&lt;A*&gt;;

%inline %{
const std::vector&lt;A*&gt;&amp; getAllObjects() {
  // Demo only
  static auto ret = std::vector&lt;A*&gt;{new A, new B, new C, new C, new B};
  return ret;
}
%}

%include "test.hh"
%init %{
  // Register B and C here
  aheirarchy[typeid(B)] = SWIG_TypeQuery("B*");
  aheirarchy[typeid(C)] = SWIG_TypeQuery("C*");
%}
</code></pre>

<p>With the <code>%inline</code> function I wrote just to illustrate things that's enough to get things started. It allowed me to run the following test Python to demonstrate my solution:</p>

<pre><code>from test import getAllObjects, A, B, C

objects = getAllObjects()
for obj in objects:
    print obj
    if isinstance(obj, B):
        print("OK")
    elif isinstance(obj, C):
        print("OK")
</code></pre>

<pre class="lang-none prettyprint-override"><code>swig3.0 -c++ -python -Wall test.i
g++ -std=c++11 -Wall test_wrap.cxx -o  _test.so -shared -I/usr/include/python2.7/ -fPIC
python run.py 
&lt;test.A; proxy of &lt;Swig Object of type 'A *' at 0xf7442950&gt; &gt;
&lt;test.B; proxy of &lt;Swig Object of type 'B *' at 0xf7442980&gt; &gt;
OK
&lt;test.C; proxy of &lt;Swig Object of type 'C *' at 0xf7442fb0&gt; &gt;
OK
&lt;test.C; proxy of &lt;Swig Object of type 'C *' at 0xf7442fc8&gt; &gt;
OK
&lt;test.B; proxy of &lt;Swig Object of type 'B *' at 0xf7442f98&gt; &gt;
OK
</code></pre>

<p>Which you'll notice matched the types created in my dummy implementation of <code>getAllObjects</code>.</p>

<p>You could do a few things more neatly:</p>

<ol>
<li>Add a macro for registering the types. (Or do it automatically some other way)</li>
<li>Add typemaps for regular returning of objects if needed.</li>
</ol>

<p>And as I indicated earlier this isn't the only way to solve this problem, just the most generic.</p>

python c++ swig