By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 765 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

supplying constants in an extension module

P: n/a
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.

Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Torsten Mohr wrote:
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>

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.