如何使用SWIG将std::vector<int>暴露为Python列表?

18

我正在尝试使用SWIG将此函数暴露给Python:

std::vector<int> get_match_stats();

我希望SWIG为Python生成包装代码,以便我可以将其视为整数列表。
将以下内容添加到.i文件中:
``` %include "typemaps.i" %include "std_vector.i"
namespace std { %template(IntVector) vector; } ```
我正在运行SWIG Version 1.3.36,并使用-Wall调用swig,没有警告。
我能够访问列表,但是在使用-g++(GCC)4.2.4编译生成的C ++代码时,我会收到一堆警告,这些警告说:
``` warning: dereferencing type-punned pointer will break strict-aliasing rules ```
是否正确公开了函数?如果是,请问警告是什么意思?
在同一功能中的有问题的行之前,是以下行:
``` 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); ```
有问题的行是:
``` res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0); ```
更多的代码在那之后。
在使用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 ```

较新版本的swig仍会生成导致警告的代码,例如此类。使用-fno-strict-aliasing可以使g++接受swig包装器而不出现问题。 - J Quinn
2个回答

14
%template(IntVector) vector<int>;

这就是我尝试的,但在使用g++编译时会收到一堆警告。有什么想法吗? - Marcos Lara
1
你使用的g++版本是什么?我正在使用4.1.2,即使使用-Wall也没有任何警告。我也不记得在使用3.3左右时有任何警告。请注意,此帖子中多了一个“<int>”,而原帖中没有。 - Mr Fooz
我正在使用 g++ 4.2.4 并尝试使用“-Wall -Werror -ansi -pedantic”进行构建。我刚刚尝试了只使用 -Wall 进行构建,但仍然收到警告。 - Marcos Lara
这可能是新的4.2版本问题。在gcc 4.2下面有一些重大的变化。你能否发布产生此警告的生成代码行? - Mr Fooz
1
一些旧版本的SWIG生成的代码比较松散。GCC 4.2不太喜欢其中的很多内容。 - Seth Johnson
显示剩余2条评论

0

我对Swig没有太多经验,但是你在.i文件中是否包含了C++头文件?可以尝试其中一个或两个:

%include "myvector.h"


%{
#   include "myvector.h"
%}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接