如何使用 SWIG 将 std::vector<int> 公开为 Python 列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/276769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to expose std::vector<int> as a Python list using SWIG?
提问by Marcos Lara
I'm trying to expose this function to Python using SWIG:
我正在尝试使用 SWIG 将此函数公开给 Python:
std::vector<int> get_match_stats();
And I want SWIG to generate wrapping code for Python so I can see it as a list of integers.
我希望 SWIG 为 Python 生成包装代码,以便我可以将其视为整数列表。
Adding this to the .i file:
将此添加到 .i 文件中:
%include "typemaps.i" %include "std_vector.i" namespace std { %template(IntVector) vector<int>; }
I'm running SWIG Version 1.3.36
and calling swig with -Wall
and I get no warnings.
我正在跑步SWIG Version 1.3.36
并打电话给 swig-Wall
并且我没有收到任何警告。
I'm able to get access to a list but I get a bunch of warnings when compiling with -Wall
(with g++ (GCC) 4.2.4
) the generated C++ code that say:
我能够访问一个列表,但是在使用-Wall
(使用g++ (GCC) 4.2.4
)生成的 C++ 代码进行编译时,我收到了一堆警告:
warning: dereferencing type-punned pointer will break strict-aliasing rules
Am I exposing the function correctly? If so, what does the warning mean?
我是否正确公开了该功能?如果是这样,警告是什么意思?
These are the lines before the offending line in the same function:
这些是同一函数中违规行之前的行:
SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; std::vector *arg1 = (std::vector *) 0 ; std::vector::iterator arg2 ; std::vector::iterator result; void *argp1 = 0 ; int res1 = 0 ; swig::PySwigIterator *iter2 = 0 ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'"); } arg1 = reinterpret_cast * >(argp1);
And this is the offending line:
这是违规行:
res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0);
More code follows that.
更多的代码紧随其后。
The warning generated when compiling with g++ 4.2.4 is:
用g++ 4.2.4编译时产生的警告是:
swig_iss_wrap.cxx: In function ‘PyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)': swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules
采纳答案by Mr Fooz
%template(IntVector) vector<int>;
回答by Fergal
I don't have much experience with Swig, but are you #including your C++ header file in your .i file? Try one (or both) of
我对 Swig 没有太多经验,但是您是否在 .i 文件中#include C++ 头文件?尝试其中一种(或两种)
%include "myvector.h"
%{
# include "myvector.h"
%}