Python ctypes 模块,Structure() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.Structure()

项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def enumerate_handles():
    size_needed = ULONG()
    size = 0x1000
    buffer = ctypes.c_buffer(size)

    try:
        winproxy.NtQuerySystemInformation(16, buffer, size, ReturnLength=ctypes.byref(size_needed))
    except WindowsError as e:
        pass

    size = size_needed.value + 0x1000
    buffer = ctypes.c_buffer(size)
    winproxy.NtQuerySystemInformation(16, buffer, size, ReturnLength=ctypes.byref(size_needed))
    x = SYSTEM_HANDLE_INFORMATION.from_buffer(buffer)
    class _GENERATED_SYSTEM_HANDLE_INFORMATION(ctypes.Structure):
        _fields_ = [
            ("HandleCount", ULONG),
            ("Handles", Handle * x.HandleCount),
        ]
    return list(_GENERATED_SYSTEM_HANDLE_INFORMATION.from_buffer_copy(buffer[:size_needed.value]).Handles)
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def _ram(self):
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong
        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ('dwLength', c_ulong),
                ('dwMemoryLoad', c_ulong),
                ('dwTotalPhys', c_ulong),
                ('dwAvailPhys', c_ulong),
                ('dwTotalPageFile', c_ulong),
                ('dwAvailPageFile', c_ulong),
                ('dwTotalVirtual', c_ulong),
                ('dwAvailVirtual', c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
        return (memoryStatus.dwTotalPhys, memoryStatus.dwAvailPhys)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __init__(self, *args):
        """
        The initialization function may take an OGREnvelope structure, 4-element
        tuple or list, or 4 individual arguments.
        """

        if len(args) == 1:
            if isinstance(args[0], OGREnvelope):
                # OGREnvelope (a ctypes Structure) was passed in.
                self._envelope = args[0]
            elif isinstance(args[0], (tuple, list)):
                # A tuple was passed in.
                if len(args[0]) != 4:
                    raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
                else:
                    self._from_sequence(args[0])
            else:
                raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
        elif len(args) == 4:
            # Individual parameters passed in.
            #  Thanks to ww for the help
            self._from_sequence([float(a) for a in args])
        else:
            raise GDALException('Incorrect number (%d) of arguments.' % len(args))

        # Checking the x,y coordinates
        if self.min_x > self.max_x:
            raise GDALException('Envelope minimum X > maximum X.')
        if self.min_y > self.max_y:
            raise GDALException('Envelope minimum Y > maximum Y.')
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def win32_version():
    import ctypes
    class OSVERSIONINFOEXW(ctypes.Structure):
        _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong),
                    ('dwMajorVersion', ctypes.c_ulong),
                    ('dwMinorVersion', ctypes.c_ulong),
                    ('dwBuildNumber', ctypes.c_ulong),
                    ('dwPlatformId', ctypes.c_ulong),
                    ('szCSDVersion', ctypes.c_wchar*128),
                    ('wServicePackMajor', ctypes.c_ushort),
                    ('wServicePackMinor', ctypes.c_ushort),
                    ('wSuiteMask', ctypes.c_ushort),
                    ('wProductType', ctypes.c_byte),
                    ('wReserved', ctypes.c_byte)]
    """
    Get's the OS major and minor versions.  Returns a tuple of
    (OS_MAJOR, OS_MINOR).
    """
    os_version = OSVERSIONINFOEXW()
    os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version)
    retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version))
    if retcode != 0:
        raise Exception("Failed to get OS version")

    return os_version.dwMajorVersion
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:pncpp    作者:amadxx    | 项目源码 | 文件源码
def __call__(self, *args):
        if not self.c_method:
            raise AttributeError("Method not resolved")

        nargs = list(args)
        for i, arg in enumerate(nargs):
            if issubclass(type(arg), CXXStruct):
                c_type = self.c_args[i]
                if issubclass(c_type, ctypes._Pointer):
                    nargs[i] = arg.this
                elif issubclass(c_type, ctypes.Structure):
                    nargs[i] = arg.struct
        if self.override:
            result = self.v_method(*nargs)
        else:
            result = self.c_method(*nargs)
        return result
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:PokeDuino    作者:tzwenn    | 项目源码 | 文件源码
def Pokearray(length):

    # okay, I learned. 
    # It's not possible to use a custom base class
    # in a ctypes.Structure field. Forget about it

    @classmethod
    def fromBytes(cls, data):
        return cls(*data)

    def asBytes(self):
        return bytes(iter(self))

    t = ctypes.c_uint8 * length
    t.fromBytes = fromBytes
    t.bytes = asBytes
    return t
