tuple is returned by python wrapper generated by swig for a C++ vector

眉间皱痕 提交于 2021-02-11 12:56:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!