supplying constants in an extension module

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Torsten Mohr

    #1

    supplying constants in an extension module

    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.

  • Fredrik Lundh

    #2
    Re: supplying constants in an extension module

    Torsten Mohr wrote:
    [color=blue]
    > 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?[/color]

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

    PyMODINIT_FUNC
    initmymodule(vo id)
    {
    PyObject *m;

    m = Py_InitModule(. ..);

    PyModule_AddInt Constant(m, "int", value);
    PyModule_AddStr ingConstant(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(vo id)
    {
    PyObject* m;
    PyObject* d;
    PyObject* x;

    m = Py_InitModule(. ..);
    d = PyModule_GetDic t(m);

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

    x = PyString_FromSt ring("string value");
    if (x) {
    PyDict_SetItemS tring(d, "STRING", x);
    Py_DECREF(x);
    }
    }

    </F>



    Comment

    Working...