def mem_2(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open('MEM:::') gdal.PopErrorHandler() if ds is not None: gdaltest.post_reason('opening MEM dataset should have failed.') return 'fail' try: import ctypes except: return 'skip' for libname in ['msvcrt', 'libc.so.6']: try: crt = ctypes.CDLL(libname) except: crt = None if crt is not None: break if crt is None: return 'skip' malloc = crt.malloc malloc.argtypes = [ctypes.c_size_t] malloc.restype = ctypes.c_void_p free = crt.free free.argtypes = [ctypes.c_void_p] free.restype = None # allocate band data array. width = 50 height = 3 p = malloc(width * height * 4) if p is None: return 'skip' float_p = ctypes.cast(p, ctypes.POINTER(ctypes.c_float)) # build ds name. dsnames = [ 'MEM:::DATAPOINTER=0x%X,PIXELS=%d,LINES=%d,BANDS=1,DATATYPE=Float32,PIXELOFFSET=4,LINEOFFSET=%d,BANDOFFSET=0' % (p, width, height, width * 4), 'MEM:::DATAPOINTER=0x%X,PIXELS=%d,LINES=%d,DATATYPE=Float32' % (p, width, height) ] for dsname in dsnames: for i in range(width * height): float_p[i] = 5.0 ds = gdal.Open(dsname) if ds is None: gdaltest.post_reason('opening MEM dataset failed.') free(p) return 'fail' chksum = ds.GetRasterBand(1).Checksum() if chksum != 750: gdaltest.post_reason('checksum failed.') print(chksum) free(p) return 'fail' ds.GetRasterBand(1).Fill(100.0) ds.FlushCache() if float_p[0] != 100.0: print(float_p[0]) gdaltest.post_reason('fill seems to have failed.') free(p) return 'fail' ds = None free(p) return 'success'
import ctypes import time SendInput = ctypes.windll.user32.SendInput # C struct redefinitions PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): _fields_ = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): _fields_ = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): _fields_ = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): _fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure):
class _U1(ct.Union): _fields_ = [("match", ct.POINTER(ct.POINTER(xt_entry_match))), ("target", ct.POINTER(ct.POINTER(xt_entry_target)))]
def ref(value, offset=0): if offset == 0: return ctypes.byref(value) return ctypes.cast(ctypes.addressof(value) + offset, ctypes.POINTER(ctypes.c_byte))
import ctypes from pprint import pprint Py_ssize_t = ctypes.c_int64 if hasattr(ctypes.pythonapi, 'Py_InitModule4_64') else ctypes.c_int class PyObject(ctypes.Structure): pass PyObject._fields_ = [('ob_refcnt', Py_ssize_t), ('ob_type', ctypes.POINTER(PyObject))] class Proxy(PyObject): _fields_ = [ ('dict', ctypes.POINTER(PyObject)), ] """ This is a bunch of jank in order to build the structure: ob_refcnt - Py_ssize_t ob_type - *PyObject dict - *PyObject At the same time it bootstraps the notion of a PyObject """ def shimmed(class_):
def memhandle_as_ctypes_array_32(self, memhandle): return ctypes.cast(memhandle, ctypes.POINTER(ctypes.c_ulong))
class DataBlob(ctypes.Structure): _fields_ = [('cbData', ctypes.wintypes.DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))]
def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. """ import ctypes from types import TracebackType # figure out side of _Py_ssize_t if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'): _Py_ssize_t = ctypes.c_int64 else: _Py_ssize_t = ctypes.c_int # regular python class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] # python with trace if object.__basicsize__ != ctypes.sizeof(_PyObject): class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('_ob_next', ctypes.POINTER(_PyObject)), ('_ob_prev', ctypes.POINTER(_PyObject)), ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] class _Traceback(_PyObject): pass _Traceback._fields_ = [ ('tb_next', ctypes.POINTER(_Traceback)), ('tb_frame', ctypes.POINTER(_PyObject)), ('tb_lasti', ctypes.c_int), ('tb_lineno', ctypes.c_int) ] def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Traceback.from_address(id(tb.tb_next)) old.ob_refcnt -= 1 if next is None: obj.tb_next = ctypes.POINTER(_Traceback)() else: next = _Traceback.from_address(id(next)) next.ob_refcnt += 1 obj.tb_next = ctypes.pointer(next) return tb_set_next # try to get a tb_set_next implementation try: tb_set_next = _init_ugly_crap() except: tb_set_next = None
def to_double_ref(nparray): return nparray.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
def _database_downloaded(self, branch, progress, reply): """ Called when the file has been downloaded. :param branch: the branch :param progress: the progress dialog :param reply: the reply from the server """ # Close the progress dialog progress.close() # Get the absolute path of the file appPath = QCoreApplication.applicationFilePath() appName = QFileInfo(appPath).fileName() fileExt = 'i64' if '64' in appName else 'idb' fileName = '%s_%s.%s' % (branch.repo, branch.name, fileExt) filePath = local_resource('files', fileName) # Write the packet content to disk with open(filePath, 'wb') as outputFile: outputFile.write(reply.content) logger.info("Saved file %s" % fileName) # Save the old database database = ida_loader.get_path(ida_loader.PATH_TYPE_IDB) if database: ida_loader.save_database(database, ida_loader.DBFL_TEMP) # Get the dynamic library idaname = 'ida64' if '64' in appName else 'ida' if sys.platform == 'win32': dllname, dlltype = idaname + '.dll', ctypes.windll elif sys.platform == 'linux2': dllname, dlltype = 'lib' + idaname + '.so', ctypes.cdll elif sys.platform == 'darwin': dllname, dlltype = 'lib' + idaname + '.dylib', ctypes.cdll dllpath = ida_diskio.idadir(None) if not os.path.exists(os.path.join(dllpath, dllname)): dllpath = dllpath.replace('ida64', 'ida') dll = dlltype[os.path.join(dllpath, dllname)] # Close the old database oldPath = ida_loader.get_path(ida_loader.PATH_TYPE_IDB) if oldPath: dll.term_database() # Open the new database LP_c_char = ctypes.POINTER(ctypes.c_char) args = [appName, filePath] argc = len(args) argv = (LP_c_char * (argc + 1))() for i, arg in enumerate(args): arg = arg.encode('utf-8') argv[i] = ctypes.create_string_buffer(arg) LP_c_int = ctypes.POINTER(ctypes.c_int) v = ctypes.c_int(0) av = ctypes.addressof(v) pv = ctypes.cast(av, LP_c_int) dll.init_database(argc, argv, pv) # Create a copy of the new database fileExt = '.i64' if '64' in appName else '.idb' tmpFile, tmpPath = tempfile.mkstemp(suffix=fileExt) shutil.copyfile(filePath, tmpPath) class UIHooks(ida_kernwin.UI_Hooks): def database_inited(self, is_new_database, idc_script): self.unhook() # Remove the tmp database os.close(tmpFile) if os.path.exists(tmpPath): os.remove(tmpPath) hooks = UIHooks() hooks.hook() # Open the tmp database s = ida_loader.snapshot_t() s.filename = tmpPath ida_kernwin.restore_database_snapshot(s, None, None)
def callback_fun(hackrf_transfer): array_type = (ctypes.c_byte*length) values = ctypes.cast(hackrf_transfer.contents.buffer, ctypes.POINTER(array_type)).contents #iq data here iq = hackrf.packed_bytes_to_iq(values) return 0
def __init__(self, obj, imports=None): size = obj.byte_size if not obj.debug_info: raise ValueError( 'Unable to load "{}"' " because it does not contain debug info.".format(obj)) # Create a code page into memory: self._code_page = MemoryPage(size) self._data_page = MemoryPage(size) # Create callback pointers if any: imports = imports or {} self._import_symbols = [] extra_symbols = {} for name, function in imports.items(): signature = inspect.signature(function) if signature.return_annotation is inspect._empty: raise ValueError( '"{}" requires return type annotations'.format(name)) return_type = signature.return_annotation argument_types = [ p.annotation for p in signature.parameters.values() ] restype = get_ctypes_type(return_type) argtypes = [get_ctypes_type(a) for a in argument_types] ftype = ctypes.CFUNCTYPE(restype, *argtypes) callback = ftype(function) logger.debug("Import name %s", name) self._import_symbols.append((name, callback, ftype)) extra_symbols[name] = ctypes.cast(callback, ctypes.c_void_p).value # Link to e.g. apply offset to global literals layout2 = layout.Layout() layout_code_mem = layout.Memory("codepage") layout_code_mem.location = self._code_page.addr layout_code_mem.size = size layout_code_mem.add_input(layout.Section("code")) layout2.add_memory(layout_code_mem) layout_data_mem = layout.Memory("datapage") layout_data_mem.location = self._data_page.addr layout_data_mem.size = size layout_data_mem.add_input(layout.Section("data")) layout2.add_memory(layout_data_mem) # Link the object into memory: obj = link([obj], layout=layout2, debug=True, extra_symbols=extra_symbols) assert obj.byte_size == size # Load the code into the page: code = bytes(obj.get_section("code").data) self._code_page.write(code) data = bytes(obj.get_section("data").data) self._data_page.write(data) # TODO: we might have more sections! # Get a function pointer for function in obj.debug_info.functions: function_name = function.name # Determine the function type: restype = get_ctypes_type(function.return_type) argtypes = [get_ctypes_type(a.typ) for a in function.arguments] logger.debug("function sig %s %s", restype, argtypes) ftype = ctypes.CFUNCTYPE(restype, *argtypes) # Create a function pointer: vaddress = obj.get_symbol_id_value(function.begin.symbol_id) fpointer = ftype(vaddress) # Set the attribute: setattr(self, function_name, fpointer) # Get a variable pointers for variable in obj.debug_info.variables: variable_name = variable.name assert isinstance(variable, debuginfo.DebugVariable) assert isinstance(variable.address, debuginfo.DebugAddress) vaddress = obj.get_symbol_id_value(variable.address.symbol_id) var_ctyp = ctypes.POINTER(get_ctypes_type(variable.typ)) vpointer = ctypes.cast(vaddress, var_ctyp) # Set the attribute: setattr(self, variable_name, vpointer) # Store object for later usage: self._obj = obj
def stabilizer_free(stab): lib.stabilizer_free.argtypes = [ctypes.POINTER(Stabilizer)] lib.stabilizer_free(ctypes.byref(stab))
method_getTypeEncoding.restype = c_char_p sel_getName = c.sel_getName sel_getName.restype = c_char_p sel_getName.argtypes = [c_void_p] sel_registerName = c.sel_registerName sel_registerName.restype = c_void_p sel_registerName.argtypes = [c_char_p] object_getClass = c.object_getClass object_getClass.argtypes = [c_void_p] object_getClass.restype = c_void_p class_copyMethodList = c.class_copyMethodList class_copyMethodList.restype = ctypes.POINTER(c_void_p) class_copyMethodList.argtypes = [c_void_p, ctypes.POINTER(ctypes.c_uint)] class_getProperty = c.class_getProperty class_getProperty.restype = c_void_p class_getProperty.argtypes = [c_void_p, c_char_p] property_getAttributes = c.property_getAttributes property_getAttributes.argtypes = [c_void_p] property_getAttributes.restype = c_char_p method_getName = c.method_getName method_getName.restype = c_void_p method_getName.argtypes = [c_void_p] class objc_method_description (Structure):
csvdbLib.Column_delete.argstypes = [ctypes.c_void_p] csvdbLib.Column_delete.restype = None csvdbLib.CreateIntWhereConst.argstypes = [ctypes.c_int64] csvdbLib.CreateIntWhereConst.restype = ctypes.c_void_p csvdbLib.CreateTimestampWhereConst.argstypes = [ctypes.c_uint64] csvdbLib.CreateTimestampWhereConst.restype = ctypes.c_void_p csvdbLib.CreateVarcharWhereConst.argstypes = [ctypes.c_char_p] csvdbLib.CreateVarcharWhereConst.restype = ctypes.c_void_p csvdbLib.CreateFloatWhereConst.argstypes = [ctypes.c_double] csvdbLib.CreateFloatWhereConst.restype = ctypes.c_void_p csvdbLib.Table_Create.argstypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_int), \ ctypes.c_int, ctypes.POINTER(ctypes.c_int), \ ctypes.c_int, ctypes.c_int, ctypes.c_void_p, \ ctypes.c_int, ctypes.c_int, \ ctypes.c_int, ctypes.POINTER(ctypes.c_int), \ ctypes.POINTER(ctypes.c_int), ctypes.c_void_p, \ ctypes.c_int, ctypes.POINTER(ctypes.c_int), \ ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int, ctypes.c_void_p] csvdbLib.Table_Create.restype = ctypes.c_void_p csvdbLib.Table_select.argstypes = [ctypes.c_void_p, ctypes.c_char_p] csvdbLib.Table_select.restype = None csvdbLib.Table_delete.argstypes = [ctypes.c_void_p] csvdbLib.Table_delete.restype = None
def to_int_ref(nparray): return nparray.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
def memhandle_as_ctypes_array(self, memhandle): return ctypes.cast(memhandle, ctypes.POINTER(ctypes.c_ushort))
IID_IWbemLocator = GUID("{dc12a687-737f-11cf-884d-00aa004b2e24}") # generic prototype Generic_Proto = ct.WINFUNCTYPE(HRESULT, wt.LPVOID) # virtual HRESULT STDMETHODCALLTYPE QueryInterface( # /* [in] */ REFIID riid, # /* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR *__RPC_FAR *ppvObject) = 0; # # virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0; # # virtual ULONG STDMETHODCALLTYPE Release( void) = 0; # IUnknown method prototypes IUnknown_QueryInterface_Proto = ct.WINFUNCTYPE(HRESULT, wt.LPVOID, ct.POINTER(GUID), ct.POINTER(wt.LPVOID)) IUnknown_AddRef_Proto = ct.WINFUNCTYPE(HRESULT, wt.LPVOID) IUnknown_Release_Proto = ct.WINFUNCTYPE(HRESULT, wt.LPVOID) # virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0; # # virtual HRESULT STDMETHODCALLTYPE Next( # /* [in] */ long lTimeout, # /* [in] */ ULONG uCount, # /* [length_is][size_is][out] */ __RPC__out_ecount_part(uCount, *puReturned) IWbemClassObject **apObjects, # /* [out] */ __RPC__out ULONG *puReturned) = 0; # # virtual HRESULT STDMETHODCALLTYPE NextAsync(
def memhandle_as_ctypes_array_scaled(self, memhandle): return ctypes.cast(memhandle, ctypes.POINTER(ctypes.c_double))
if type(v) != int: continue if not v in alc_enums: alc_enums[v] = [] alc_enums[v].append(k) class ALCError(Exception): pass def alc_check_error(result, func, arguments): err = alcGetError(0) if err: raise ALCError(alc_enums[err][0]) return result alcCreateContext = lib.alcCreateContext alcCreateContext.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] alcCreateContext.restype = ctypes.c_void_p alcCreateContext.errcheck = alc_check_error alcMakeContextCurrent = lib.alcMakeContextCurrent alcMakeContextCurrent.argtypes = [ctypes.c_void_p] alcMakeContextCurrent.restype = ctypes.c_uint8 alcMakeContextCurrent.errcheck = alc_check_error alcProcessContext = lib.alcProcessContext alcProcessContext.argtypes = [ctypes.c_void_p] alcProcessContext.restype = None alcProcessContext.errcheck = alc_check_error alcSuspendContext = lib.alcSuspendContext alcSuspendContext.argtypes = [ctypes.c_void_p]
value = ffi_obj.string(value) output.append(value) return output def callback(library, signature_name, func): ffi_obj = _get_ffi(library) return ffi_obj.callback(signature_name, func) engine = 'cffi' else: import ctypes from ctypes import pointer, c_int, c_char_p, c_uint, c_void_p, c_wchar_p _pointer_int_types = int_types + (c_char_p, ctypes.POINTER(ctypes.c_byte)) _pointer_types = { 'void *': True, 'wchar_t *': True, 'char *': True, 'char **': True, } _type_map = { 'void *': c_void_p, 'wchar_t *': c_wchar_p, 'char *': c_char_p, 'char **': ctypes.POINTER(c_char_p), 'int': c_int, 'unsigned int': c_uint, 'size_t': ctypes.c_size_t,
def get_file_version_info(cls, filename): """ Get the program version from an executable file, if available. @type filename: str @param filename: Pathname to the executable file to query. @rtype: tuple(str, str, bool, bool, str, str) @return: Tuple with version information extracted from the executable file metadata, containing the following: - File version number (C{"major.minor"}). - Product version number (C{"major.minor"}). - C{True} for debug builds, C{False} for production builds. - C{True} for legacy OS builds (DOS, OS/2, Win16), C{False} for modern OS builds. - Binary file type. May be one of the following values: - "application" - "dynamic link library" - "static link library" - "font" - "raster font" - "TrueType font" - "vector font" - "driver" - "communications driver" - "display driver" - "installable driver" - "keyboard driver" - "language driver" - "legacy driver" - "mouse driver" - "network driver" - "printer driver" - "sound driver" - "system driver" - "versioned printer driver" - Binary creation timestamp. Any of the fields may be C{None} if not available. @raise WindowsError: Raises an exception on error. """ # Get the file version info structure. if type(filename) is str: pBlock = win32.GetFileVersionInfoA(filename) pBuffer, dwLen = win32.VerQueryValueA(pBlock, "\\") else: pBlock = win32.GetFileVersionInfoW(filename) pBuffer, dwLen = win32.VerQueryValueW(pBlock, u"\\") if dwLen != ctypes.sizeof(win32.VS_FIXEDFILEINFO): raise ctypes.WinError(win32.ERROR_BAD_LENGTH) pVersionInfo = ctypes.cast(pBuffer, ctypes.POINTER(win32.VS_FIXEDFILEINFO)) VersionInfo = pVersionInfo.contents if VersionInfo.dwSignature != 0xFEEF04BD: raise ctypes.WinError(win32.ERROR_BAD_ARGUMENTS) # File and product versions. FileVersion = "%d.%d" % (VersionInfo.dwFileVersionMS, VersionInfo.dwFileVersionLS) ProductVersion = "%d.%d" % (VersionInfo.dwProductVersionMS, VersionInfo.dwProductVersionLS) # Debug build? if VersionInfo.dwFileFlagsMask & win32.VS_FF_DEBUG: DebugBuild = (VersionInfo.dwFileFlags & win32.VS_FF_DEBUG) != 0 else: DebugBuild = None # Legacy OS build? LegacyBuild = (VersionInfo.dwFileOS != win32.VOS_NT_WINDOWS32) # File type. FileType = cls.__binary_types.get(VersionInfo.dwFileType) if VersionInfo.dwFileType == win32.VFT_DRV: FileType = cls.__driver_types.get(VersionInfo.dwFileSubtype) elif VersionInfo.dwFileType == win32.VFT_FONT: FileType = cls.__font_types.get(VersionInfo.dwFileSubtype) # Timestamp, ex: "Monday, July 7, 2013 (12:20:50.126)". # FIXME: how do we know the time zone? FileDate = (VersionInfo.dwFileDateMS << 32) + VersionInfo.dwFileDateLS if FileDate: CreationTime = win32.FileTimeToSystemTime(FileDate) CreationTimestamp = "%s, %s %d, %d (%d:%d:%d.%d)" % ( cls.__days_of_the_week[CreationTime.wDayOfWeek], cls.__months[CreationTime.wMonth], CreationTime.wDay, CreationTime.wYear, CreationTime.wHour, CreationTime.wMinute, CreationTime.wSecond, CreationTime.wMilliseconds, ) else: CreationTimestamp = None # Return the file version info. return ( FileVersion, ProductVersion, DebugBuild, LegacyBuild, FileType, CreationTimestamp, )
@struct class HARDWAREINPUT: uMsg: ctypes.wintypes.DWORD wParamL: ctypes.wintypes.WORD wParamH: ctypes.wintypes.WORD @struct class INPUT: @union class _INPUT: ki: KEYBDINPUT mi: MOUSEINPUT hi: HARDWAREINPUT _anonymous_ = ("_input", ) type: ctypes.wintypes.DWORD _input: _INPUT ctypes.wintypes.LPINPUT = ctypes.POINTER(INPUT) @struct class MODULEINFO: lpBaseOfDll: ctypes.wintypes.LPVOID SizeOfImage: ctypes.wintypes.DWORD EntryPoint: ctypes.wintypes.LPVOID
def load_dbghelp(cls, pathname=None): """ Load the specified version of the C{dbghelp.dll} library. This library is shipped with the Debugging Tools for Windows, and it's required to load debug symbols. If you don't specify the pathname, this method will try to find the location of the dbghelp.dll library despite Microsoft's efforts to keep us from using it, since they keep moving it around... This method can be useful for bundling dbghelp.dll in your scripts, so users won't need to have the Microsoft SDK installed. Example:: from winappdbg import Debug def simple_debugger( argv ): # Instance a Debug object, passing it the event handler callback debug = Debug( my_event_handler ) try: # Load a specific dbghelp.dll file debug.system.load_dbghelp("C:\\Custom install path\\dbghelp.dll") # Start a new process for debugging debug.execv( argv ) # Wait for the debugee to finish debug.loop() # Stop the debugger finally: debug.stop() @see: U{http://msdn.microsoft.com/en-us/library/ms679294(VS.85).aspx} @type pathname: str @param pathname: (Optional) Full pathname to the C{dbghelp.dll} library. If not provided this method will try to autodetect it. @rtype: ctypes.WinDLL @return: Loaded instance of C{dbghelp.dll}. @raise NotImplementedError: This feature was not implemented for the current architecture. @raise WindowsError: An error occured while processing this request. """ # If a pathname was given, just load the library and return. # Raise an exception on error. if pathname: dbghelp = ctypes.windll.LoadLibrary(pathname) # If no pathname was provided, we try to autodetect the install path for the SDK. else: # This is where we'll keep all the candidate libraries. # There may be more than one, so we'll sort out later which one to load. candidates = [] # The Microsoft SDK always seems to be installed in the "Program Files (x86)" folder on # Intel 64 bit machines, and "Program Files" on every other platform. sysdrive = getenv("SystemDrive", "C:") if win32.arch == win32.ARCH_AMD64: basedir = "%s\\Program Files (x86)" % sysdrive basedir = getenv("ProgramFiles(x86)", basedir) else: basedir = "%s\\Program Files" % sysdrive basedir = getenv("ProgramFiles", basedir) # Let's try the oldest known location for dbghelp.dll. # Oh, those were the days, when this was the same across all versions. candidates.append( ntpath.join(basedir, "Debugging Tools for Windows (x86)", "dbghelp.dll")) # Then the debugger got embedded into the SDK. This path is different for each version. # The format is different too. And they bundled 32 and 64 bits together. # Then on later versions there's also binaries for other, incompatible architectures too??? # I gave up on trying to make sense of it, let's just try all combinations to be safe. # (We only support x86 and x64 though. In the future we may have to update this.) # This StackOverflow answer helped me a lot: https://stackoverflow.com/a/24478856 if win32.bits == 32: candidates.extend( glob.glob( ntpath.join(basedir, "Windows Kits", "*", "Debuggers", "x86", "dbghelp.dll"))) else: candidates.extend( glob.glob( ntpath.join(basedir, "Windows Kits", "*", "Debuggers", "x64", "dbghelp.dll"))) if win32.bits == 32: candidates.extend( glob.glob( ntpath.join(basedir, "Microsoft SDKs", "Windows", "*", "Debuggers", "x86", "dbghelp.dll"))) else: candidates.extend( glob.glob( ntpath.join(basedir, "Microsoft SDKs", "Windows", "*", "Debuggers", "x64", "dbghelp.dll"))) if win32.bits == 32: candidates.extend( glob.glob( ntpath.join(basedir, "Microsoft", "Microsoft SDKs", "Windows", "*", "Debuggers", "x86", "dbghelp.dll"))) else: candidates.extend( glob.glob( ntpath.join(basedir, "Microsoft", "Microsoft SDKs", "Windows", "*", "Debuggers", "x64", "dbghelp.dll"))) # All of the above only works for the scenario where the SDK was installed globally. # But after who knows what version they also allow installing the SDK on a user's home. # So we need to check the Windows Registry for that. # ...unfortunately the registry keys are just as chaotic and inconsistent as the default paths. :( # TODO: I feel too tired and angry to implement this right now. Will do it later. Pinky promise. # Now that we have a list of potential locations for dbghelp.dll, let's check them out. # The idea here is 1) test if the file exists, 2) read the metadata, 3) pick the best one. # Sort the list and remove duplicates (there shouldn't be any, but why not, it's fast anyway). candidates = sorted(set(candidates)) # Discard any pathnames where the file cannot be found. candidates = [x for x in candidates if ntpath.exists(x)] # Get the metadata for each file found. Sort them by version, newer first. by_version = [] for pathname in candidates: pBlock = win32.GetFileVersionInfoA(pathname) pBuffer, dwLen = win32.VerQueryValueA(pBlock, "\\") if dwLen != ctypes.sizeof(win32.VS_FIXEDFILEINFO): #raise ctypes.WinError(win32.ERROR_BAD_LENGTH) continue pVersionInfo = ctypes.cast( pBuffer, ctypes.POINTER(win32.VS_FIXEDFILEINFO)) VersionInfo = pVersionInfo.contents if VersionInfo.dwSignature != 0xFEEF04BD: #raise ctypes.WinError(win32.ERROR_BAD_ARGUMENTS) continue FileVersion = (VersionInfo.dwFileVersionMS, VersionInfo.dwFileVersionLS) ProductVersion = (VersionInfo.dwProductVersionMS, VersionInfo.dwProductVersionLS) if FileVersion > ProductVersion: by_version.append((FileVersion, pathname)) else: by_version.append((ProductVersion, pathname)) by_version.sort() by_version = by_version[::-1] # Try loading them all, starting with the newer versions. # Stop once we got one to load successfully. dbghelp = None for _, pathname in by_version: try: dbghelp = ctypes.windll.LoadLibrary(pathname) break except Exception: continue # If we couldn't load the SDK library, try the system default one. # It's an outdated version generally, but still better than nothing. # Issue a warning to let the user know they should install the SDK. if dbghelp is None: pathname = ntpath.join(getenv("WINDIR", "C:\\WINDOWS"), "System32", "dbghelp.dll") try: dbghelp = ctypes.windll.LoadLibrary(pathname) except Exception: dbghelp = None # If no library could be loaded, fail with an exception. if dbghelp is None: msg = "Could not find a compatible dbghelp.dll in the system. Tried the following: %r" msg = msg % (candidates + [pathname], ) raise NotImplementedError(msg) # If we loaded the system default, issue a warning. warnings.warn( "Microsoft SDK not found, using the system default dbghelp.dll." ) # Set it globally as the library to be used. ctypes.windll.dbghelp = dbghelp # Return the library. return dbghelp
class Proxy(PyObject): _fields_ = [ ('dict', ctypes.POINTER(PyObject)), ]
def ptr(x): return x.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
for xtdir in ["/lib/xtables", "/usr/lib/xtables", "/usr/lib/iptables", "/usr/local/lib/xtables"]: if os.path.isdir(xtdir): _xtables_libdir = xtdir break if _xtables_libdir is None: raise XTablesError("can't find directory with extensions; " "please set XTABLES_LIBDIR") _lib_xtwrapper, _ = find_library("xtwrapper") _throw = _lib_xtwrapper.throw_exception _wrap_parse = _lib_xtwrapper.wrap_parse _wrap_parse.restype = ct.c_int _wrap_parse.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(ct.c_char_p), ct.c_int, ct.POINTER(ct.c_uint), ct.c_void_p, ct.POINTER(ct.c_void_p)] _wrap_save = _lib_xtwrapper.wrap_save _wrap_save.restype = ct.c_void_p _wrap_save.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_void_p] _wrap_uintfn = _lib_xtwrapper.wrap_uintfn _wrap_uintfn.restype = ct.c_int _wrap_uintfn.argtypes = [ct.c_void_p, ct.c_uint] _wrap_voidfn = _lib_xtwrapper.wrap_voidfn _wrap_voidfn.restype = ct.c_int _wrap_voidfn.argtypes = [ct.c_void_p]
# MPI Initialization comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() # Ctypes initialization #_IIRABM = ctypes.CDLL('/home/chase/iirabm_fullga/IIRABM_RuleGA.so') #_IIRABM = ctypes.CDLL('/users/r/c/rcockrel/iirabm_fullga/IIRABM_RuleGA.so') _IIRABM = ctypes.CDLL('/global/cscratch1/sd/cockrell/IIRABM_RuleGA.so') # (oxyHeal,infectSpread,numRecurInj,numInfectRepeat,inj_number,seed,numMatrixElements,internalParameterization) _IIRABM.mainSimulation.argtypes = (ctypes.c_float, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_float), ctypes.c_int) _IIRABM.mainSimulation.restype = ndpointer(dtype=ctypes.c_float, shape=(20, 5280)) numMatrixElements = 429 numStochasticReplicates = 50 array_type = ctypes.c_float * numMatrixElements selectedTimePoints = np.array([ 29, 59, 89, 119, 149, 179, 209, 239, 359, 479, 719, 1199, 1919, 3599, 5279 ]) numDataPoints = selectedTimePoints.shape[0] tnfMins = np.array([ 22.34, 20.74, 0, 0, 9.57, 1.6, 9.57, 0, 1.6, 0, 0, 0, 14.36, 19.15, 15.96 ])
class _xtables_match_v9(ct.Structure): _fields_ = [("version", ct.c_char_p), ("next", ct.c_void_p), ("name", ct.c_char_p), ("real_name", ct.c_char_p), ("revision", ct.c_uint8), ("family", ct.c_uint16), ("size", ct.c_size_t), ("userspacesize", ct.c_size_t), ("help", ct.CFUNCTYPE(None)), ("init", ct.CFUNCTYPE(None, ct.POINTER(xt_entry_match))), # fourth parameter entry is struct ipt_entry for example # int (*parse)(int c, char **argv, int invert, unsigned int # *flags, const void *entry, struct xt_entry_match **match) ("parse", ct.CFUNCTYPE(ct.c_int, ct.c_int, ct.POINTER(ct.c_char_p), ct.c_int, ct.POINTER(ct.c_uint), ct.c_void_p, ct.POINTER(ct.POINTER( xt_entry_match)))), ("final_check", ct.CFUNCTYPE(None, ct.c_uint)), # prints out the match iff non-NULL: put space at end # first parameter ip is struct ipt_ip * for example ("print", ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(xt_entry_match), ct.c_int)), # saves the match info in parsable form to stdout. # first parameter ip is struct ipt_ip * for example ("save", ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(xt_entry_match))), # pointer to list of extra command-line options ("extra_opts", ct.POINTER(option)), # introduced with the new iptables API ("x6_parse", ct.CFUNCTYPE(None, ct.POINTER(xt_option_call))), ("x6_fcheck", ct.CFUNCTYPE(None, ct.POINTER(xt_fcheck_call))), ("x6_options", ct.POINTER(xt_option_entry)), # size of per-extension instance extra "global" scratch space ("udata_size", ct.c_size_t), # ignore these men behind the curtain: ("udata", ct.c_void_p), ("option_offset", ct.c_uint), ("m", ct.POINTER(xt_entry_match)), ("mflags", ct.c_uint), ("loaded", ct.c_uint)]
class TIS_GrabberDLL(object): if sys.maxsize > 2**32: __tisgrabber = C.windll.LoadLibrary("tisgrabber_x64.dll") else: __tisgrabber = C.windll.LoadLibrary("tisgrabber.dll") def __init__(self, **keyargs): """Initialize the Albatross from the keyword arguments.""" self.__dict__.update(keyargs) GrabberHandlePtr = C.POINTER(GrabberHandle) #################################### # Initialize the ICImagingControl class library. This function must be called # only once before any other functions of this library are called. # @param szLicenseKey IC Imaging Control license key or NULL if only a trial version is available. # @retval IC_SUCCESS on success. # @retval IC_ERROR on wrong license key or other errors. # @sa IC_CloseLibrary InitLibrary = __tisgrabber.IC_InitLibrary(None) # Get the number of the currently available devices. This function creates an # internal array of all connected video capture devices. With each call to this # function, this array is rebuild. The name and the unique name can be retrieved # from the internal array using the functions IC_GetDevice() and IC_GetUniqueNamefromList. # They are usefull for retrieving device names for opening devices. # # @retval >= 0 Success, count of found devices. # @retval IC_NO_HANDLE Internal Error. # # @sa IC_GetDevice # @sa IC_GetUniqueNamefromList get_devicecount = __tisgrabber.IC_GetDeviceCount get_devicecount.restype = C.c_int get_devicecount.argtypes = None # Get unique device name of a device specified by iIndex. The unique device name # consist from the device name and its serial number. It allows to differ between # more then one device of the same type connected to the computer. The unique device name # is passed to the function IC_OpenDevByUniqueName # # @param iIndex The number of the device whose name is to be returned. It must be # in the range from 0 to IC_GetDeviceCount(), # @return Returns the string representation of the device on success, NULL # otherwise. # # @sa IC_GetDeviceCount # @sa IC_GetUniqueNamefromList # @sa IC_OpenDevByUniqueName get_unique_name_from_list = __tisgrabber.IC_GetUniqueNamefromList get_unique_name_from_list.restype = C.c_char_p get_unique_name_from_list.argtypes = (C.c_int, ) # Creates a new grabber handle and returns it. A new created grabber should be # release with a call to IC_ReleaseGrabber if it is no longer needed. # @sa IC_ReleaseGrabber create_grabber = __tisgrabber.IC_CreateGrabber create_grabber.restype = GrabberHandlePtr create_grabber.argtypes = None # Open a video capture by using its UniqueName. Use IC_GetUniqueName() to # retrieve the unique name of a camera. # # @param hGrabber Handle to a grabber object # @param szDisplayName Memory that will take the display name. # # @sa IC_GetUniqueName # @sa IC_ReleaseGrabber open_device_by_unique_name = __tisgrabber.IC_OpenDevByUniqueName open_device_by_unique_name.restype = C.c_int open_device_by_unique_name.argtypes = (GrabberHandlePtr, C.c_char_p) set_videoformat = __tisgrabber.IC_SetVideoFormat set_videoformat.restype = C.c_int set_videoformat.argtypes = (GrabberHandlePtr, C.c_char_p) set_framerate = __tisgrabber.IC_SetFrameRate set_framerate.restype = C.c_int set_framerate.argtypes = (GrabberHandlePtr, C.c_float) # Returns the width of the video format. get_video_format_width = __tisgrabber.IC_GetVideoFormatWidth get_video_format_width.restype = C.c_int get_video_format_width.argtypes = (GrabberHandlePtr, ) # returns the height of the video format. get_video_format_height = __tisgrabber.IC_GetVideoFormatHeight get_video_format_height.restype = C.c_int get_video_format_height.argtypes = (GrabberHandlePtr, ) # Get the number of the available video formats for the current device. # A video capture device must have been opened before this call. # # @param hGrabber The handle to the grabber object. # # @retval >= 0 Success # @retval IC_NO_DEVICE No video capture device selected. # @retval IC_NO_HANDLE No handle to the grabber object. # # @sa IC_GetVideoFormat GetVideoFormatCount = __tisgrabber.IC_GetVideoFormatCount GetVideoFormatCount.restype = C.c_int GetVideoFormatCount.argtypes = (GrabberHandlePtr, ) # Get a string representation of the video format specified by iIndex. # iIndex must be between 0 and IC_GetVideoFormatCount(). # IC_GetVideoFormatCount() must have been called before this function, # otherwise it will always fail. # # @param hGrabber The handle to the grabber object. # @param iIndex Number of the video format to be used. # # @retval Nonnull The name of the specified video format. # @retval NULL An error occured. # @sa IC_GetVideoFormatCount GetVideoFormat = __tisgrabber.IC_GetVideoFormat GetVideoFormat.restype = C.c_char_p GetVideoFormat.argtypes = (GrabberHandlePtr, C.c_int) # Get the number of the available input channels for the current device. # A video capture device must have been opened before this call. # # @param hGrabber The handle to the grabber object. # # @retval >= 0 Success # @retval IC_NO_DEVICE No video capture device selected. # @retval IC_NO_HANDLE No handle to the grabber object. # # @sa IC_GetInputChannel GetInputChannelCount = __tisgrabber.IC_GetInputChannelCount GetInputChannelCount.restype = C.c_int GetInputChannelCount.argtypes = (GrabberHandlePtr, ) # Get a string representation of the input channel specified by iIndex. # iIndex must be between 0 and IC_GetInputChannelCount(). # IC_GetInputChannelCount() must have been called before this function, # otherwise it will always fail. # @param hGrabber The handle to the grabber object. # @param iIndex Number of the input channel to be used.. # # @retval Nonnull The name of the specified input channel # @retval NULL An error occured. # @sa IC_GetInputChannelCount GetInputChannel = __tisgrabber.IC_GetInputChannel GetInputChannel.restype = C.c_char_p GetInputChannel.argtypes = (GrabberHandlePtr, C.c_int) # Get the number of the available video norms for the current device. # A video capture device must have been opened before this call. # # @param hGrabber The handle to the grabber object. # # @retval >= 0 Success # @retval IC_NO_DEVICE No video capture device selected. # @retval IC_NO_HANDLE No handle to the grabber object. # # @sa IC_GetVideoNorm GetVideoNormCount = __tisgrabber.IC_GetVideoNormCount GetVideoNormCount.restype = C.c_int GetVideoNormCount.argtypes = (GrabberHandlePtr, ) # Get a string representation of the video norm specified by iIndex. # iIndex must be between 0 and IC_GetVideoNormCount(). # IC_GetVideoNormCount() must have been called before this function, # otherwise it will always fail. # # @param hGrabber The handle to the grabber object. # @param iIndex Number of the video norm to be used. # # @retval Nonnull The name of the specified video norm. # @retval NULL An error occured. # @sa IC_GetVideoNormCount GetVideoNorm = __tisgrabber.IC_GetVideoNorm GetVideoNorm.restype = C.c_char_p GetVideoNorm.argtypes = (GrabberHandlePtr, C.c_int) SetFormat = __tisgrabber.IC_SetFormat SetFormat.restype = C.c_int SetFormat.argtypes = (GrabberHandlePtr, C.c_int) GetFormat = __tisgrabber.IC_GetFormat GetFormat.restype = C.c_int GetFormat.argtypes = (GrabberHandlePtr, ) # Start the live video. # @param hGrabber The handle to the grabber object. # @param iShow The parameter indicates: @li 1 : Show the video @li 0 : Do not show the video, but deliver frames. (For callbacks etc.) # @retval IC_SUCCESS on success # @retval IC_ERROR if something went wrong. # @sa IC_StopLive StartLive = __tisgrabber.IC_StartLive StartLive.restype = C.c_int StartLive.argtypes = (GrabberHandlePtr, C.c_int) StopLive = __tisgrabber.IC_StopLive StopLive.restype = C.c_int StopLive.argtypes = (GrabberHandlePtr, ) SetHWND = __tisgrabber.IC_SetHWnd SetHWND.restype = C.c_int SetHWND.argtypes = (GrabberHandlePtr, C.c_int) # Snaps an image. The video capture device must be set to live mode and a # sink type has to be set before this call. The format of the snapped images depend on # the selected sink type. # # @param hGrabber The handle to the grabber object. # @param iTimeOutMillisek The Timeout time is passed in milli seconds. A value of -1 indicates, that # no time out is set. # # # @retval IC_SUCCESS if an image has been snapped # @retval IC_ERROR if something went wrong. # @retval IC_NOT_IN_LIVEMODE if the live video has not been started. # # @sa IC_StartLive # @sa IC_SetFormat SnapImage = __tisgrabber.IC_SnapImage SnapImage.restype = C.c_int SnapImage.argtypes = (GrabberHandlePtr, C.c_int) # Retrieve the properties of the current video format and sink type # @param hGrabber The handle to the grabber object. # @param *lWidth This recieves the width of the image buffer. # @param *lHeight This recieves the height of the image buffer. # @param *iBitsPerPixel This recieves the count of bits per pixel. # @param *format This recieves the current color format. # @retval IC_SUCCESS on success # @retval IC_ERROR if something went wrong. GetImageDescription = __tisgrabber.IC_GetImageDescription GetImageDescription.restype = C.c_int GetImageDescription.argtypes = ( GrabberHandlePtr, C.POINTER(C.c_long), C.POINTER(C.c_long), C.POINTER(C.c_int), C.POINTER(C.c_int), ) GetImagePtr = __tisgrabber.IC_GetImagePtr GetImagePtr.restype = C.c_void_p GetImagePtr.argtypes = (GrabberHandlePtr, ) # ############################################################################ ShowDeviceSelectionDialog = __tisgrabber.IC_ShowDeviceSelectionDialog ShowDeviceSelectionDialog.restype = GrabberHandlePtr ShowDeviceSelectionDialog.argtypes = (GrabberHandlePtr, ) # ############################################################################ ShowPropertyDialog = __tisgrabber.IC_ShowPropertyDialog ShowPropertyDialog.restype = GrabberHandlePtr ShowPropertyDialog.argtypes = (GrabberHandlePtr, ) # ############################################################################ IsDevValid = __tisgrabber.IC_IsDevValid IsDevValid.restype = C.c_int IsDevValid.argtypes = (GrabberHandlePtr, ) # ############################################################################ LoadDeviceStateFromFile = __tisgrabber.IC_LoadDeviceStateFromFile LoadDeviceStateFromFile.restype = GrabberHandlePtr LoadDeviceStateFromFile.argtypes = (GrabberHandlePtr, C.c_char_p) # ############################################################################ SaveDeviceStateToFile = __tisgrabber.IC_SaveDeviceStateToFile SaveDeviceStateToFile.restype = C.c_int SaveDeviceStateToFile.argtypes = (GrabberHandlePtr, C.c_char_p) GetCameraProperty = __tisgrabber.IC_GetCameraProperty GetCameraProperty.restype = C.c_int GetCameraProperty.argtypes = (GrabberHandlePtr, C.c_int, C.POINTER(C.c_long)) SetCameraProperty = __tisgrabber.IC_SetCameraProperty SetCameraProperty.restype = C.c_int SetCameraProperty.argtypes = (GrabberHandlePtr, C.c_int, C.c_long) SetPropertyValue = __tisgrabber.IC_SetPropertyValue SetPropertyValue.restype = C.c_int SetPropertyValue.argtypes = (GrabberHandlePtr, C.c_char_p, C.c_char_p, C.c_int) GetPropertyValue = __tisgrabber.IC_GetPropertyValue GetPropertyValue.restype = C.c_int GetPropertyValue.argtypes = ( GrabberHandlePtr, C.c_char_p, C.c_char_p, C.POINTER(C.c_long), ) # ############################################################################ SetPropertySwitch = __tisgrabber.IC_SetPropertySwitch SetPropertySwitch.restype = C.c_int SetPropertySwitch.argtypes = (GrabberHandlePtr, C.c_char_p, C.c_char_p, C.c_int) GetPropertySwitch = __tisgrabber.IC_GetPropertySwitch GetPropertySwitch.restype = C.c_int GetPropertySwitch.argtypes = ( GrabberHandlePtr, C.c_char_p, C.c_char_p, C.POINTER(C.c_long), ) # ############################################################################ IsPropertyAvailable = __tisgrabber.IC_IsPropertyAvailable IsPropertyAvailable.restype = C.c_int IsPropertyAvailable.argtypes = (GrabberHandlePtr, C.c_char_p, C.c_char_p) PropertyOnePush = __tisgrabber.IC_PropertyOnePush PropertyOnePush.restype = C.c_int PropertyOnePush.argtypes = (GrabberHandlePtr, C.c_char_p, C.c_char_p) SetPropertyAbsoluteValue = __tisgrabber.IC_SetPropertyAbsoluteValue SetPropertyAbsoluteValue.restype = C.c_int SetPropertyAbsoluteValue.argtypes = ( GrabberHandlePtr, C.c_char_p, C.c_char_p, C.c_float, ) GetPropertyAbsoluteValue = __tisgrabber.IC_GetPropertyAbsoluteValue GetPropertyAbsoluteValue.restype = C.c_int GetPropertyAbsoluteValue.argtypes = ( GrabberHandlePtr, C.c_char_p, C.c_char_p, C.POINTER(C.c_float), ) # definition of the frameready callback FRAMEREADYCALLBACK = C.CFUNCTYPE(C.c_void_p, C.c_int, C.POINTER(C.c_ubyte), C.c_ulong, C.py_object) # set callback function SetFrameReadyCallback = __tisgrabber.IC_SetFrameReadyCallback SetFrameReadyCallback.restype = C.c_int SetFrameReadyCallback.argtypes = [ GrabberHandlePtr, FRAMEREADYCALLBACK, C.py_object ] SetContinuousMode = __tisgrabber.IC_SetContinuousMode SaveImage = __tisgrabber.IC_SaveImage SaveImage.restype = C.c_int SaveImage.argtypes = [C.c_void_p, C.c_char_p, C.c_int, C.c_int] OpenVideoCaptureDevice = __tisgrabber.IC_OpenVideoCaptureDevice OpenVideoCaptureDevice.restype = C.c_int OpenVideoCaptureDevice.argtypes = [C.c_void_p, C.c_char_p] # ############################################################################ ### GK Additions - adding frame filters. Pieces copied from: https://github.com/morefigs/py-ic-imaging-control CreateFrameFilter = __tisgrabber.IC_CreateFrameFilter CreateFrameFilter.restype = C.c_int CreateFrameFilter.argtypes = (C.c_char_p, C.POINTER(FrameFilterHandle)) AddFrameFilter = __tisgrabber.IC_AddFrameFilterToDevice AddFrameFilter.restype = C.c_int AddFrameFilter.argtypes = (GrabberHandlePtr, C.POINTER(FrameFilterHandle)) FilterGetParameter = __tisgrabber.IC_FrameFilterGetParameter FilterGetParameter.restype = C.c_int FilterGetParameter.argtypes = (C.POINTER(FrameFilterHandle), C.c_char_p, C.c_void_p) FilterSetParameter = __tisgrabber.IC_FrameFilterSetParameterInt FilterSetParameter.restype = C.c_int FilterSetParameter.argtypes = (C.POINTER(FrameFilterHandle), C.c_char_p, C.c_int)