supplying constants in an extension module

T

Torsten Mohr

Hi,

i write an extension module in C at the moment.

I want to define some constants (integer mainly,
but maybe also some strings).

How do i do that best within this extension module
in C? Do i supply them as RO attributes?

What's the best way for it?


Thanks for hints,
Torsten.
 
F

Fredrik Lundh

Torsten said:
i write an extension module in C at the moment.

I want to define some constants (integer mainly,
but maybe also some strings).

How do i do that best within this extension module
in C? Do i supply them as RO attributes?

What's the best way for it?

reading the source for existing modules will teach you many useful
idioms. here's how this is currently done:

PyMODINIT_FUNC
initmymodule(void)
{
PyObject *m;

m = Py_InitModule(...);

PyModule_AddIntConstant(m, "int", value);
PyModule_AddStringConstant(m, "string", "string value");
}

(both functions set the exception state and return -1 if they fail, but you
can usually ignore this; the importing code will check the state on return
from the init function)

if you want to support older versions of Python, you need to add stuff to
the module dictionary yourself. an example:

#if PY_VERSION_HEX < 0x02030000
DL_EXPORT(void)
#else
PyMODINIT_FUNC
#endif
initmymodule(void)
{
PyObject* m;
PyObject* d;
PyObject* x;

m = Py_InitModule(...);
d = PyModule_GetDict(m);

x = PyInt_FromLong(value);
if (x) {
PyDict_SetItemString(d, "INT", x);
Py_DECREF(x);
}

x = PyString_FromString("string value");
if (x) {
PyDict_SetItemString(d, "STRING", x);
Py_DECREF(x);
}
}

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top