5

I am using ctypes to access a shared library written in C. The C source of the shared library contains an enum like

enum {
   invalid = 0,
   type1   = 1,
   type2   = 2
} type_enum;

On the Python side I was intending to just define integer constants for the various enum values, like:

INVALID = 0
TYPE1 = 1
TYPE2 = 2  

And then use these numerical "constants" in the Python code calling the C functions. This seems to work OK, however I would strongly prefer to get the numerical values for the enums directly from the shared library (introspection?); however using e.g. nm on the shared library it does not seem to contain any of the symbols 'invalid', 'type1' or 'type2'. So my question is:

  1. Is it possible to extract the numerical values from enum definitions from a shared library - or is the whole enum concept 'dropped on the floor' when the compiler is done?
  2. If the enum values exist in the shared library - how can I access them from Python/ctypes?
Cœur
  • 37,241
  • 25
  • 195
  • 267
user422005
  • 1,989
  • 16
  • 34
  • See [this question](https://stackoverflow.com/q/58732872/235698) for a way to auto-parse a header and even create Python-equivalent enums. – Mark Tolonen Aug 12 '21 at 18:13

2 Answers2

5

Enum definitions are not exported so your current solution is the only one available.

In any case, C enum values are nothing much more than integer constants. There's no type safety on the C side, you can pass any integer values to an enum parameter. So it's not like the C compiler is doing much anyway.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

See MSDN on the benefits of enums: "alternative to the #define preprocessor directive with the advantages that the values can be generated for you and obey normal scoping rules" - notably missing is type safety. This strongly suggests that, as you suggest, enums are dropped on the floor once compiled.

lvc
  • 34,233
  • 10
  • 73
  • 98