在ctypes.Structure

时间:2015-06-12 09:31:12

标签: python ctypes

阅读文档here,我发现您可以使用ctypes.Structure,如下所示: -

>>> class Int(Structure):
...     _fields_ = [("first_16", c_int, 16),
...                 ("second_16", c_int, 16)]
...
>>> print Int

我可以通过使用动态决定的列表来创建这样的类吗?例如,有些东西: -

def int_factory(fields):
    int_class = get_int_class(fields) # This returns a class object with _fields_ set to fields
    return int_class

def user(values=[1,2]):
    int_class = int_factory(int_fields)
    i = int_class(values[0], values[1])

是否可以这样做?

1 个答案:

答案 0 :(得分:5)

在下面的例子中:

  • int_factory 生成 Int
  • user 返回 Int 实例, first_16 设置为1, second_16 设置为2

code.py

#!/usr/bin/env python3

import sys
from ctypes import Structure, \
    c_int


def int_factory(fields):
    return type("Int", (Structure,), {"_fields_": fields})


def user(values=[1, 2]):
    int_fields = (("first_16", c_int, 16), ("second_16", c_int, 16))  # This is just an example to illustrate your class definition. int_fields can be generated dynamically.
    int_class = int_factory(int_fields)
    int_obj = int_class(*values)
    return int_obj


def print_int_obj_data(int_obj):
    print("Type: {:}\n_fields_: {:}".format(int_obj.__class__.__name__, int_obj._fields_))
    for field in int_obj._fields_:
        print("    {:}: {:}".format(field[0], getattr(int_obj, field[0])))


def main():
    int0 = user()
    print_int_obj_data(int0)


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

<强>输出

e:\Work\Dev\StackOverflow\q030799760>"e:\Work\Dev\VEnvs\py27x64_test\Scripts\python.exe" code.py
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32

Type: Int
_fields_: (('first_16', <class 'ctypes.c_long'>, 16), ('second_16', <class 'ctypes.c_long'>, 16))
    first_16: 1
    second_16: 2