C 扩展中的函数随机停止 python 程序执行

Function in C extension randomly stops python program execution

我对 python 的 C 扩展比较陌生。我写了一个扩展,显示了一种对我来说似乎很奇怪的行为。当我 运行 使用此扩展的 python 脚本时,脚本随机停止 扩展中的例程已成功执行后。也就是说,我有一个像这样的脚本:

import FlowCalc
import numpy as np
np.random.seed(1)

lakeNr = 6
trialNr = 10
a = np.round(np.random.rand(trialNr, lakeNr)).astype(int)
b = np.ones(shape=(lakeNr, lakeNr), dtype=float)

x = FlowCalc.flowCalc(a, b)
print(x)

for i in range(100000):
    print(i)

脚本有时会在打印 x 之前停止,有时会在最后的循环中停止,有时根本不会停止。停止的概率取决于 lakeNrtrialNr 的值,但我没有发现任何有用的相关性。这可能只是由于输入矩阵的维数发生变化时填充的随机数不同所致。 在任何情况下都不会抛出异常。程序就像完成了一样停止了。

我能够在我的扩展程序中检测到必须对此行为负责的函数。首先,我向您展示我的包装函数:

static PyObject *FlowCalc_flowCalc(PyObject *self, PyObject *args)
{
    PyArrayObject *trials_array, *flows_array, *result;

    /* Parse the input tuple */
    if (!PyArg_ParseTuple(args, "OO", &trials_array, &flows_array)) {
        PyErr_SetString(PyExc_ValueError,
                    "Exception");
        return NULL;
    }
    pymatrix_to_CarrayptrsInt(trials_array);

    return Py_BuildValue("i", 42);

问题一定出在函数pymatrix_to_CarrayptrsInt:

int **pymatrix_to_CarrayptrsInt(PyArrayObject *arrayin) {
   int **c, *a;
   int i,n,m;

   n=arrayin->dimensions[0];
   m=arrayin->dimensions[1];
   c=ptrvectorInt(n);
   a=(int *) arrayin->data; /* pointer to arrayin data as int */
   for ( i=0; i<n; i++) {
      c[i]=a+i*m; }
   return c;
}

int **ptrvectorInt(long n) {
   int **v;
   v = (int**) malloc((size_t) (n * sizeof(int)));
   if (!v)   {
      printf("In **ptrvectorInt. Allocation of memory for int array failed.");
      exit(0); }
   return v;
}

此方法是 pymatrix_to_CarrayptrsDouble 的更改重新实现:

double **pymatrix_to_CarrayptrsDouble(PyArrayObject *arrayin) {
   double **c, *a;
   int i,n,m;

   n=arrayin->dimensions[0];
   m=arrayin->dimensions[1];
   c=ptrvectorDouble(n);
   a=(double *) arrayin->data; /* pointer to arrayin data as double */
   for ( i=0; i<n; i++) {
      c[i]=a+i*m; }
   return c;
}

double **ptrvectorDouble(long n) {
   double **v;
   v = (double**) malloc((size_t) (n * sizeof(double)));
   if (!v)   {
      printf("In **ptrvectorDouble. Allocation of memory for double array failed.");
      exit(0); }
   return v;
}

double 的版本工作正常,不会引起任何问题。我猜这个问题与内存管理有关,但我不确定。有谁知道 int 版本的问题是什么?

我正在使用 python 3.4 64 位和 Windows 8 64 位(编译器:Visual Studio 10)。

感谢您的帮助!

我想出了如何避免这个问题:应该为输出数组分配内存的函数 ptrvectorInt 没有正常工作。我将其替换为

int **ptrvectorInt(long dim1) {
   int **v;
   if (!(v = malloc(dim1 * sizeof(int*)))) {
      PyErr_SetString(PyExc_MemoryError,
              "In **ptrvectorInt. Allocation of memory for integer array failed.");
      exit(0); 
   }
   return v;
}

一切正常。我仍然不完全了解错误的机制(即它出现的原因以及它随机停止程序的原因)。不过,问题还是解决了。