项目:opc-rest-api    作者:matzpersson    | 项目源码 | 文件源码
def _mem_info():
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong
        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ('dwLength', c_ulong),
                ('dwMemoryLoad', c_ulong),
                ('dwTotalPhys', c_ulong),
                ('dwAvailPhys', c_ulong),
                ('dwTotalPageFile', c_ulong),
                ('dwAvailPageFile', c_ulong),
                ('dwTotalVirtual', c_ulong),
                ('dwAvailVirtual', c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
        return (memoryStatus.dwTotalPhys, memoryStatus.dwAvailPhys)
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:islam-buddy    作者:hamir    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:FightstickDisplay    作者:calexil    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:cryptogram    作者:xinmingzhang    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:kotori    作者:daq-tools    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        """
        Ctypes.Structure with integrated default values.
        https://stackoverflow.com/questions/7946519/default-values-in-a-ctypes-structure/25892189#25892189

        :param kwargs: values different to defaults
        :type kwargs: dict
        """

        # sanity checks
        defaults = type(self)._defaults_
        assert type(defaults) is types.DictionaryType

        # use defaults, but override with keyword arguments, if any
        values = defaults.copy()
        for (key, val) in kwargs.items():
            values[key] = val

        # appropriately initialize ctypes.Structure
        #super().__init__(**values)                     # Python 3 syntax
        return Structure.__init__(self, **values)       # Python 2 syntax

    # http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str/1827666#1827666
    # https://wiki.python.org/moin/ctypes
项目:UMOG    作者:hsab    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:pythonista-scripts    作者:khilnani    | 项目源码 | 文件源码
def __call__(self, *args, **kwargs):
        type_encoding = c.method_getTypeEncoding(self.method)
        type_parser = kwargs.get('type_parser', parse_types)
        restype, argtypes = type_parser(type_encoding)
        if restype and issubclass(restype, Structure) and not LP64:
            retval = restype()
            c.objc_msgSend_stret.argtypes = [c_void_p] + argtypes
            c.objc_msgSend_stret.restype = None
            c.objc_msgSend_stret(ctypes.byref(retval), self.obj.ptr, sel(self.sel_name), *args)
            return retval
        else:
            c.objc_msgSend.argtypes = argtypes
            c.objc_msgSend.restype = restype
            res = c.objc_msgSend(self.obj.ptr, sel(self.sel_name), *args)
            if res and type_encoding[0] == '@':
                if res == self.obj.ptr:
                    return self.obj
                # If an object is returned, wrap the pointer in an ObjCInstance:
                return ObjCInstance(res)
            return res

#Some commonly-used Foundation classes:
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:nimi-python    作者:ni    | 项目源码 | 文件源码
def __init__(self, data=None, absolute_initial_x=0.0, relative_initial_x=0.0,
                 x_increment=0.0, actual_samples=0, offset=0.0, gain=0.0,
                 reserved1=0.0, reserved2=0.0):
        super(ctypes.Structure, self).__init__()
        if data is not None:
            self.absolute_initial_x = data.absolute_initial_x
            self.relative_initial_x = data.relative_initial_x
            self.x_increment = data.x_increment
            self.actual_samples = data.actual_samples
            self.offset = data.offset
            self.gain = data.gain
            self.reserved1 = data.reserved1
            self.reserved2 = data.reserved2
        else:
            self.absolute_initial_x = absolute_initial_x
            self.relative_initial_x = relative_initial_x
            self.x_increment = x_increment
            self.actual_samples = actual_samples
            self.offset = offset
            self.gain = gain
            self.reserved1 = reserved1
            self.reserved2 = reserved2
项目:nimi-python    作者:ni    | 项目源码 | 文件源码
def __init__(self, data=None, absolute_initial_x=0.0, relative_initial_x=0.0,
                 x_increment=0.0, actual_samples=0, offset=0.0, gain=0.0,
                 reserved1=0.0, reserved2=0.0):
        super(ctypes.Structure, self).__init__()
        if data is not None:
            self.absolute_initial_x = data.absolute_initial_x
            self.relative_initial_x = data.relative_initial_x
            self.x_increment = data.x_increment
            self.actual_samples = data.actual_samples
            self.offset = data.offset
            self.gain = data.gain
            self.reserved1 = data.reserved1
            self.reserved2 = data.reserved2
        else:
            self.absolute_initial_x = absolute_initial_x
            self.relative_initial_x = relative_initial_x
            self.x_increment = x_increment
            self.actual_samples = actual_samples
            self.offset = offset
            self.gain = gain
            self.reserved1 = reserved1
            self.reserved2 = reserved2
项目:beepboop    作者:nicolehe    | 项目源码 | 文件源码
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE)
项目:pyUVVIS    作者:ddietze    | 项目源码 | 文件源码
def create_camera_list(dwCount):
    """Returns an instance of the UC480_CAMERA_LIST structure having the properly scaled UC480_CAMERA_INFO array.

    :param ULONG dwCount: Number of camera info structures requested.
    :returns: UC480_CAMERA_LIST

    :var ULONG dwCount: Size of uci.
    :var UC480_CAMERA_INFO[dwCount] uci: List of camera info structures.
    """
    class UC480_CAMERA_LIST(ctypes.Structure):
        _fields_ = [("dwCount", wt.ULONG),
                    ("uci", UC480_CAMERA_INFO * dwCount)]
    a_list = UC480_CAMERA_LIST()
    a_list.dwCount = dwCount
    return a_list

