问题
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.
回答1:
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 :^)
来源:https://stackoverflow.com/questions/52960876/tuple-is-returned-by-python-wrapper-generated-by-swig-for-a-c-vector