supplying constants in an extension module

Discussion in 'Python' started by Torsten Mohr, Jan 17, 2005.

  1. Torsten Mohr

    Torsten Mohr Guest

    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.
    Torsten Mohr, Jan 17, 2005
    #1
    1. Advertising

  2. 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>
    Fredrik Lundh, Jan 17, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?U3llZCBHaGF5YXM=?=

    Problem writing cookie when supplying Path property

    =?Utf-8?B?U3llZCBHaGF5YXM=?=, May 6, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    442
    =?Utf-8?B?bWljcm9zb2Z0LnB1YmxpYy5kb3RuZXQuZnJhbWV3
    May 6, 2005
  2. sp
    Replies:
    3
    Views:
    702
    Philippe Poulard
    Jan 27, 2006
  3. Daniel Nichols
    Replies:
    6
    Views:
    423
    CBFalconer
    Jun 15, 2004
  4. Daniel Nichols
    Replies:
    5
    Views:
    439
  5. Jim McGivney
    Replies:
    1
    Views:
    450
    =?Utf-8?B?UGV0ZXIgQnJvbWJlcmcgW0MjIE1WUF0=?=
    Sep 3, 2006
Loading...

Share This Page