问题描述
我的头文件中有一些定义为符号常量的值:
I have a few values defined as symbolic constants in my header file:
#define NONE 0x00
#define SYM 0x11
#define SEG 0x43
...
这些值的名称表示某种类型的数据.
The names of these values represent a certain type of data.
现在,在我当前的模块实现中,我将所有这些符号链接放入数组中
Now in my current implementation of my module I put all these symbolic links into an array
static unsigned char TYPES[] = { NONE, SYM, SEG, ...}
并将数组中类型的位置添加为模块中的int
常量.
And add the positions of the types in the array as int
constants in the module.
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);
...
}
当调用函数时,我必须做类似的事情:
And when calling functions I have to do something like :
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);
}
我对这种黑客不太满意,我认为它很容易出错,因此我基本上是在寻找一种解决方案,该解决方案无需使用数组,并且可以在函数调用中直接使用常量.有提示吗?
I'm not very happy with this hack and I think it is very prone to errors and so I'm basically looking for a solution which eliminates the array and allows for direct use of the constants in a function call. Any tips?
修改
使用PyModule_AddIntMacro(m, SEG);
并如此调用示例函数即可解决该问题:
Using PyModule_AddIntMacro(m, SEG);
and calling sample function as such, solves it:
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);
}
推荐答案
为什么不只将常量添加到模块中?
Why not just add the constants to the module ?
PyModule_AddIntMacro(m, SYM);
这篇关于将具有十六进制值的符号常量添加到Python扩展模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!