Cython Memoryview段故障

时间:2019-09-30 05:45:32

标签: python c cython

尝试使用Cython的memoryview时遇到分段错误。这是我的代码:

def fock_build_init_with_inputs(tei_ints):

     # set the number of orbitals
     norb = tei_ints.shape[0]

     # get memory view of TEIs
     cdef double[:,:,:,::1] tei_memview  = tei_ints

     # get index pairs
     prep_ipss_serial(norb, &tei_memview[0,0,0,0])

void prep_ipss_serial(const int n, const double * const tei) {

   int p, q, r, s, np;
   double maxval;

   const double thresh = 1.0e-9;

   // first we count the number of index pairs with above-threshold integrals
   np = 0;
   for (q = 0; q < n; q++)
     for (p = q; p < n; p++) {
       maxval = 0.0;
       for (s = 0; s < n; s++)
         for (r = s; r < n; r++) {
           maxval = fmax( maxval, fabs( tei[ r + n*s + n*n*p + n*n*n*q ] ) );
         }
       if ( maxval > thresh )
         np++;
     }
   ipss_np = np;

当我通过输入numpy.zeros([n,n,n,n])调用第一个函数来运行代码时,当n超过特定数字时会遇到分段错误(212)。有谁知道导致此问题的原因以及如何解决?

谢谢, 露宁

1 个答案:

答案 0 :(得分:0)

这看起来像32位整数溢出-即213*213*213*213大于最大32位整数。您应该使用64位整数作为索引(long或更明确的int64_t)。

为什么要将memoryview转换为指针?您将不会获得太大的速度,并且会丢失有关形状的任何信息(例如,假设所有尺寸都相同),并且可以让Cython为您处理多维索引。最好将tei参数设置为memoryview而不是指针。