my_ctypes.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # coding=utf-8
  2. '''
  3. unsigned char* -> POINTER(c_ubyte)
  4. data: bytes
  5. ubuffer = (c.c_ubyte * len(data))(*data)
  6. from ctypes.wintypes import BOOL
  7. '''
  8. import ctypes as c
  9. import sys
  10. charset = "utf-8"
  11. # charset = "gbk"
  12. py_str = lambda x: x.decode(charset) if x is not None else None
  13. str2bytes = lambda x: x.encode(charset) if x is not None else None
  14. # str->const char*
  15. py_str_c_c_char_p = lambda x: c.c_char_p(str2bytes(x))
  16. # str->const wchar*
  17. py_str_c_c_wchar_p = lambda x: c.c_wchar_p(x)
  18. # str->char*
  19. py_str_c_char_p = lambda x, size=None: c.cast(c.create_string_buffer(str2bytes(x), size), c.c_char_p)
  20. # char*->str
  21. c_char_p_py_str = lambda x, size=-1: c.string_at(x, size)
  22. def lib_loader(dll_fps: dict, exported_functions: list):
  23. sp = str(sys.platform)
  24. dll_fp = dll_fps.get(sp)
  25. # create the library...
  26. if sp == "win32":
  27. lib = c.windll.LoadLibrary(dll_fp)
  28. else:
  29. lib = c.cdll.LoadLibrary(dll_fp)
  30. # register the functions...
  31. for item in exported_functions:
  32. func = getattr(lib, item[0])
  33. try:
  34. if item[1]:
  35. func.argtypes = item[1]
  36. func.restype = item[2]
  37. except KeyError:
  38. pass
  39. try:
  40. if item[3]:
  41. func.errcheck = item[3]
  42. except KeyError:
  43. print("Error assigning check function to %s", func)
  44. return lib
  45. def lib_load_default(dll_fps: dict, exported_functions: list):
  46. try:
  47. _lib = lib_loader(dll_fps, exported_functions)
  48. except Exception as e:
  49. # logger.error(e)
  50. _lib = None
  51. return _lib
  52. class BaseStructure(c.Structure):
  53. def __init__(self, **kwargs):
  54. """
  55. Ctypes.Structure with integrated default values.
  56. :param kwargs: values different to defaults
  57. :type kwargs: dict
  58. """
  59. values = type(self)._defaults_.copy()
  60. for (key, val) in kwargs.items():
  61. values[key] = val
  62. super().__init__(**values) # Python 3 syntax