簡體   English   中英

Swig-結構的C ++向量以及如何連接它們

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

我正在編寫一個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)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM