我正在包装一个 C 文件,以便可以在 python 中使用它。 C 函数的输出是一个双精度数组。我希望这是 python 中的一个 numpy 数组。我得到垃圾。这是生成错误的示例。
首先是C文件(重点关注最后一个函数定义,其他都应该没问题):
#include <Python.h>
#include <numpy/arrayobject.h>
#include <stdio.h>
static char module_docstring[] =
"docstring";
static char error_docstring[] =
"generate the error";
static PyObject *_aux_error(PyObject *self, PyObject *args);
static PyMethodDef module_methods[] = {
{"error", _aux_error, METH_VARARGS, error_docstring},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC init_tmp(void) {
PyObject *m = Py_InitModule3("_tmp", module_methods, module_docstring);
if (m == NULL)
return;
/* Load `numpy` functionality. */
import_array();
}
static PyObject *_aux_error(PyObject *self ,PyObject *args) {
double vector[2] = {1.0 , 2.0};
npy_intp dims[1] = { 2 };
PyObject *ret = PyArray_SimpleNewFromData(1, dims, (int)NPY_FLOAT , vector );
return ret;
}
编译顺利(据我了解 - 我使用了一个可以编译所有内容的 python 脚本)。
在 python 中,我运行以下脚本来测试我的新模块:
try:
import _tmp
res = _tmp.error()
print(res)
except:
print("fail")
我在屏幕上看到的结果是垃圾。我尝试替换(int)NPY_FLOAT
with (int)NPY_FLOAT32, (int)NPY_FLOAT64, (int)NPY_DOUBLE
我仍然收到垃圾。
我使用的是python2.7。
谢谢!!!
EDIT:按照下面的答案,我将最后一个函数更改为:
static PyObject *_aux_error(PyObject *self, PyObject *args) {
double *vector = calloc(2, sizeof(double));
vector[0] = 1.0;
vector[1] = 2.0;
npy_intp *dims = calloc(1 , sizeof(npy_intp));
dims[1] = 2;
PyObject *ret = PyArray_SimpleNewFromData(1, dims, (int)NPY_FLOAT , &vector );
return ret;
}
现在 python 显示一个空数组。