2

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

1 Answer 1

2

Why not just add the constants to the module ?

PyModule_AddIntMacro(m, SYM);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I tried that as well and when I do I get errors when I call the function with the constant. Perhaps I'm reading it in wrong, but I just can't spot the error
I realized my error was that I forgot to cast the int constant to a unsigned char. That solved it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.