#  ----------------------------------------------------------------------------
#  the  following defines are the status bits of the dwStatus member of
#  the UC480_CAMERA_INFO structure
项目:pyUVVIS    作者:ddietze    | 项目源码 | 文件源码
def create_image_format_list(nNumListElements):
    """Returns an instance of the IMAGE_FORMAT_LIST structure having the properly scaled *FormatInfo* array.

    :param ULONG nNumListElements: Number of format info structures requested.
    :returns: IMAGE_FORMAT_LIST

    :var UINT nSizeOfListEntry:
    :var UINT nNumListElements:
    :var UINT[4] nReserved:
    :var IMAGE_FORMAT_INFO[nNumListElements] FormatInfo:
    """
    class IMAGE_FORMAT_LIST(ctypes.Structure):
        _fields_ = [("nSizeOfListEntry", wt.UINT),
                    ("nNumListElements", wt.UINT),
                    ("nReserved", wt.UINT * 4),
                    ("FormatInfo", IMAGE_FORMAT_INFO * nNumListElements)]
    a_list = IMAGE_FORMAT_LIST()
    a_list.nNumListElements = nNumListElements
    return a_list
项目:pyUVVIS    作者:ddietze    | 项目源码 | 文件源码
def create_fdt_info_list(nNumListElements):
    """Returns an instance of the FDT_INFO_LIST structure having the properly scaled *FaceEntry* array.

    :param ULONG nNumListElements: Number of face entry structures requested.
    :returns: FDT_INFO_LIST

    :var UINT nSizeOfListEntry:
    :var UINT nNumDetectedFaces:
    :var UINT nNumListElements:
    :var UINT[4] nReserved:
    :var FDT_INFO_EL[nNumListElements] FaceEntry:
    """
    class FDT_INFO_LIST(ctypes.Structure):
        _fields_ = [("nSizeOfListEntry", wt.UINT),
                    ("nNumDetectedFaces", wt.UINT),
                    ("nNumListElements", wt.UINT),
                    ("nReserved", wt.UINT * 4),
                    ("FaceEntry", FDT_INFO_EL * nNumListElements)]
    a_list = FDT_INFO_LIST()
    a_list.nNumListElements = nNumListElements
    return a_list
