SWIG argument error when using “using std::vector”

2019-07-13 05:29发布

问题:

This is very related to this question

Regardless of whether or not this is coding practice, I have come across code that looks like this

test.hh

#include <vector>                                                                                   
using std::vector;                                                             

class Test 
{                                                                     
    public:                                                                      
        vector<double> data;                                                     
};  

I am trying to swig this using swig3.0 using the following interface file

test.i

%module test_swig                                                                

%include "std_vector.i"                                                          

namespace std {                                                                  
    %template(VectorDouble) vector<double>;                                      
};                                                                               

%{                                                                               
    #include "test.hh"                                                               
%}                                                                               

%naturalvar Test::data;                                                                                 
%include "test.hh"    

And the following test code

test.py

t = test.Test()                                                              
jprint(t)                                                                    
a      = [1, 2, 3]                                                                
t.data = a # fails   

doing so gives me the following error

in method 'Test_data_set', argument 2 of type 'vector< double >'

This can be fixed by either changing the using std::vector in test.hh to using namespace std or by removing using std::vector and changing vector<double> to std::vector<double>. This is not what I want.

The problem is that I was given this code as is. I am not allowed to make changes, but I am supposed to still make everything available in python via SWIG. What's going on here?

Thanks in advance.

回答1:

To me, this looks like SWIG does not support the using std::vector; statement correctly. I think it's a SWIG bug. I can think of the following workarounds:

  • Add using namespace std; to the SWIG interface file (this will only affect the way wrappers are created; the using statement will not enter C++ code)
  • Add #define vector std::vector to the SWIG interface file (this will only work if vector is never used as std::vector)
  • Copy the declarations from the header file to the SWIG interface file, and change vector to std::vector. This will cause SWIG to generate correct wrappers, and again will not affect the C++ library code.