ctypes结构中的默认值

Lew*_*lis 7 python parameters ctypes default structure

在ctypes结构中,是否可以指定默认值?

例如,使用常规python函数,您可以这样做:

def func(a, b=2):
    print a + b
Run Code Online (Sandbox Code Playgroud)

这将允许这种行为:

func(1) # prints 3

func(1, 20) # prints 21

func(1, b=50) # prints 51
Run Code Online (Sandbox Code Playgroud)

是否可以在ctypes结构中执行此操作?

例如:

class Struct(Structure):
    _fields_ = [("a", c_int), ("b", c_int)] # b default should be 2

    def print_values(self):
        print self.a, self.b

struct_instance = Struct(1)

struct_instance.print_values() # should somehow print 1, 2
Run Code Online (Sandbox Code Playgroud)

Pet*_*rin 7

是.只需覆盖该__init__方法即可.

class Struct(Structure):
    _fields_ = [("a", c_int), ("b", c_int)]

    def __init__(self, a, b=2):
        super(Struct, self).__init__(a, b)

    def print_values(self):
        print(self.a, self.b)
Run Code Online (Sandbox Code Playgroud)


Chi*_*kus 5

如果您有很多默认值与 ctypes 不同的结构,则有一种更舒适的方法。将 ctypes.Structure 扩展到另一个类变量_defaults_

class BaseStructure(ctypes.Structure):

    def __init__(self, **kwargs):
        """
        Ctypes.Structure with integrated default values.

        :param kwargs: values different to defaults
        :type kwargs: dict
        """

        values = type(self)._defaults_.copy()
        for (key, val) in kwargs.items():
            values[key] = val

        super().__init__(**values)            # Python 3 syntax



class YourStructure(BaseStructure):
    _fields_ = [ ("param1", ctypes.c_uint32),
                 ("param2", ctypes.c_uint32),
                 ("param3", ctypes.c_int32),
               ]
    _defaults_ = { "param1" : 42,
                   "param3" : -23,
                 }
Run Code Online (Sandbox Code Playgroud)