我一直致力于将一些C代码转换为Python模块。我是按照本教程的,
http://dan.iel.fm/posts/python-c-extensions/
像我在本文中所做的那样,将Python模块用于简单函数(如函数的函数)非常简单,
Argument passing in Python module written in C
然而,我对如何处理我传递指针但没有返回任何内容的函数感到困惑。
例如,我在C中有这个功能,
void insert_source(node_t *node, source_t *source) {
node_t *quadrant;
// Check if the MAX has been reached
if (node->contents.length == MAX)
subdivide(node);
// A node in the tree will be filled with either content or sub
// quadrants. Check to see whether subquads exist.
if (node->q1 != NULL) {
if (source->alpha >= node->xmid) {
if (source->delta >= node->ymid)
quadrant = node->q1;
else
quadrant = node->q4;
} else {
if (source->delta >= node->ymid)
quadrant = node->q2;
else
quadrant = node->q3;
}
insert_source(quadrant, source);
} else {
// If no subquads exist add source to the list in contents element
// Use push() to prepend the source on the list.
push(&node->contents, source);
}
}
然后我的(不完整的)尝试包装器,
static void *Quadtree_insert_source(PyObject *self, PyObject *args) {
PyObject *node_obj, *source_obj;
if (!PyArg_ParseTuple(args, "OO", &node_obj, &source_obj))
return NULL;
PyObject *node_array = PyArray_FROM_OTF(node_obj, NPY_DOUBLE, NPY_IN_ARRAY);
PyObject *source_array = PyArray_FROM_OTF(source_obj, NPY_DOUBLE, NPY_IN_ARRAY);
if (node_array == NULL || source_array == NULL) {
Py_XDECREF(node_array);
Py_XDECREF(source_array);
}
node_t *node = (node_t*)PyArray_DATA(node_array)
source_t *source = (source_t*)PyArray_DATA(source_array)
/* Don't know what to put on this line */
void insert_source(node, source);
Py_DECREF(node_array);
Py_DECREF(source_array);
/* Don't know what to return/if I should return anything */
}
我链接的教程说我要调用的任何函数都必须返回一个PyObject,我只是不知道在这种情况下应该是什么。
作为参考,以下是我在insert_source中使用的结构:
node_t
typedef struct node_t {
box_t box;
double xmid, ymid;
struct node_t *q1, *q2, *q3, *q4;
list_t contents;
} node_t;
source_t
typedef struct source_t {
list_links_t links;
struct source_t *next, *prev;
int number;
double flux_iso, fluxerr_iso, flux_aper, fluxerr_aper;
double x_image, y_image, alpha, delta;
double mag_auto, magerr_auto, mag_best, magerr_best;
double mag_aper, magerr_aper, a_world, erra_world;
double b_world, errb_world, theta;
double errtheta, isoarea_img, mu_max, flux_radius;
int flags;
double fwhm, elongation, vignet;
struct source_t *match2, *match3;
} source_t;
Quadtree只是构成四叉树功能的一组函数,包括insert_source。 C代码现在都是功能性的,它只是制作Python界面的问题。
答案 0 :(得分:0)
我仔细阅读了documentation并看到了这个
如果你的C函数没有返回有用的参数(函数返回void),相应的Python函数必须返回None。你需要这个成语(由Py_RETURN_NONE宏实现):
Py_INCREF(Py_None);
返回Py_None;
那么包装器的最后一部分是这样的,
insert_source(node, source);
Py_DECREF(node_array);
Py_DECREF(source_array);
Py_INCREF(Py_None);
return Py_None;
?任何人都可以确认吗?