Define a constant in Python C extension

F

fredbasset1000

I'm writing a C extension for Python, is it possible to define
constants in the C code and have them visible from Python?
 
R

Robert Kern

I'm writing a C extension for Python, is it possible to define
constants in the C code and have them visible from Python?

In your init<module> function, create Python objects from the constants
and insert them into the module using PyModule_AddObject(). The
initspam() function in this section does this (though not with #defined
constants):

http://docs.python.org/extending/extending.html#providing-a-c-api-for-an-extension-module

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though
it had
an underlying truth."
-- Umberto Eco
 
M

Mel

I'm writing a C extension for Python, is it possible to define
constants in the C code and have them visible from Python?

There's an API function to create a module-level name with a given value,
e.g.

PyModule_AddIntConstant (module, "S_IRUSR", S_IRUSR); // user read

In this example, S_IRUSR was defined in one of the .h files for the
functions being wrapped.

Mel.
 
S

Stefan Behnel

I'm writing a C extension for Python, is it possible to define
constants in the C code and have them visible from Python?

Have you looked at Cython? It allows you to define e.g. enums as "public"
and will generate the rest for you.

http://cython.org

Stefan
 

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

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top