Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > supplying constants in an extension module

Reply
Thread Tools

supplying constants in an extension module

 
 
Torsten Mohr
Guest
Posts: n/a
 
      01-17-2005
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.

 
Reply With Quote
 
 
 
 
Fredrik Lundh
Guest
Posts: n/a
 
      01-17-2005
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>



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
DataSource: Query String Supplying Parameters Jim McGivney ASP .Net 1 09-03-2006 02:20 AM
supplying runtime parameter sp XML 3 01-27-2006 08:42 AM
Problem writing cookie when supplying Path property =?Utf-8?B?U3llZCBHaGF5YXM=?= ASP .Net 2 05-06-2005 03:55 PM
Making function private/ not supplying declaration in header file Daniel Nichols C Programming 6 06-15-2004 05:03 AM
Making function private/ not supplying declaration in header file Daniel Nichols C Programming 5 06-15-2004 03:38 AM



Advertisments