项目:Proxy-Factory    作者:ping99    | 项目源码 | 文件源码
def remove_ca(self, name):
        import ctypes
        import ctypes.wintypes
        class CERT_CONTEXT(ctypes.Structure):
            _fields_ = [
                ('dwCertEncodingType', ctypes.wintypes.DWORD),
                ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
                ('cbCertEncoded', ctypes.wintypes.DWORD),
                ('pCertInfo', ctypes.c_void_p),
                ('hCertStore', ctypes.c_void_p),]
        crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
        store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
        pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
        while pCertCtx:
            certCtx = CERT_CONTEXT.from_address(pCertCtx)
            certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
            cert =  OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata)
            if hasattr(cert, 'get_subject'):
                cert = cert.get_subject()
            cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
            if cert_name and name.lower() == cert_name.split()[0].lower():
                crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
            pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
        return 0
项目:Proxy-Factory    作者:ping99    | 项目源码 | 文件源码
def remove_ca(self, name):
        import ctypes
        import ctypes.wintypes
        class CERT_CONTEXT(ctypes.Structure):
            _fields_ = [
                ('dwCertEncodingType', ctypes.wintypes.DWORD),
                ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
                ('cbCertEncoded', ctypes.wintypes.DWORD),
                ('pCertInfo', ctypes.c_void_p),
                ('hCertStore', ctypes.c_void_p),]
        crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
        store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
        pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
        while pCertCtx:
            certCtx = CERT_CONTEXT.from_address(pCertCtx)
            certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
            cert =  OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata)
            if hasattr(cert, 'get_subject'):
                cert = cert.get_subject()
            cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
            if cert_name and name.lower() == cert_name.split()[0].lower():
                crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
            pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
        return 0
项目:GotoX    作者:SeaHOH    | 项目源码 | 文件源码
def remove_cert(name):
    if os.name == 'nt':
        import ctypes, ctypes.wintypes
        class CERT_CONTEXT(ctypes.Structure):
            _fields_ = [
                ('dwCertEncodingType', ctypes.wintypes.DWORD),
                ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
                ('cbCertEncoded', ctypes.wintypes.DWORD),
                ('pCertInfo', ctypes.c_void_p),
                ('hCertStore', ctypes.c_void_p),]
        crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
        store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
        pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
        while pCertCtx:
            certCtx = CERT_CONTEXT.from_address(pCertCtx)
            certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
            cert =  crypto.load_certificate(crypto.FILETYPE_ASN1, certdata)
            if hasattr(cert, 'get_subject'):
                cert = cert.get_subject()
            cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
            if cert_name and name == cert_name:
                crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
            pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
        return 0
    return -1
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def new_struct_type(self, name):
        return self._new_struct_or_union('struct', name, ctypes.Structure)
