How to expose std::vector<int> as a Python list using SWIG?

I'm trying to expose this function to Python using SWIG:

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.

Adding this to the .i file:

%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.

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:

  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:

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


Asked by: Aldus334 | Posted: 24-09-2021






Answer 1

%template(IntVector) vector<int>;

Answered by: Wilson257 | Posted: 25-10-2021



Answer 2

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

%include "myvector.h"


%{
#   include "myvector.h"
%}

Answered by: Lenny276 | Posted: 25-10-2021



Similar questions

How to handle C++ return type std::vector<int> in Python ctypes?

I cannot find how ctypes will bridge the gap between std::vector and Python; no where on the internet is the combination mentioned. Is this bad practice, does it not exist or am I missing something? C++ : xxx.cpp #include &lt;fstream&gt; #include &lt;string&gt; using namespace std; extern "C" std::vector&lt;int&gt; foo(const char* FILE_NAME) { string line; std:...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top