使用SWIG将Python数组传递给c ++函数

JMD*_*JMD 7 c++ python swig multidimensional-array

我已经在python中编写了一些代码,它运行得很好.但是现在我正在扩大我正在分析的问题的大小,并且python非常慢.python代码的缓慢部分是

    for i in range(0,H,1):
       x1 = i - length
       x2 = i + length
       for j in range(0,W,1):
          #print i, ',', j    # check the limits
          y1 = j - length
          y2 = j + length
          IntRed[i,j] = np.mean(RawRed[x1:x2,y1:y2])
Run Code Online (Sandbox Code Playgroud)

当H和W等于1024时,该功能大约需要5分钟才能执行.我编写了一个简单的c ++程序/函数,它执行相同的计算,并且在不到一秒的时间内以相同的数据大小进行操作.

   double summ = 0;
   double total_num = 0;
   double tmp_num = 0 ;
   int avesize = 2;
   for( i = 0+avesize; i <X-avesize ;i++)
     for(j = 0+avesize;j<Y-avesize;j++)
       {
         // loop through sub region of the matrix
         // if the value is not zero add it to the sum
         // and increment the counter. 
         for( int ii = -2; ii < 2; ii ++)
           {
             int iii = i + ii;
             for( int jj = -2; jj < 2 ; jj ++ )
               {
                 int jjj = j + jj; 
                 tmp_num = gsl_matrix_get(m,iii,jjj); 
                 if(tmp_num != 0 )
                   {
                     summ = summ + tmp_num;
                     total_num++;
                   }


               }
           }
         gsl_matrix_set(Matrix_mean,i,j,summ/total_num);
         summ = 0;
         total_num = 0;

       }
Run Code Online (Sandbox Code Playgroud)

我还有一些其他方法可以在2D数组上执行.列出的那个是一个简单的例子.

我想要做的是将python 2D数组传递给我的c ++函数并将2D数组返回给python.

我已经阅读了一些关于swig的内容,并且已经解决了过去的问题,看起来它似乎是一个可能的解决方案.但我似乎无法弄清楚我真正需要做什么.

我能得到任何帮助吗?谢谢

小智 11

您可以使用此处描述的数组:Doc - 5.4.5 Arrays,SWIG库carray.istd_vector.iSWIG库.我发现使用SWIG库中的std :: vector更容易std_vector.i将python列表发送到C++ SWIG扩展.虽然在您的情况下优化很重要,但它可能不是最佳的.

在您的情况下,您可以定义:

test.i

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

%include "std_vector.i"

namespace std {
%template(Line)  vector < int >;
    %template(Array) vector < vector < int> >;
}   

void print_array(std::vector< std::vector < int > > myarray);
Run Code Online (Sandbox Code Playgroud)

test.h

#ifndef TEST_H__
#define TEST_H__

#include <stdio.h>
#include <vector>

void print_array(std::vector< std::vector < int > > myarray);

#endif /* TEST_H__ */
Run Code Online (Sandbox Code Playgroud)

TEST.CPP

#include "test.h"

void print_array(std::vector< std::vector < int > > myarray)
{
    for (int i=0; i<2; i++)
        for (int j=0; j<2; j++)
            printf("[%d][%d] = [%d]\n", i, j, myarray[i][j]);
}
Run Code Online (Sandbox Code Playgroud)

如果运行以下python代码(我使用python 2.6.5),您可以看到C++函数可以访问python列表:

>>> import test
>>> a = test.Array()
>>> a = [[0, 1], [2, 3]]
>>> test.print_array(a)
[0][0] = [0]
[0][1] = [1]
[1][0] = [2]
[1][1] = [3]
Run Code Online (Sandbox Code Playgroud)