项目:gps_track_pod    作者:iwanders    | 项目源码 | 文件源码
def __iter__(self):
        for k, t in self._fields_:
            if (issubclass(t, ctypes.Structure)):
                if (hasattr(self, "_anonymous_") and (k in self._anonymous_)):
                    # have to iterate through it here.
                    for kk, tt, in dict(getattr(self, k)).items():
                        yield (kk, tt)
                else:
                    yield (k, dict(getattr(self, k)))
            else:
                yield (k, getattr(self, k))

    # Implement the reverse method, with some special handling for dict's and
    # lists.
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def get_MIB_TCPTABLE_OWNER_PID_from_buffer(buffer):
    x = windows.generated_def.winstructs.MIB_TCPTABLE_OWNER_PID.from_buffer(buffer)
    nb_entry = x.dwNumEntries

    class _GENERATED_MIB_TCPTABLE_OWNER_PID(ctypes.Structure):
            _fields_ = [
                ("dwNumEntries", DWORD),
                ("table", TCP4Connection * nb_entry),
            ]

    return _GENERATED_MIB_TCPTABLE_OWNER_PID.from_buffer(buffer)
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def get_MIB_TCP6TABLE_OWNER_PID_from_buffer(buffer):
    x = windows.generated_def.winstructs.MIB_TCP6TABLE_OWNER_PID.from_buffer(buffer)
    nb_entry = x.dwNumEntries

    # Struct _MIB_TCP6TABLE_OWNER_PID definitions
    class _GENERATED_MIB_TCP6TABLE_OWNER_PID(Structure):
            _fields_ = [
                ("dwNumEntries", DWORD),
                ("table", TCP6Connection * nb_entry),
            ]

    return _GENERATED_MIB_TCP6TABLE_OWNER_PID.from_buffer(buffer)
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def query_working_set(self):
        if self.bitness == 64 or windows.current_process.bitness == 64:
            WSET_BLOCK = EPSAPI_WORKING_SET_BLOCK64
            dummy = PSAPI_WORKING_SET_INFORMATION64()
        else:
            WSET_BLOCK = EPSAPI_WORKING_SET_BLOCK32
            dummy = PSAPI_WORKING_SET_INFORMATION32()
        try:
            windows.winproxy.QueryWorkingSet(self.handle, ctypes.byref(dummy), ctypes.sizeof(dummy))
        except WindowsError as e:
            if e.winerror != 24:
                raise

        NumberOfEntriesType = [f for f in WSET_BLOCK._fields_ if f[0] == "Flags"][0][1]
        for i in range(10):
            # use the same type as WSET_BLOCK.Flags
            class GENERATED_PSAPI_WORKING_SET_INFORMATION(ctypes.Structure):
                _fields_ = [
                ("NumberOfEntries", NumberOfEntriesType),
                ("WorkingSetInfo", WSET_BLOCK * dummy.NumberOfEntries),
            ]
            res = GENERATED_PSAPI_WORKING_SET_INFORMATION()
            try:
                if windows.current_process.bitness == 32 and self.bitness == 64:
                    windows.syswow64.NtQueryVirtualMemory_32_to_64(self.handle, 0, MemoryWorkingSetList, res)
                else:
                    windows.winproxy.QueryWorkingSet(self.handle, ctypes.byref(res), ctypes.sizeof(res))
            except WindowsError as e:
                if e.winerror != 24:
                    raise
                dummy.NumberOfEntries = res.NumberOfEntries
                continue
            except windows.generated_def.ntstatus.NtStatusException as e:
                if e.code != STATUS_INFO_LENGTH_MISMATCH:
                    raise
                dummy.NumberOfEntries = res.NumberOfEntries
                continue
            return res.WorkingSetInfo
        # Raise ?
        return None
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def NtQueryVirtualMemory_32_to_64(ProcessHandle, BaseAddress, MemoryInformationClass, MemoryInformation=NeededParameter, MemoryInformationLength=0, ReturnLength=None):
    if ReturnLength is None:
        ReturnLength = byref(ULONG())
    if MemoryInformation is not None and MemoryInformationLength == 0:
        MemoryInformationLength = ctypes.sizeof(MemoryInformation)
    if isinstance(MemoryInformation, ctypes.Structure):
        MemoryInformation = byref(MemoryInformation)
    return NtQueryVirtualMemory_32_to_64.ctypes_function(ProcessHandle, BaseAddress, MemoryInformationClass, MemoryInformation, MemoryInformationLength, ReturnLength)
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def is_union_type(x):
    return issubclass(x, ctypes.Union)

