Does ctypes provide anything for enums and flags?

I have an API that I would like to use from python. This API contains flags and enums implemented by C # define.

// it just almost C so don't bother adding the typedef and parenthesis diarrhea here. routine(API_SOMETHING | API_OTHERTHING) stuff = getflags() ? stuff & API_SOMETHING action(API_INTERESTING) mode = getaction() ? mode == INTERESTING 

If you ignore everything else except the enumerations and flags, my bindings should be translated as follows:

 routine(["something", "otherthing"]) stuff = getflags() if 'something' in stuff action('interesting') mode = getaction() if mode == 'interesting' 

Do ctypes provide mechanisms for this? If not, just talk about your โ€œregularโ€ tool for handling flags and enums in python bindings.

+4
source share
2 answers

I am a little disappointed to answer this question myself. Especially since I found all this from the f * manual.

http://docs.python.org/library/ctypes.html#calling-functions-with-your-own-custom-data-types

To end my answer, I will write code that wraps the element.

 from ctypes import CDLL, c_uint, c_char_p class Flag(object): flags = [(0x1, 'fun'), (0x2, 'toy')] @classmethod def from_param(cls, data): return c_uint(encode_flags(self.flags, data)) libc = CDLL('libc.so.6') printf = libc.printf printf.argtypes = [c_char_p, Flag] printf("hello %d\n", ["fun", "toy"]) 

encode_flags converts this excellent list to an integer.

+4
source

Why don't you use c_uint for the enum parameter and then use such a mapping (enumerations usually represent unsigned integer values):

in C:

 typedef enum { MY_VAR = 1, MY_OTHERVAR = 2 } my_enum_t; 

and in Python:

 class MyEnum(): __slots__ = ('MY_VAR', 'MY_OTHERVAR') MY_VAR = 1 MY_OTHERVAR = 2 myfunc.argtypes = [c_uint, ...] 

Then you can pass the MyEnum fields to the function.

If numbered values โ€‹โ€‹require a string representation, you can use dictionary in the MyEnum class.

+3
source

Source: https://habr.com/ru/post/1313631/


All Articles