簡體   English   中英

在CIG函數中將結構返回到SWIG中的Python

[英]Return Struct from a C++ function to Python in SWIG

我有一個C ++標頭,它返回一個有3個元素的結構。 如何讓python正確接受struct變量?

這就是我在C ++函數中的作用:

  // Function name myfunc
 struct velocity
 {
 std::vector< std::vector<double> > u;
 std::vector< std::vector<double> > v;
 std::vector< std::vector<double> > w;
 }; 

 velocity velo;  //Creating object

 velo.u = sum(umean,pu);
 velo.v = sum(vmean,pv);
 velo.w = sum(wmean,pw);

 return(velo)

這是我使用SWIG后的Python實現

 import numpy
 from myfunc import *    # importing C++ myfunc library
 My = 100       # Matrix dimensions
 Mz = 100
 z = myfunc(My,Mz)    # Supplying the matrix dimensions to the myfunc library
 print(z)

執行此操作時收到的錯誤消息:

 <myfunc.velocity; proxy of <Swig Object of type 'velocity *' at 0x2951ae0> >

我知道我必須以某種方式在SWIG中定義以使python“按原樣”獲取結構。 有什么辦法嗎? 或者您可能建議的任何替代方法? 這是我的SWIG文件

 %module myfunc
 %{
 #include "myfunc.h"  
 %}

 %include "std_vector.i"
 // Instantiate templates used by example
  namespace std {
  %template(IntVector) vector<int>;
  %template(DoubleVector) vector<double>;
  %template(twodvector) std::vector< std::vector<double> >; 
  }

 struct velocity
 {
 std::vector< std::vector<double> > u;
 std::vector< std::vector<double> > v;
 std::vector< std::vector<double> > w;
 };

 %include "myfunc.h"

請注意,我在這里聲明了一個結構。 這在SWIG上成功編譯,但我不知道如何在Python中使用它來實際獲取C ++結構!

這不是錯誤消息:

<myfunc.velocity; proxy of <Swig Object of type 'velocity *' at 0x2951ae0> >

它只是表明你有一個SWIG代理對象,它包含一個指向速度對象的指針。 例如,您可以訪問zu[0][0]以訪問其中一個雙向量的元素。

編輯

這是為vector<vector<double>>定義的類型映射示例。 它們並不漂亮,但允許直接為velocity成員分配Python“列表列表”:

%module x

%begin %{
#pragma warning(disable:4127 4701 4706 4996)
#include <vector>
#include <algorithm>
#include <sstream>
%}

%include <std_vector.i>
%include <std_string.i>
%template(vector_double) std::vector<double>;
%template(vector_vector_double) std::vector<std::vector<double> >;

// Input typemap converts from Python object to C++ object.
// Note error checking not shown for brevity.
// $input is the Python object, $1 is the C++ result.
//
%typemap(in) std::vector<std::vector<double> >* (std::vector<std::vector<double> > tmp) %{
    for(Py_ssize_t i = 0; i < PySequence_Size($input); ++i)
    {
        auto t = PySequence_GetItem($input,i);
        std::vector<double> vd;
        for(Py_ssize_t j = 0; j < PySequence_Size(t); ++j) {
            auto d = PySequence_GetItem(t,j);
            vd.push_back(PyFloat_AsDouble(d));
            Py_DECREF(d);
        }
        Py_DECREF(t);
        tmp.push_back(vd);
    }
    $1 = &tmp;
%}

// Output typemap converts from C++object to Python object.
// Note error checking not shown for brevity.
// $1 is the C++ object, $result is the Python result.
//
%typemap(out) std::vector<std::vector<double> >* %{
    $result = PyList_New($1->size()); // Create outer Python list of correct size
    for(size_t i = 0; i < $1->size(); ++i)
    {
        auto t = PyList_New((*$1)[i].size()); // Create inner Python list of correct size for this element.
        for(size_t j = 0; j < (*$1)[i].size(); ++j) {
            PyList_SET_ITEM(t,j,PyFloat_FromDouble((*$1)[i][j]));
        }
        PyList_SET_ITEM($result,i,t);
    }
%}

%inline %{
    struct velocity
    {
        std::vector<std::vector<double> > u;
        std::vector<std::vector<double> > v;
        std::vector<std::vector<double> > w;
    };

    // A test function with an in/out velocity parameter.
    void myfunc(velocity& vel)
    {
        for(auto& v : vel.u)
            std::transform(begin(v),end(v),begin(v),[](double d){return d*1.1;});
        for(auto& v : vel.v)
            std::transform(begin(v),end(v),begin(v),[](double d){return d*2.2;});
        for(auto& v : vel.w)
            std::transform(begin(v),end(v),begin(v),[](double d){return d*3.3;});
    }
%}

使用示例:

>>> import x
>>> vel=x.velocity()
>>> vel.u = [1,2,3],[4.5,6,7]
>>> vel.v = [1,2],[3,4,5]
>>> vel.w = [1],[2,3]
>>> vel.u
[[1.0, 2.0, 3.0], [4.5, 6.0, 7.0]]
>>> vel.v
[[1.0, 2.0], [3.0, 4.0, 5.0]]
>>> vel.w
[[1.0], [2.0, 3.0]]
>>> x.myfunc(vel)
>>> vel.u
[[1.1, 2.2, 3.3000000000000003], [4.95, 6.6000000000000005, 7.700000000000001]]
>>> vel.v
[[2.2, 4.4], [6.6000000000000005, 8.8, 11.0]]
>>> vel.w
[[3.3], [6.6, 9.899999999999999]]

Mark Tolonen是對的,你所看到的行為不是錯誤。 如果我理解正確,您希望能夠打印myfunc.velocity的實例

AFAIK可以打印任何python對象,它需要定義__str__方法。 Normaly是內置的,但是由於你要包裝一個C-struct,你必須明確定義一個。 我估計有不同的方法可以做到這一點。

擴展結構:

您可以使用Swig的extend指令在C / C ++中定義缺少的函數。

%extend {
   const char* velocity::__str__() {
      std::stringtream ss;
      ss<< "[ ";
      std::copy($self->u.begin(), $self->u.end(), std::ostream_iterator<double>(ss," "));
      ss << std::endl;
      std::copy($self->u.begin(), $self->u.end(), std::ostream_iterator<double>(ss," "));
      ss << std::endl;
      std::copy($self->u.begin(), $self->u.end(), std::ostream_iterator<double>(ss," "));
      ss << "]" << std::endl;

      return ss.str().c_str();
   }
}

這應該將函數__str__添加到velocity結構中,該結構隨后將集成到生成的Python包裝器中。

擴展生成的Python代碼:

另一種方法是為自動生成的Python-Wrapper定義其他方法 您可以使用%pythoncode%指令將Python代碼添加到%pythoncode%接口文件中。 根據您的語言偏好,這可能更容易:

%pythoncode %{
def __str__(self):
    # this is probably horribly inefficient
    return "[" + str(self.u) + "\n" + str(self.v) + "\n" + str(self.w) + " ]"
%}

Swig有大量文檔,請查看Python章節以了解有關更緊密集成的更多信息。

寫便利包裝

當然,您還可以定義第二個Python包裝類,它繼承自myfunc.velocity並定義那里缺少的所有功能。

暫無
暫無

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

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