Reputation: 439
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, ...}
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?
Edit
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);
}
Upvotes: 2
Views: 947
Reputation: 3363
Why not just add the constants to the module ?
PyModule_AddIntMacro(m, SYM);
Upvotes: 2