【发布时间】:2014-01-28 03:09:42
【问题描述】:
我有一个 yec.c 文件,它定义了一个具有两个函数的结构:
#include <python2.7/Python.h>
struct mec
{
int age;
int number;
};
static PyObject* nopoint(PyObject* self, PyObject* args)
{
struct mec m;
int n1, n2;
if (!PyArg_ParseTuple(args, "ii", &n1, &n2))
return NULL;
printf("nopoint(c) nombres: %d et %d!\n", n1, n2);
m.age = n1;
m.number = n2;
printf("nopoint(c) age nb: %d et %d!\n", m.age, m.number);
return Py_BuildValue("i", n1 + n2);
}
static PyObject* viapoint(PyObject* self, PyObject* args)
{
struct mec *m;
if (!PyArg_ParseTuple(args, "o", &m))
return NULL;
printf("viapoint av(c) age nb: %d et %d!\n", m->age, m->number);
m->age = 10;
m->number = 1;
printf("viapoint ap(c) age nb: %d et %d!\n", m->age, m->number);
return Py_BuildValue("i", m->age + m->number);
}
static PyMethodDef MyYecMethods[] = {
{"nopoint", nopoint, METH_VARARGS, "Description de fune"},
{"viapoint", viapoint, METH_VARARGS, "Description de fdeux"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inityec(void)
{
(void) Py_InitModule("yec", MyYecMethods);
}
我在以下 setup_yec.py 文件中使用python setup_yec.py build 命令将 yec.c 文件编译为 yec.so:
from distutils.core import setup, Extension
module1 = Extension('yec', sources = ['yec.c'])
setup (name = 'YecPkg',
version = '1.0',
description = 'This is a demo of yec pkg',
ext_modules = [module1])
我可以在 Python 下使用我编译的库,并且 nopoint() 函数有效:
import yec
yec.nopoint(3, 4)
我想使用第二个功能;我的库的 viapoint() 应该接受来自 Python 的结构指针,我在其中定义了相关的 ctypes.Structure:
from ctypes import *
class Mec(Structure):
_fields_ = [("age", c_int),
("number", c_int)]
m = Mec(1, 2)
print "py mec class", m.age, m.number
yec.viapoint(byref(m))
当然不行:
Traceback (most recent call last):
File "testyec.py", line 18, in <module>
yec.viapoint(byref(m))
TypeError: must be impossible<bad format char>, not CArgObject
如果有人知道如何修改 viapoint() 函数以便能够通过 PyArg_ParseTuple() 解析结构指针以及如何在 python 中传递 python 结构指针(使用 byref?),那将是一个很大的帮助。
谢谢。
【问题讨论】:
标签: python c pointers structure ctypes