本文整理汇总了Python中ctypes.c_char方法的典型用法代码示例。如果您正苦于以下问题:Python ctypes.c_char方法的具体用法?Python ctypes.c_char怎么用?Python ctypes.c_char使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ctypes
的用法示例。
在下文中一共展示了ctypes.c_char方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ctypes2buffer
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def ctypes2buffer(cptr, length):
"""Convert ctypes pointer to buffer type.
Parameters
----------
cptr : ctypes.POINTER(ctypes.c_char)
Pointer to the raw memory region.
length : int
The length of the buffer.
Returns
-------
buffer : bytearray
The raw byte memory buffer.
"""
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
示例2: _dgemm
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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
示例3: frompointer
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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)
示例4: _createShader
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def _createShader(self, strings, shadertype):
# create the shader handle
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
示例5: enum_process_names
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def enum_process_names():
pid_to_name = {}
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
示例6: test_padded_union
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def test_padded_union(self):
dt = np.dtype(dict(
names=['a', 'b'],
offsets=[0, 0],
formats=[np.uint16, np.uint32],
itemsize=5,
))
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
])
示例7: MessageClass
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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
示例8: synchronized
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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)
try:
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
#
示例9: __init__
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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)
示例10: __init__
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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)
示例11: FillConsoleOutputCharacter
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
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
示例12: __getstate__
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def __getstate__(self):
handle = self.handle
this = {'handle' : None}
if handle is not None:
length = ctypes.c_size_t()
cptr = ctypes.POINTER(ctypes.c_char)()
check_call(_LIB.MXNDArraySaveRawBytes(self.handle,
ctypes.byref(length),
ctypes.byref(cptr)))
this['handle'] = ctypes2buffer(cptr, length.value)
return this
示例13: __setstate__
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def __setstate__(self, state):
# pylint: disable=assigning-non-slot
handle = state['handle']
if handle is not None:
buf = handle
handle = NDArrayHandle()
ptr = (ctypes.c_char * len(buf)).from_buffer(buf)
length = ctypes.c_size_t(len(buf))
check_call(_LIB.MXNDArrayLoadFromRawBytes(ptr, length, ctypes.byref(handle)))
self.handle = handle
else:
self.handle = None
# pylint: disable=line-too-long
示例14: __init__
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def __init__(self, symbol_file,
param_raw_bytes, input_shapes,
dev_type="cpu", dev_id=0):
dev_type = devstr2type[dev_type]
indptr = [0]
sdata = []
keys = []
for k, v in input_shapes.items():
if not isinstance(v, tuple):
raise ValueError("Expect input_shapes to be dict str->tuple")
keys.append(c_str(k))
sdata.extend(v)
indptr.append(len(sdata))
handle = PredictorHandle()
param_raw_bytes = bytearray(param_raw_bytes)
ptr = (ctypes.c_char * len(param_raw_bytes)).from_buffer(param_raw_bytes)
_check_call(_LIB.MXPredCreate(
c_str(symbol_file),
ptr, len(param_raw_bytes),
ctypes.c_int(dev_type), ctypes.c_int(dev_id),
mx_uint(len(indptr) - 1),
c_array(ctypes.c_char_p, keys),
c_array(mx_uint, indptr),
c_array(mx_uint, sdata),
ctypes.byref(handle)))
self.handle = handle
示例15: _get_void_ptr
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import c_char [as 别名]
def _get_void_ptr(arr):
simple_arr = numpy.asarray(_internal._unsafe_first_element_pointer(arr))
c_arr = (ctypes.c_char * 0).from_buffer(simple_arr)
return ctypes.cast(ctypes.byref(c_arr), ctypes.c_void_p)
# patch _get_void_ptr as a workaround to numpy issue #13808