0

For the following C++ API:

std::vector<float> get_sweep_points()
{
    return program->sweep_points;
}

Swig generates a wrapper which returns a tuple (), rather than a list []. Why? How can I force Swig to return a list to python.

Imran
  • 642
  • 6
  • 25
  • Possible duplicate of [How to expose std::vector as a Python list using SWIG?](https://stackoverflow.com/questions/276769/how-to-expose-stdvectorint-as-a-python-list-using-swig) – 9301293 Oct 24 '18 at 05:46
  • In my interface file, I already have %template(vectorf) vector; but it is still returning a tuple instead of list. – Imran Oct 24 '18 at 07:24

1 Answers1

3

If you use std_vector.i, you get typemaps as implemented by std_vector.i. If you don't like it, you have to write your own typemaps.

Here's a typemap to override the default behavior (no error checking) and return a list instead of a tuple:

%typemap(out) std::vector<int> (PyObject* obj) %{
    obj = PyList_New($1.size());
    for(auto i = 0; i < $1.size(); ++i)
        PyList_SET_ITEM(obj, i, PyLong_FromLong($1[i]));
    $result = SWIG_Python_AppendOutput($result, obj);
%}

Of course you can also just do v = list(get_sweep_points()) and now it is a list :^)

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251