I'm working on an accelerator module for Python written in C++. It's an implementation of Dijkstra's algorithm and eventually returns a pointer to a Route object which in turn contains a std::list<struct waypoint>. To interface with this object using Python I wrote the following interface file:
%{
#include "universe.hpp"
%}
%include <std_list.i>
%include "universe.hpp"
%template(Waypoints) std::list<struct waypoint>;
This allowed me to access the list object and index it, but the iterator over it was not working properly:
>>> r
<mod.Route; proxy of <Swig Object of type 'Route *' at 0x7f6ab39ff4e0> >
>>> r.points
<mod.Waypoints; proxy of <Swig Object of type 'std::list< waypoint > *' at 0x7f6ab502d630> >
>>> r.points[0]
<mod.waypoint; proxy of <Swig Object of type 'waypoint *' at 0x7f6ab39ff540> >
>>> for x in r.points:
... print(x)
...
<Swig Object of type 'unknown' at 0x7f6ab39ff5d0>
swig/python detected a memory leak of type 'unknown', no destructor found.
<Swig Object of type 'unknown' at 0x7f6ab39ff5a0>
swig/python detected a memory leak of type 'unknown', no destructor found.
<Swig Object of type 'unknown' at 0x7f6ab39ff5d0>
swig/python detected a memory leak of type 'unknown', no destructor found.
...
In an attempt to remedy this (and to make the code bit nicer to read) I wanted to convert the std::list<struct waypoint> into a normal Python list so I wrote the following typemap:
%{
#include "universe.hpp"
%}
%typemap(out) std::list<struct waypoint> {
$result = PyList_New($1->size());
printf("This never gets printed\n");
for(size_t i = 0; i < $1->size(); ++i) {
PyList_SET_ITEM($result, i, $1[i]);
}
}
%include <std_list.i>
%include "universe.hpp"
This typemap doesn't work, however. In fact, the list is now just a SwigPyObject and does not support subscription at all. The typemap is also never executed since the print statement inside it is never executed. I'm having a hard time finding people with the same problem on the web and I hope someone here can help me figure out what I'm doing wrong.
These are the minimal contents of universe.hpp:
#include <string>
#include <list>
struct Entity;
struct waypoint {
Entity *entity;
int type;
};
class Route {
public:
int loops;
double cost;
std::list<struct waypoint> points;
};
class Entity {
public:
float x, y, z;
int id, seq_id;
std::string name;
};