向Python扩展modu添加带十六进制值的符号常量

2024-04-19 13:47:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的头文件中,有几个值被定义为符号常量:

#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);
}

Tags: samplepyreturniftypeargs数组kwargs