【问题标题】:Passing Python array to c++ function with SWIG使用 SWIG 将 Python 数组传递给 c++ 函数
【发布时间】:2011-03-09 19:22:46
【问题描述】:

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

当 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 的文章,并且已经找到了一些以前的问题,这似乎是一个可能的解决方案。但我似乎无法弄清楚我真正需要做什么。

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

【问题讨论】:

标签: c++ python multidimensional-array swig


【解决方案1】:

您可以使用此处描述的数组:Doc - 5.4.5 Arrays、SWIG 库中的carray.istd_vector.i。 我发现使用 SWIG 库 std_vector.i 中的 std::vector 将 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]

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 2016-09-15
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多