在我的头文件中,有几个值被定义为符号常量:
#define NONE 0x00
#define SYM 0x11
#define SEG 0x43
...
这些值的名称表示某种类型的数据。在
现在,在我当前的模块实现中,我将所有这些符号链接放入一个数组中
^{pr2}$并将类型在数组中的位置添加为模块中的int
常量。在
PyMODINIT_FUNC initShell(void)
{
PyObject *m;
m= Py_InitModule3("Sample", sample_Methods,"Sample Modules");
if (m == NULL)
return;
...
PyModule_AddIntConstant(m, "NONE", 0);
PyModule_AddIntConstant(m, "SYM", 1);
PyModule_AddIntConstant(m, "SEG", 2);
...
}
当调用函数时,我必须执行以下操作:
static PyObject *py_samplefunction(PyObject *self, PyObject *args, PyObject *kwargs) {
int type;
if (!PyArg_ParseTuple(args,kwargs,"i",&type)
return NULL;
int retc;
retc = sample_function(TYPES[type]);
return Py_BuildValue("i", retc);
}
我对这种方法不太满意,我认为它很容易出错,所以我基本上在寻找一种解决方案,它可以消除数组,并允许在函数调用中直接使用常量。有什么提示吗?在
编辑
使用PyModule_AddIntMacro(m, SEG);
并以此方式调用示例函数,可以解决该问题:
static PyObject *py_samplefunction(PyObject *self, PyObject *args, PyObject *kwargs) {
int type;
if (!PyArg_ParseTuple(args,kwargs,"i",&type)
return NULL;
int retc;
retc = sample_function((unsigned char) type);
return Py_BuildValue("i", retc);
}
为什么不直接在模块中添加常量呢?在
相关问题 更多 >
编程相关推荐