Coverage for linuxpy/ctypes.py: 76%

70 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-21 07:58 +0200

1# 

2# This file is part of the linuxpy project 

3# 

4# Copyright (c) 2023 Tiago Coutinho 

5# Distributed under the GPLv3 license. See LICENSE for more info. 

6 

7import collections 

8import ctypes 

9import struct 

10import time 

11 

12from .constants import MICROSEC_PER_SEC, NANOSEC_PER_MICROSEC 

13 

14i8 = ctypes.c_int8 

15i16 = ctypes.c_int16 

16i32 = ctypes.c_int32 

17i64 = ctypes.c_int64 

18 

19u8 = ctypes.c_uint8 

20u16 = ctypes.c_uint16 

21u32 = ctypes.c_uint32 

22u64 = ctypes.c_uint64 

23 

24 

25cint = ctypes.c_int 

26cuint = ctypes.c_uint 

27clong = ctypes.c_long 

28culong = ctypes.c_ulong 

29clonglong = ctypes.c_longlong 

30culonglong = ctypes.c_ulonglong 

31 

32cchar = ctypes.c_char 

33ccharp = ctypes.c_char_p 

34 

35cenum = cuint 

36cvoidp = ctypes.c_void_p 

37 

38fsword = cuint 

39fsblkcnt = culong 

40fsfilcnt = culong 

41 

42cast = ctypes.cast 

43sizeof = ctypes.sizeof 

44byref = ctypes.byref 

45addressof = ctypes.addressof 

46string_at = ctypes.string_at 

47 

48calcsize = struct.calcsize 

49 

50Union = ctypes.Union 

51 

52pointer = ctypes.pointer 

53POINTER = ctypes.POINTER 

54 

55create_string_buffer = ctypes.create_string_buffer 

56cast = ctypes.cast 

57memmove = ctypes.memmove 

58 

59 

60def memcpy(dst, src): 

61 typ = type(dst) 

62 return memmove(byref(dst), byref(src), sizeof(typ)) 

63 

64 

65class Struct(ctypes.Structure): 

66 def __repr__(self): 

67 name = type(self).__name__ 

68 fields = filter(lambda field: field[0] != "reserved", self._fields_) 

69 fields = ", ".join(f"{field[0]}={getattr(self, field[0])}" for field in fields) 

70 return f"{name}({fields})" 

71 

72 def __iter__(self): 

73 for fname, ftype in self._fields_: 

74 yield fname, ftype, getattr(self, fname) 

75 

76 def asdict(self): 

77 r = collections.OrderedDict() 

78 for name, _, value in self: 

79 if hasattr(value, "_fields_"): 

80 value = value.asdict() 

81 r[name] = value 

82 return r 

83 

84 

85class timeval(Struct): 

86 _fields_ = [ 

87 ("secs", ctypes.c_long), 

88 ("usecs", ctypes.c_long), 

89 ] 

90 

91 def set_ns(self, value=None): 

92 if value is None: 92 ↛ 94line 92 didn't jump to line 94 because the condition on line 92 was always true

93 value = time.time_ns() 

94 microsecs = time.time_ns() // NANOSEC_PER_MICROSEC 

95 self.secs = microsecs // MICROSEC_PER_SEC 

96 self.usecs = microsecs % MICROSEC_PER_SEC 

97 

98 

99class timespec(Struct): 

100 _fields_ = [ 

101 ("secs", ctypes.c_long), 

102 ("nsecs", ctypes.c_long), 

103 ] 

104 

105 def timestamp(self): 

106 return self.secs + self.nsecs * 1e-9 

107 

108 

109c = ctypes.cdll.LoadLibrary("libc.so.6")