【问题标题】:SWIG argument error when using "using std::vector" in python在 python 中使用“使用 std::vector”时 SWIG 参数错误
【发布时间】:2016-06-29 23:58:42
【问题描述】:

这和this问题很相关

不管这是否是编码练习,我都遇到过类似这样的代码

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 >'

可以通过将 test.hh 中的 using std::vector 更改为 using namespace std 或删除 using std::vector 并将 vector&lt;double&gt; 更改为 std::vector&lt;double&gt; 来解决此问题。这不是我想要的。

问题是我得到了这个代码。我不允许进行更改,但我仍然应该通过 SWIG 在 python 中提供所有内容。这里发生了什么?

提前致谢。

【问题讨论】:

  • 将 using 语句放在头文件中是不行的,你正在找出原因。

标签: python c++ c++11 vector swig


【解决方案1】:

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

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

【讨论】:

  • (或者只是不要通过将using 放在头文件中的全局范围内来强制每个人使用)。
  • 我同意柔印,毫无疑问。这可能是处理这个问题的最佳方式,但不幸的是,这不是问题所在。就 m7thon 的响应而言,第一个项目符号似乎覆盖了 h 文件中的 using std::vector。非常好!其他选项不确定,但由于第一个项目符号,我将其视为已关闭。
  • 第三点(复制和自定义声明)在某种意义上是“正确”的方式,并保证工作。使用%include "test.hh" 确实是头文件可以按原样使用的捷径。前两点是黑客,但如果他们工作...... ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多