【问题标题】:Swig - c++ vector of a struct and how to interface themSwig - 结构的 C++ 向量以及如何连接它们
【发布时间】:2017-11-02 15:50:08
【问题描述】:

我正在编写一个 c++ 库,我希望能够在 python 中调用它。 我很想使用 swig 我能够成功地创建和编译 python 模块,但是我在理解如何连接 python 和 c++ 方面有点挣扎。

struct twod {
        double x; ///< x value
        double y; ///< y value
    };

    double distance_calculation(std::vector <twod>  A, std::vector <twod> B);

这是我的头文件的快照。按照我的 .i 文件:

%module hausdorff
%{
#include "Hausdorff.h"
using namespace hausdorff;
%}


%include "std_vector.i"
%include "Hausdorff.h"
namespace std {
    %template(vector2d) vector<twod>;
}

在 python 中我可以创建对象:

In [13]: vector = hausdorff.vector2d

In [14]: vector = ([1,2], [3,4])

In [15]: result = hausdorff.distance_calculation(vector, vector)

我得到错误:

TypeError: in method 'distance_calculation', argument 1 of type 'std::vector< hausdorff::twod,std::allocator< hausdorff::twod > >'

如何将正确的对象传递给函数?

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

    比这要复杂一点,至少不用做更多工作:

    >>> import hausdorff
    >>> v = hausdorff.vector2d()
    >>> a = hausdorff.twod()
    >>> a.x = 1.2
    >>> a.y = 2.3
    >>> v.push_back(a)
    >>> a.x = 3.4
    >>> a.y = 4.5
    >>> v.push_back(a)
    >>> test.distance_calculation(v,v)
    

    如果你为你的结构提供构造函数,你可以简化:

    >>> test.distance_calculation([test.twod(1.2,3.4),test.twod(1.2,3.4)],
                                  [test.twod(4.5,6.7),test.twod(1.2,3.4)])
    

    如果您提供类型映射转换,我将其留作练习(或另一个 SO 问题 :^),可以这样做:

    >>> test.distance_calculation([(1.1,2.2),(3.3,4.4)],[(5.5,6.6),(7.7,8.8)])
    

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多