# ### My types ### #

# # 64bits pointer types # #

# I know direct inheritance from _SimpleCData seems bad
# But it seems to be the only way to have the normal
# ctypes.Structure way of working (need to investigate)
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def create_remote_array(subtype, len):

    class RemoteArray(_ctypes.Array):
        _length_ = len
        _type_ = subtype

        def __init__(self, addr, target):
            self._base_addr = addr
            self.target = target

        def __getitem__(self, slice):
            # import pdb;pdb.set_trace()
            if not isinstance(slice, (int, long)):
                raise NotImplementedError("RemoteArray slice __getitem__")
            if slice >= len:
                raise IndexError("Access to {0} for a RemoteArray of size {1}".format(slice, len))
            item_addr = self._base_addr + (ctypes.sizeof(subtype) * slice)

            # TODO: do better ?
            class TST(ctypes.Structure):
                _fields_ = [("TST", subtype)]
            return RemoteStructure.from_structure(TST)(item_addr, target=self.target).TST

        def __getslice__(self, start, stop): # Still used even for python 2.7 wtf :F
            stop = min(stop, len)
            start = max(start, 0)
            # dummy implementation
            return [self[i] for i in range(start, stop)]

    return RemoteArray


# 64bits pointers
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def _handle_field_getattr(self, ftype, fosset, fsize):
        s = self._target.read_memory(self._base_addr + fosset, fsize)
        if ftype in self._field_type_to_remote_type:
            return self._field_type_to_remote_type[ftype].from_buffer_with_target(bytearray(s), target=self._target).value
        if issubclass(ftype, _ctypes._Pointer):  # Pointer
            return RemoteStructurePointer.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemotePtr64):  # Pointer to remote64 bits process
            return RemoteStructurePointer64.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemotePtr32):  # Pointer to remote32 bits process
            return RemoteStructurePointer32.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemoteStructureUnion):  # Structure|Union already transfomed in remote
            return ftype(self._base_addr + fosset, self._target)
        if issubclass(ftype, ctypes.Structure):  # Structure that must be transfomed
            return RemoteStructure.from_structure(ftype)(self._base_addr + fosset, self._target)
        if issubclass(ftype, ctypes.Union):  # Union that must be transfomed
            return RemoteUnion.from_structure(ftype)(self._base_addr + fosset, self._target)
        if issubclass(ftype, _ctypes.Array):  # Arrays
            # if this is a string: just cast the read value to string
            if ftype._type_ == ctypes.c_char: # Use issubclass instead ?
                return s.split("\x00", 1)[0]
            elif ftype._type_ == ctypes.c_wchar: # Use issubclass instead ?
                # Decode from utf16 -> size /=2 | put it in a wchar array | split at the first "\x00"
                return (ftype._type_ * (fsize / 2)).from_buffer_copy(s.decode('utf16'))[:].split("\x00", 1)[0] # Sorry..
            # I am pretty sur something smarter is possible..
            return create_remote_array(ftype._type_, ftype._length_)(self._base_addr + fosset, self._target)
        # Normal types
        # Follow the ctypes usage: if it's not directly inherited from _SimpleCData
        # We do not apply the .value
        # Seems weird but it's mandatory AND useful :D (in pe_parse)
        if _SimpleCData not in ftype.__bases__:
            return ftype.from_buffer(bytearray(s))
        return ftype.from_buffer(bytearray(s)).value
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def _create_vtable(self, interface):
        implems = []
        names = []
        for index, name, method in self.extract_methods_order(interface):
            func_implem = getattr(self, name)
            #PVOID is 'this'
            types = [method.restype, PVOID] + list(method.argtypes)
            implems.append(ctypes.WINFUNCTYPE(*types)(func_implem))
            names.append(name)
        class Vtable(ctypes.Structure):
            _fields_ = [(name, ctypes.c_void_p) for name in names]
        return Vtable(*[ctypes.cast(x, ctypes.c_void_p) for x in implems]), implems
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __init__(self, *args):
        """
        The initialization function may take an OGREnvelope structure, 4-element
        tuple or list, or 4 individual arguments.
        """

        if len(args) == 1:
            if isinstance(args[0], OGREnvelope):
                # OGREnvelope (a ctypes Structure) was passed in.
                self._envelope = args[0]
            elif isinstance(args[0], (tuple, list)):
                # A tuple was passed in.
                if len(args[0]) != 4:
                    raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
                else:
                    self._from_sequence(args[0])
            else:
                raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
        elif len(args) == 4:
            # Individual parameters passed in.
            #  Thanks to ww for the help
            self._from_sequence([float(a) for a in args])
        else:
            raise GDALException('Incorrect number (%d) of arguments.' % len(args))

        # Checking the x,y coordinates
        if self.min_x > self.max_x:
            raise GDALException('Envelope minimum X > maximum X.')
        if self.min_y > self.max_y:
            raise GDALException('Envelope minimum Y > maximum Y.')
