1

I have enum that used for communication between python server and c client.

I want to have the enum just in single file, prefer to use python enum class.

Also I prefer to avoid mixing with runtime parsing of C enum in python.

arye
  • 458
  • 3
  • 15
  • @EthanFurman do you understand why it duplicate? the other question is much more complicated in C side, to create bi direction lookup table between string and int, while here need just C enum – arye Feb 26 '23 at 06:34
  • I think it is duplicate of https://stackoverflow.com/questions/65048495/share-enum-between-python-and-arduino as arduino is c based – arye Mar 01 '23 at 06:38

1 Answers1

3

Optional solution is to have the enum in *.py file, which C file can include and python can import.

The file will look like:

#if 0
"""
#endif
typedef enum my_enum{
#if 0
"""
from enum import IntEnum, unique
@unique
class MyEnum(IntEnum):
#endif
    FIRST = 0,
    SECOND = 1,
    THIRD = 2,
#if 0
"""
#endif
}my_enum_e;

#if 0
"""
#endif

The idea behind it is that Python ignores all the C preprocessor commands, as they are in Python triple-quoted strings, which is where I put the C only code.

In the other hand, C ignores everything inside #if 0 - where I put the python code.

The disadvantage in this structure is it bit confusing and I didn't find way to make the numbering automatic.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
arye
  • 458
  • 3
  • 15
  • This has the even bigger disadvantage that in C your enum values are `0`, `1`, and `2`, while in Python it is `(0, )`, `(1, )`, and `(2,)` -- 1-element tuples instead of integers. – Ethan Furman Feb 20 '23 at 01:46
  • @EthanFurman If you are using Enum indeed you will get tuple. But with IntEnum I got integer – arye Feb 20 '23 at 06:04
  • Of course, you're right. Thanks for the reminder. – Ethan Furman Feb 20 '23 at 20:50