Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum definition from shared library

Tags:

python

c

ctypes

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?
like image 463
user422005 Avatar asked Jun 03 '11 08:06

user422005


1 Answers

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.

like image 185
David Heffernan Avatar answered Sep 22 '22 16:09

David Heffernan