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

7 投票
1 回答
7519 浏览
提问于 2025-04-16 13:22

我写了一些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])

当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;

       }

我还有其他方法要在这个二维数组上执行,刚才提到的只是一个简单的例子。

我想做的是把一个Python的二维数组传给我的C++函数,然后再把一个二维数组返回给Python。

我看过一些关于swig的资料,也搜索了一些之前的问题,似乎这是一个可行的解决方案。但我还是搞不清楚我到底需要做什么。

有人能帮帮我吗?谢谢!

1 个回答

11

你可以按照这里的说明使用数组:文档 - 5.4.5 数组,或者使用SWIG库中的carray.istd_vector.i。我发现使用SWIG库中的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);

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__ */

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

如果你运行以下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]

撰写回答