在python中使用"using std::vector"时SWIG参数错误

SWIG argument error when using "using std::vector" in python

本文关键字:vector SWIG 错误 参数 using python std      更新时间:2023-10-16

这与这个问题非常相关

不管这是不是编码实践,我遇到过这样的代码

test.hh

#include <vector>                                                                                   
using std::vector;                                                             
class Test 
{                                                                     
    public:                                                                      
        vector<double> data;                                                     
};  

我正在尝试使用swig3.0使用以下接口文件

test.i

%module test_swig                                                                
%include "std_vector.i"                                                          
namespace std {                                                                  
    %template(VectorDouble) vector<double>;                                      
};                                                                               
%{                                                                               
    #include "test.hh"                                                               
%}                                                                               
%naturalvar Test::data;                                                                                 
%include "test.hh"    

和下面的测试代码

test.py

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

这样做会产生以下错误

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

这可以通过更改测试中的using std::vector来修复。hh为using namespace std或去除using std::vector,将vector<double>改为std::vector<double>。这不是我想要的

问题是我得到的代码是这样的。我不允许进行更改,但我应该仍然通过SWIG在python中提供所有可用的内容。这是怎么回事?

对我来说,这看起来像是SWIG不正确地支持using std::vector;语句。我认为这是一个SWIG bug。我可以想到以下的解决方法:

  • using namespace std;添加到SWIG接口文件中(这只会影响包装的创建方式;using语句不会进入c++代码)
  • #define vector std::vector添加到SWIG接口文件中(这只会在vector从未用作std::vector时起作用)
  • 将头文件中的声明复制到SWIG接口文件中,并将vector更改为std::vector。这将导致SWIG生成正确的包装器,并且不会影响c++库代码。