Python ctypes.cast() Examples
The following are 30
code examples of ctypes.cast().
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
ctypes
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: winspool.py From sk1-wx with GNU General Public License v3.0 | 6 votes |
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
Example #2
Source File: wmi.py From cWMI with Apache License 2.0 | 6 votes |
def GetNames(self, qualifier_name, flags, qualifier_val): prototype = ctypes.WINFUNCTYPE(HRESULT, wintypes.LPCWSTR, ctypes.c_long, ctypes.POINTER(winapi.VARIANT), ctypes.POINTER(wintypes.LPVOID)) paramflags = ((_In_, 'wszQualifierName'), (_In_, 'lFlags'), (_In_, 'pQualifierVal'), (_Out_, 'pNames'), ) _GetNames = prototype(IWbemClassObject_GetNames_Idx, 'GetNames', paramflags) _GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR return_obj = _GetNames(self.this, qualifier_name, flags, ctypes.byref(qualifier_val) if qualifier_val else None ) return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY)) return return_obj
Example #3
Source File: _ffi.py From oscrypto with MIT License | 6 votes |
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
Example #4
Source File: wmi.py From cWMI with Apache License 2.0 | 6 votes |
def GetNames(self, flags): prototype = ctypes.WINFUNCTYPE(HRESULT, ctypes.c_long, ctypes.POINTER(wintypes.LPVOID)) paramflags = ((_In_, 'lFlags'), (_Out_, 'pNames'), ) _GetNames = prototype(IWbemContext_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
Example #5
Source File: workspace.py From typhon with MIT License | 6 votes |
def __verbosity_init__(self): """ Executes verbosityInit WSM directly through the ARTS api to suppress output. """ wsm = workspace_methods["verbosityInit"] (m_id, args_out, args_in, ts) = wsm._parse_output_input_lists(self, [], {}) arg_out_ptr = c.cast((c.c_long * len(args_out))(*args_out), c.POINTER(c.c_long)) arg_in_ptr = c.cast((c.c_long * len(args_in))(*args_in), c.POINTER(c.c_long)) with CoutCapture(self, silent = True): e_ptr = arts_api.execute_workspace_method(self.ptr, m_id, len(args_out), arg_out_ptr, len(args_in), arg_in_ptr) for t in ts[::-1]: t.erase()
Example #6
Source File: monitor.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
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
Example #7
Source File: win.py From recruit with Apache License 2.0 | 6 votes |
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 is 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]
Example #8
Source File: wmi.py From cWMI with Apache License 2.0 | 6 votes |
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
Example #9
Source File: test_ctypeslib.py From recruit with Apache License 2.0 | 6 votes |
def test_reference_cycles(self): # related to gh-6511 import ctypes # create array to work with # don't use int/long to avoid running into bpo-10746 N = 100 a = np.arange(N, dtype=np.short) # get pointer to array pnt = np.ctypeslib.as_ctypes(a) with np.testing.assert_no_gc_cycles(): # decay the array above to a pointer to its first element newpnt = ctypes.cast(pnt, ctypes.POINTER(ctypes.c_short)) # and construct an array using this data b = np.ctypeslib.as_array(newpnt, (N,)) # now delete both, which should cleanup both objects del newpnt, b
Example #10
Source File: leveldb.py From leveldb-py with MIT License | 6 votes |
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
Example #11
Source File: leveldb.py From leveldb-py with MIT License | 6 votes |
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)
Example #12
Source File: mol_lib.py From pytorch_structure2vec with MIT License | 6 votes |
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
Example #13
Source File: privileges.py From minidump with MIT License | 6 votes |
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
Example #14
Source File: s2v_lib.py From pytorch_structure2vec with MIT License | 6 votes |
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
Example #15
Source File: low_level.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #16
Source File: low_level.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #17
Source File: win.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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]
Example #18
Source File: pomp_loop_thread.py From olympe with BSD 3-Clause "New" or "Revised" License | 6 votes |
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) )
Example #19
Source File: shader.py From ratcave with MIT License | 6 votes |
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
Example #20
Source File: moleintor.py From pyscf with Apache License 2.0 | 6 votes |
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)
Example #21
Source File: winspool.py From sk1-wx with GNU General Public License v3.0 | 6 votes |
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
Example #22
Source File: ctypeslib.py From recruit with Apache License 2.0 | 6 votes |
def as_array(obj, shape=None): """ Create a numpy array from a ctypes array or POINTER. The numpy array shares the memory with the ctypes object. The shape parameter must be given if converting from a ctypes POINTER. The shape parameter is ignored if converting from a ctypes array """ if isinstance(obj, ctypes._Pointer): # convert pointers to an array of the desired shape if shape is None: raise TypeError( 'as_array() requires a shape argument when called on a ' 'pointer') p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape)) obj = ctypes.cast(obj, p_arr_type).contents return array(obj, copy=False)
Example #23
Source File: low_level.py From core with MIT License | 5 votes |
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
Example #24
Source File: low_level.py From ServerlessCrawler-VancouverRealState with MIT License | 5 votes |
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
Example #25
Source File: low_level.py From ServerlessCrawler-VancouverRealState with MIT License | 5 votes |
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
Example #26
Source File: radiobuttons.py From pylibui with MIT License | 5 votes |
def uiRadioButtonsPointer(obj): """ Casts an object to uiRadioButtons pointer type. :param obj: a generic object :return: uiRadioButtons """ return ctypes.cast(obj, ctypes.POINTER(uiRadioButtons)) # - void uiRadioButtonsAppend(uiRadioButtons *r, const char *text);
Example #27
Source File: privileges.py From minidump with MIT License | 5 votes |
def get_array(self): array_type = LUID_AND_ATTRIBUTES*self.count privileges = ctypes.cast(self.privileges, ctypes.POINTER(array_type)).contents return privileges
Example #28
Source File: datetimepicker.py From pylibui with MIT License | 5 votes |
def uiDateTimePickerPointer(obj): """ Casts an object to uiDateTimePicker pointer type. :param obj: a generic object :return: uiDateTimePicker """ return ctypes.cast(obj, ctypes.POINTER(uiDateTimePicker)) # - uiDateTimePicker *uiNewDateTimePicker(void);
Example #29
Source File: button.py From pylibui with MIT License | 5 votes |
def uiButtonPointer(obj): """ Casts an object to uiButton pointer type. :param obj: a generic object :return: uiButton """ return ctypes.cast(obj, ctypes.POINTER(uiButton)) # - char *uiButtonText(uiButton *b);
Example #30
Source File: low_level.py From ServerlessCrawler-VancouverRealState with MIT License | 5 votes |
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