简体   繁体   English

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

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

I am writing a c++ library and I would love to be able to call it in python. 我正在编写一个c ++库,希望能够在python中调用它。 I would love to use swig I am successfully able to create and compile the python module, but I struggle a bit on understanding how to interface python and c++. 我很乐意使用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);

This is a snap of my header file. 这是我的头文件的快照。 Following my .i file: 在我的.i文件之后:

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


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

In python I am able to create the object: 在python中,我可以创建对象:

In [13]: vector = hausdorff.vector2d

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

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

And I get as error: 我得到错误:

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

How can I pass the right object to the function? 如何将正确的对象传递给函数?

It's a little more complicated than that, at least without more work: 比这要复杂得多,至少不需要更多工作:

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

If you provide constructors for your structure, you can simplify: 如果为结构提供构造函数,则可以简化:

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

If you provide typemap conversions, which I leave as a exercise (or another SO question :^) this can be done: 如果您提供类型映射转换,我将保留它作为练习(或另一个SO问题:^),可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM