我对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之前停止,有时在最后的循环中停止,有时根本不停止。停止的概率取决于lakeNr
和trialNr
的值,尽管我没有发现任何有用的相关性。这可能是由于输入矩阵的维数改变时,其填充的随机数不同造成的。在任何情况下都不会引发异常。程序停止了,就好像它结束了一样。你知道吗
我能够检测到我的扩展中必须对这种行为负责的函数。首先,我向您展示我的包装器函数:
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;
}
有双的版本工作正常,不会引起任何问题。我想这个问题与内存管理有关,但我不确定。有人知道int版本的问题是什么吗?你知道吗
am使用Python3.4 64位和Windows8 64位(编译器:VisualStudio10)。你知道吗
谢谢你的帮助!你知道吗
我找到了避免问题的方法:为输出数组分配内存的函数
ptrvectorInt
没有正常工作。我把它换成了一切正常。我仍然不完全知道错误的机制(即它为什么出现以及为什么随机停止程序)。然而,问题解决了。你知道吗
相关问题 更多 >
编程相关推荐