项目:spread-knowledge-repository    作者:danieldev13    | 项目源码 | 文件源码
def __init__(self, uuidstr):
            uuid = UUID(uuidstr)
            ctypes.Structure.__init__(self)
            self.Data1, self.Data2, self.Data3, \
                self.Data4[0], self.Data4[1], rest = uuid.fields
            for i in range(2, 8):
                self.Data4[i] = rest>>(8-i-1)*8 & 0xff
项目:SwiftKitten    作者:johncsnyder    | 项目源码 | 文件源码
def new_struct_type(self, name):
        return self._new_struct_or_union('struct', name, ctypes.Structure)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def __init__(self, *args):
        """
        The initialization function may take an OGREnvelope structure, 4-element
        tuple or list, or 4 individual arguments.
        """

        if len(args) == 1:
            if isinstance(args[0], OGREnvelope):
                # OGREnvelope (a ctypes Structure) was passed in.
                self._envelope = args[0]
            elif isinstance(args[0], (tuple, list)):
                # A tuple was passed in.
                if len(args[0]) != 4:
                    raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
                else:
                    self._from_sequence(args[0])
            else:
                raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
        elif len(args) == 4:
            # Individual parameters passed in.
            #  Thanks to ww for the help
            self._from_sequence([float(a) for a in args])
        else:
            raise GDALException('Incorrect number (%d) of arguments.' % len(args))

        # Checking the x,y coordinates
        if self.min_x > self.max_x:
            raise GDALException('Envelope minimum X > maximum X.')
        if self.min_y > self.max_y:
            raise GDALException('Envelope minimum Y > maximum Y.')
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def __init__(self):
        ctypes.Structure.__init__(self)
        self.width = 0
        self.height = 0
        self.red_bits = 0
        self.green_bits = 0
        self.blue_bits = 0
        self.refresh_rate = 0
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def __init__(self):
        ctypes.Structure.__init__(self)
        self.red = None
        self.red_array = None
        self.green = None
        self.green_array = None
        self.blue = None
        self.blue_array = None
        self.size = 0
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def new_struct_type(self, name):
        return self._new_struct_or_union('struct', name, ctypes.Structure)
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def __init__(self, *args):
        """
        The initialization function may take an OGREnvelope structure, 4-element
        tuple or list, or 4 individual arguments.
        """

        if len(args) == 1:
            if isinstance(args[0], OGREnvelope):
                # OGREnvelope (a ctypes Structure) was passed in.
                self._envelope = args[0]
            elif isinstance(args[0], (tuple, list)):
                # A tuple was passed in.
                if len(args[0]) != 4:
                    raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
                else:
                    self._from_sequence(args[0])
            else:
                raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
        elif len(args) == 4:
            # Individual parameters passed in.
            #  Thanks to ww for the help
            self._from_sequence([float(a) for a in args])
        else:
            raise GDALException('Incorrect number (%d) of arguments.' % len(args))

        # Checking the x,y coordinates
        if self.min_x > self.max_x:
            raise GDALException('Envelope minimum X > maximum X.')
        if self.min_y > self.max_y:
            raise GDALException('Envelope minimum Y > maximum Y.')
