将带有hex值的符号常量添加到Python扩展模块

我在头文件中定义了一些值作为符号常量:

#define NONE 0x00 #define SYM 0x11 #define SEG 0x43 ... 

这些值的名称代表某种类型的数据。

现在,在我目前的模块实现中,我将所有这些符号链接放入一个数组中

 static unsigned char TYPES[] = { NONE, SYM, SEG, ...} 

并将数组中类型的位置添加为模块中的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); } 

我对这个hack不太满意,我认为它很容易出错,所以我基本上都在寻找一种解决方案来消除数组并允许在函数调用中直接使用常量。 有小费吗?

编辑

使用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); } 

为什么不将常量添加到模块中?

 PyModule_AddIntMacro(m, SYM);