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.

2
  • @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 Commented Feb 26, 2023 at 6:34
  • I think it is duplicate of stackoverflow.com/questions/65048495/… as arduino is c based Commented Mar 1, 2023 at 6:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@EthanFurman If you are using Enum indeed you will get tuple. But with IntEnum I got integer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.