项目:coolplots    作者:mpvismer    | 项目源码 | 文件源码
def makeDataObject(num):
    """
    Creates the ctypes data object used by both processes - defines the layout
    of the shared memory.
    """
    class DataBlock(ctypes.Structure):
            _fields_ = [("y", ctypes.c_float*(num*3)),
                        ("y10", ctypes.c_float*(num//10*3)),
                        ("y100", ctypes.c_float*(num//100*3)),
                        ("endpoint", ctypes.c_ssize_t),
                        ("startpoint", ctypes.c_ssize_t),
                        ("pltcurrent", ctypes.c_ssize_t)]
    return num
项目:Comictagger    作者:dickloraine    | 项目源码 | 文件源码
def __init__(self, ArcName=None, ArcNameW=u'', OpenMode=RAR_OM_LIST):
        self.CmtBuf = ctypes.c_buffer(64*1024)
        ctypes.Structure.__init__(self, ArcName=ArcName, ArcNameW=ArcNameW, OpenMode=OpenMode, _CmtBuf=ctypes.addressof(self.CmtBuf), CmtBufSize=ctypes.sizeof(self.CmtBuf))
项目:Comictagger    作者:dickloraine    | 项目源码 | 文件源码
def __init__(self):
        self.CmtBuf = ctypes.c_buffer(64*1024)
        ctypes.Structure.__init__(self, _CmtBuf=ctypes.addressof(self.CmtBuf), CmtBufSize=ctypes.sizeof(self.CmtBuf))
项目:git_intgrtn_aws_s3    作者:droidlabour    | 项目源码 | 文件源码
def new_struct_type(self, name):
        return self._new_struct_or_union('struct', name, ctypes.Structure)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def import_windows_ca(common_name, certfile):
        import ctypes
        with open(certfile, 'rb') as fp:
            certdata = fp.read()
            if certdata.startswith(b'-----'):
                begin = b'-----BEGIN CERTIFICATE-----'
                end = b'-----END CERTIFICATE-----'
                certdata = base64.b64decode(b''.join(certdata[certdata.find(begin)+len(begin):certdata.find(end)].strip().splitlines()))
            crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
            store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
            if not store_handle:
                return False
            CERT_FIND_SUBJECT_STR = 0x00080007
            CERT_FIND_HASH = 0x10000
            X509_ASN_ENCODING = 0x00000001
            class CRYPT_HASH_BLOB(ctypes.Structure):
                _fields_ = [('cbData', ctypes.c_ulong), ('pbData', ctypes.c_char_p)]
            assert CertUtil.ca_thumbprint
            crypt_hash = CRYPT_HASH_BLOB(20, binascii.a2b_hex(CertUtil.ca_thumbprint.replace(':', '')))
            crypt_handle = crypt32.CertFindCertificateInStore(store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH, ctypes.byref(crypt_hash), None)
            if crypt_handle:
                crypt32.CertFreeCertificateContext(crypt_handle)
                return True

            ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
            crypt32.CertCloseStore(store_handle, 0)
            del crypt32


            if not ret and __name__ != "__main__":
                #res = CertUtil.win32_notify(msg=u'Import PHP_proxy Ca?', title=u'Authority need')
                #if res == 2:
                #    return -1

                import win32elevate
                win32elevate.elevateAdminRun(os.path.abspath(__file__))
                return True

            return True if ret else False