本文整理汇总了Python中ctypes.cast方法的典型用法代码示例。如果您正苦于以下问题:Python ctypes.cast方法的具体用法?Python ctypes.cast怎么用?Python ctypes.cast使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ctypes
的用法示例。
在下文中一共展示了ctypes.cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GetNames
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def GetNames(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemQualifierSet_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
flags
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
示例2: __init__
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def __init__(self, interval, stat_func=None, pattern='.*', sort=False):
if stat_func is None:
def asum_stat(x):
"""returns |x|/size(x), async execution."""
return ndarray.norm(x)/sqrt(x.size)
stat_func = asum_stat
self.stat_func = stat_func
self.interval = interval
self.activated = False
self.queue = []
self.step = 0
self.exes = []
self.re_prog = re.compile(pattern)
self.sort = sort
def stat_helper(name, array):
"""wrapper for executor callback"""
array = ctypes.cast(array, NDArrayHandle)
array = NDArray(array, writable=False)
if not self.activated or not self.re_prog.match(py_str(name)):
return
self.queue.append((self.step, py_str(name), self.stat_func(array)))
self.stat_helper = stat_helper
示例3: array_from_pointer
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def array_from_pointer(library, name, point, size):
ffi_obj = _get_ffi(library)
array = ffi_obj.cast('%s[%s]' % (name, size), point)
total_bytes = ffi_obj.sizeof(array)
if total_bytes == 0:
return []
output = []
string_types = {
'LPSTR': True,
'LPCSTR': True,
'LPWSTR': True,
'LPCWSTR': True,
'char *': True,
'wchar_t *': True,
}
string_type = name in string_types
for i in range(0, size):
value = array[i]
if string_type:
value = ffi_obj.string(value)
output.append(value)
return output
示例4: get
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def get(self, key, verify_checksums=False, fill_cache=True):
error = ctypes.POINTER(ctypes.c_char)()
options = _ldb.leveldb_readoptions_create()
_ldb.leveldb_readoptions_set_verify_checksums(options,
verify_checksums)
_ldb.leveldb_readoptions_set_fill_cache(options, fill_cache)
if self._snapshot is not None:
_ldb.leveldb_readoptions_set_snapshot(options, self._snapshot.ref)
size = ctypes.c_size_t(0)
val_p = _ldb.leveldb_get(self._db.ref, options, key, len(key),
ctypes.byref(size), ctypes.byref(error))
if bool(val_p):
val = ctypes.string_at(val_p, size.value)
_ldb.leveldb_free(ctypes.cast(val_p, ctypes.c_void_p))
else:
val = None
_ldb.leveldb_readoptions_destroy(options)
_checkError(error)
return val
# pylint: disable=W0212
示例5: approximateDiskSizes
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def approximateDiskSizes(self, *ranges):
if self._snapshot is not None:
raise TypeError("cannot calculate disk sizes on leveldb snapshot")
assert len(ranges) > 0
key_type = ctypes.c_void_p * len(ranges)
len_type = ctypes.c_size_t * len(ranges)
start_keys, start_lens = key_type(), len_type()
end_keys, end_lens = key_type(), len_type()
sizes = (ctypes.c_uint64 * len(ranges))()
for i, range_ in enumerate(ranges):
assert isinstance(range_, tuple) and len(range_) == 2
assert isinstance(range_[0], str) and isinstance(range_[1], str)
start_keys[i] = ctypes.cast(range_[0], ctypes.c_void_p)
end_keys[i] = ctypes.cast(range_[1], ctypes.c_void_p)
start_lens[i], end_lens[i] = len(range_[0]), len(range_[1])
_ldb.leveldb_approximate_sizes(self._db.ref, len(ranges), start_keys,
start_lens, end_keys, end_lens, sizes)
return list(sizes)
示例6: make_cintopt
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def make_cintopt(atm, bas, env, intor):
intor = intor.replace('_sph','').replace('_cart','').replace('_spinor','')
c_atm = numpy.asarray(atm, dtype=numpy.int32, order='C')
c_bas = numpy.asarray(bas, dtype=numpy.int32, order='C')
c_env = numpy.asarray(env, dtype=numpy.double, order='C')
natm = c_atm.shape[0]
nbas = c_bas.shape[0]
cintopt = lib.c_null_ptr()
# TODO: call specific ECP optimizers for each intor.
if intor[:3] == 'ECP':
foptinit = libcgto.ECPscalar_optimizer
foptinit(ctypes.byref(cintopt),
c_atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),
c_bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),
c_env.ctypes.data_as(ctypes.c_void_p))
return ctypes.cast(cintopt, _ecpoptHandler)
else:
foptinit = getattr(libcgto, intor+'_optimizer')
foptinit(ctypes.byref(cintopt),
c_atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),
c_bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),
c_env.ctypes.data_as(ctypes.c_void_p))
return ctypes.cast(cintopt, _cintoptHandler)
示例7: PrepareFeatureLabel
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def PrepareFeatureLabel(self, molgraph_list):
c_list = (ctypes.c_void_p * len(molgraph_list))()
total_num_nodes = 0
total_num_edges = 0
for i in range(len(molgraph_list)):
c_list[i] = molgraph_list[i].handle
total_num_nodes += molgraph_list[i].num_nodes
total_num_edges += molgraph_list[i].num_edges
torch_node_feat = torch.zeros(total_num_nodes, self.num_node_feats)
torch_edge_feat = torch.zeros(total_num_edges * 2, self.num_edge_feats)
torch_label = torch.zeros(len(molgraph_list), 1)
node_feat = torch_node_feat.numpy()
edge_feat = torch_edge_feat.numpy()
label = torch_label.numpy()
self.lib.PrepareBatchFeature(len(molgraph_list), ctypes.cast(c_list, ctypes.c_void_p),
ctypes.c_void_p(node_feat.ctypes.data),
ctypes.c_void_p(edge_feat.ctypes.data))
for i in range(len(molgraph_list)):
label[i] = molgraph_list[i].pce
return torch_node_feat, torch_edge_feat, torch_label
示例8: _prepare_graph
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def _prepare_graph(self, graph_list, is_directed=0):
edgepair_list = (ctypes.c_void_p * len(graph_list))()
list_num_nodes = np.zeros((len(graph_list), ), dtype=np.int32)
list_num_edges = np.zeros((len(graph_list), ), dtype=np.int32)
for i in range(len(graph_list)):
if type(graph_list[i].edge_pairs) is ctypes.c_void_p:
edgepair_list[i] = graph_list[i].edge_pairs
elif type(graph_list[i].edge_pairs) is np.ndarray:
edgepair_list[i] = ctypes.c_void_p(graph_list[i].edge_pairs.ctypes.data)
else:
raise NotImplementedError
list_num_nodes[i] = graph_list[i].num_nodes
list_num_edges[i] = graph_list[i].num_edges
total_num_nodes = np.sum(list_num_nodes)
total_num_edges = np.sum(list_num_edges)
self.lib.PrepareBatchGraph(self.batch_graph_handle,
len(graph_list),
ctypes.c_void_p(list_num_nodes.ctypes.data),
ctypes.c_void_p(list_num_edges.ctypes.data),
ctypes.cast(edgepair_list, ctypes.c_void_p),
is_directed)
return total_num_nodes, total_num_edges
示例9: _cf_string_to_unicode
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def _cf_string_to_unicode(value):
"""
Creates a Unicode string from a CFString object. Used entirely for error
reporting.
Yes, it annoys me quite a lot that this function is this complex.
"""
value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))
string = CoreFoundation.CFStringGetCStringPtr(
value_as_void_p, CFConst.kCFStringEncodingUTF8
)
if string is None:
buffer = ctypes.create_string_buffer(1024)
result = CoreFoundation.CFStringGetCString(
value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8
)
if not result:
raise OSError("Error copying C string from CFStringRef")
string = buffer.value
if string is not None:
string = string.decode("utf-8")
return string
示例10: _add_fd_to_loop
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def _add_fd_to_loop(self, fd, cb, fd_events, userdata=None):
if cb is None:
self.logger.info(
"Cannot add fd '{}' to pomp loop without "
"a valid callback function".format(fd)
)
return None
self.fd_userdata[fd] = userdata
userdata = ctypes.cast(
ctypes.pointer(ctypes.py_object(userdata)), ctypes.c_void_p
)
self.c_fd_userdata[fd] = userdata
self.pomp_fd_callbacks[fd] = od.pomp_fd_event_cb_t(cb)
res = od.pomp_loop_add(
self.pomp_loop,
ctypes.c_int32(fd),
od.uint32_t(int(fd_events)),
self.pomp_fd_callbacks[fd],
userdata
)
if res != 0:
raise RuntimeError(
"Cannot add fd '{}' to pomp loop: {} ({})".format(
fd, os.strerror(-res), res)
)
示例11: get_printer_names
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def get_printer_names():
names = []
info = ctypes.POINTER(BYTE)()
pcbNeeded = DWORD(0)
pcReturned = DWORD(0)
winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, NAME, 1, ctypes.byref(info),
0, ctypes.byref(pcbNeeded), ctypes.byref(pcReturned))
bufsize = pcbNeeded.value
if bufsize:
buff = msvcrt.malloc(bufsize)
winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, NAME, 1, buff, bufsize,
ctypes.byref(pcbNeeded),
ctypes.byref(pcReturned))
info = ctypes.cast(buff, ctypes.POINTER(PRINTER_INFO_1))
for i in range(pcReturned.value):
names.append(info[i].pName)
msvcrt.free(buff)
return names
示例12: is_color_printer
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def is_color_printer(prtname):
ret = False
if not prtname:
prtname = get_default_printer()
hptr = open_printer(prtname)
info = ctypes.POINTER(BYTE)()
cbBuf = DWORD(0)
pcbNeeded = DWORD(0)
winspool.GetPrinterA(hptr, 2, ctypes.byref(info),
cbBuf, ctypes.byref(pcbNeeded))
bufsize = pcbNeeded.value
if bufsize:
buff = msvcrt.malloc(bufsize)
winspool.GetPrinterA(hptr, 2, buff, bufsize, ctypes.byref(pcbNeeded))
info = ctypes.cast(buff, ctypes.POINTER(PRINTER_INFO_2))
ret = info.contents.pDevMode.contents.dmColor == 2
msvcrt.free(buff)
close_printer(hptr)
return ret
示例13: _createShader
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [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
示例14: load_name
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def load_name(self, offset):
"""
Load a timezone name from a DLL offset (integer).
>>> from dateutil.tzwin import tzres
>>> tzr = tzres()
>>> print(tzr.load_name(112))
'Eastern Standard Time'
:param offset:
A positive integer value referring to a string from the tzres dll.
..note:
Offsets found in the registry are generally of the form
`@tzres.dll,-114`. The offset in this case if 114, not -114.
"""
resource = self.p_wchar()
lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR)
nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0)
return resource[:nchar]
示例15: enable_debug_privilege
# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import cast [as 别名]
def enable_debug_privilege():
"""
Try to assign the symlink privilege to the current process token.
Return True if the assignment is successful.
"""
# create a space in memory for a TOKEN_PRIVILEGES structure
# with one element
size = ctypes.sizeof(TOKEN_PRIVILEGES)
size += ctypes.sizeof(LUID_AND_ATTRIBUTES)
buffer = ctypes.create_string_buffer(size)
tp = ctypes.cast(buffer, ctypes.POINTER(TOKEN_PRIVILEGES)).contents
tp.count = 1
tp.get_array()[0].enable()
tp.get_array()[0].LUID = get_debug_luid()
token = get_process_token()
res = AdjustTokenPrivileges(token, False, tp, 0, None, None)
if res == 0:
raise RuntimeError("Error in AdjustTokenPrivileges")
ERROR_NOT_ALL_ASSIGNED = 1300
return ctypes.windll.kernel32.GetLastError() != ERROR_NOT_ALL_ASSIGNED