Swig - 结构的 c++ 向量以及如何连接它们

Swig - c++ vector of a struct and how to interface them

本文关键字:何连接 连接 结构 c++ 向量 Swig      更新时间:2023-10-16

我正在编写一个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 > >'

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

它比这复杂一些,至少没有更多的工作:

>>> 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)])