コード例 #1
0
ファイル: test_windows.py プロジェクト: zion302/colorclass
def test_init_kernel32_unique():
    """Make sure function doesn't override other LibraryLoaders."""
    k32_a = ctypes.LibraryLoader(ctypes.WinDLL).kernel32
    k32_a.GetStdHandle.argtypes = [ctypes.c_void_p]
    k32_a.GetStdHandle.restype = ctypes.c_ulong

    k32_b, stderr_b, stdout_b = windows.init_kernel32()

    k32_c = ctypes.LibraryLoader(ctypes.WinDLL).kernel32
    k32_c.GetStdHandle.argtypes = [ctypes.c_long]
    k32_c.GetStdHandle.restype = ctypes.c_short

    k32_d, stderr_d, stdout_d = windows.init_kernel32()

    # Verify external.
    assert k32_a.GetStdHandle.argtypes == [ctypes.c_void_p]
    assert k32_a.GetStdHandle.restype == ctypes.c_ulong
    assert k32_c.GetStdHandle.argtypes == [ctypes.c_long]
    assert k32_c.GetStdHandle.restype == ctypes.c_short

    # Verify ours.
    assert k32_b.GetStdHandle.argtypes == [ctypes.c_ulong]
    assert k32_b.GetStdHandle.restype == ctypes.c_void_p
    assert k32_d.GetStdHandle.argtypes == [ctypes.c_ulong]
    assert k32_d.GetStdHandle.restype == ctypes.c_void_p
    assert stderr_b == stderr_d
    assert stdout_b == stdout_d
コード例 #2
0
ファイル: vterm.py プロジェクト: 8pockets/dotfiles
 def __init__(self, lib, **kwargs):
     self.lib = lib
     library_loader = ctypes.LibraryLoader(ctypes.CDLL)
     library = library_loader.LoadLibrary(lib)
     self.library = library
     for name, args in kwargs.items():
         self.__dict__[name] = CTypesFunction(library, name, *args)
コード例 #3
0
ファイル: _compat.py プロジェクト: NicoPy/myhdl_bck
    def set_inheritable(fd, inheritable):
        # This implementation of set_inheritable is based on a code sample in
        # [PEP 0446](https://www.python.org/dev/peps/pep-0446/) and on the
        # CPython implementation of that proposal which can be browsed [here]
        # (hg.python.org/releasing/3.4/file/8671f89107c8/Modules/posixmodule.c#l11130)
        if sys.platform == "win32":
            import msvcrt
            #             import ctypes.windll.kernel32 as kernel32
            import ctypes
            windll = ctypes.LibraryLoader(ctypes.WinDLL)
            SetHandleInformation = windll.kernel32.SetHandleInformation

            HANDLE_FLAG_INHERIT = 1

            if SetHandleInformation(msvcrt.get_osfhandle(fd),
                                    HANDLE_FLAG_INHERIT,
                                    1 if inheritable else 0) == 0:
                raise IOError("Failed on HANDLE_FLAG_INHERIT")
        else:
            import fcntl

            fd_flags = fcntl.fcntl(fd, fcntl.F_GETFD)

            if inheritable:
                fd_flags &= ~fcntl.FD_CLOEXEC
            else:
                fd_flags |= fcntl.FD_CLOEXEC

            fcntl.fcntl(fd, fcntl.F_SETFD, fd_flags)
コード例 #4
0
    def __init__(self, path: str, dll_type=AnyDll):
        """
        Initialize a new dll handle for path.
        No type hints are created for its functions,
        if you want to create some, you shall use DllImport.
        """

        x = ctypes.LibraryLoader(dll_type)
        self._lib = x.LoadLibrary(path)
        self._path = path

        super().__init__("_lib")
コード例 #5
0
    def __init__(self, command, maximized=False, title=None):
        """Constructor.

        :param iter command: Command to run.
        :param bool maximized: Start process in new console window, maximized.
        :param bytes title: Set new window title to this. Needed by user32.FindWindow.
        """
        if title is None:
            title = 'pytest-{0}-{1}'.format(os.getpid(), random.randint(1000, 9999)).encode('ascii')
        self.startup_info = StartupInfo(maximize=maximized, title=title)
        self.process_info = ProcessInfo()
        self.command_str = subprocess.list2cmdline(command).encode('ascii')
        self._handles = list()
        self._kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32
        self._kernel32.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]
        self._kernel32.GetExitCodeProcess.restype = ctypes.c_long
コード例 #6
0
ファイル: windows.py プロジェクト: xti9er/oletools
def init_kernel32(kernel32=None):
    """Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles.

    1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of
       kernel32 to prevent overriding (or being overwritten by) user's own changes to ctypes.windll.kernel32.
    2. While we're doing all this we might as well get the handles to STDOUT and STDERR streams.
    3. If either stream has already been replaced set return value to INVALID_HANDLE_VALUE to indicate it shouldn't be
       replaced.

    :raise AttributeError: When called on a non-Windows platform.

    :param kernel32: Optional mock kernel32 object. For testing.

    :return: Loaded kernel32 instance, stderr handle (int), stdout handle (int).
    :rtype: tuple
    """
    if not kernel32:
        kernel32 = ctypes.LibraryLoader(
            ctypes.WinDLL
        ).kernel32  # Load our own instance. Unique memory address.
        kernel32.GetStdHandle.argtypes = [ctypes.c_ulong]
        kernel32.GetStdHandle.restype = ctypes.c_void_p
        kernel32.GetConsoleScreenBufferInfo.argtypes = [
            ctypes.c_void_p,
            ctypes.POINTER(ConsoleScreenBufferInfo),
        ]
        kernel32.GetConsoleScreenBufferInfo.restype = ctypes.c_long

    # Get handles.
    if hasattr(sys.stderr, '_original_stream'):
        stderr = INVALID_HANDLE_VALUE
    else:
        stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
    if hasattr(sys.stdout, '_original_stream'):
        stdout = INVALID_HANDLE_VALUE
    else:
        stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

    return kernel32, stderr, stdout
コード例 #7
0
class _WindowsCSBI(object):
    """Interfaces with Windows CONSOLE_SCREEN_BUFFER_INFO API/DLL calls. Gets info for stderr and stdout.

    References:
        https://code.google.com/p/colorama/issues/detail?id=47.
        pytest's py project: py/_io/terminalwriter.py.

    Class variables:
    CSBI -- ConsoleScreenBufferInfo class/struct (not instance, the class definition itself) defined in _define_csbi().
    HANDLE_STDERR -- GetStdHandle() return integer for stderr.
    HANDLE_STDOUT -- GetStdHandle() return integer for stdout.
    WINDLL -- my own loaded instance of ctypes.WinDLL.
    """

    CSBI = None
    HANDLE_STDERR = None
    HANDLE_STDOUT = None
    WINDLL = ctypes.LibraryLoader(getattr(ctypes, 'WinDLL', None))

    @staticmethod
    def _define_csbi():
        """Defines structs and populates _WindowsCSBI.CSBI."""
        if _WindowsCSBI.CSBI is not None:
            return

        class COORD(ctypes.Structure):
            """Windows COORD structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682119"""
            _fields_ = [('X', ctypes.c_short), ('Y', ctypes.c_short)]

        class SmallRECT(ctypes.Structure):
            """Windows SMALL_RECT structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms686311"""
            _fields_ = [('Left', ctypes.c_short), ('Top', ctypes.c_short),
                        ('Right', ctypes.c_short), ('Bottom', ctypes.c_short)]

        class ConsoleScreenBufferInfo(ctypes.Structure):
            """Windows CONSOLE_SCREEN_BUFFER_INFO structure.
            http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093
            """
            _fields_ = [('dwSize', COORD), ('dwCursorPosition', COORD),
                        ('wAttributes', ctypes.wintypes.WORD),
                        ('srWindow', SmallRECT),
                        ('dwMaximumWindowSize', COORD)]

        _WindowsCSBI.CSBI = ConsoleScreenBufferInfo

    @staticmethod
    def initialize():
        """Initializes the WINDLL resource and populated the CSBI class variable."""
        _WindowsCSBI._define_csbi()
        _WindowsCSBI.HANDLE_STDERR = _WindowsCSBI.HANDLE_STDERR or _WindowsCSBI.WINDLL.kernel32.GetStdHandle(
            -12)
        _WindowsCSBI.HANDLE_STDOUT = _WindowsCSBI.HANDLE_STDOUT or _WindowsCSBI.WINDLL.kernel32.GetStdHandle(
            -11)
        if _WindowsCSBI.WINDLL.kernel32.GetConsoleScreenBufferInfo.argtypes:
            return

        _WindowsCSBI.WINDLL.kernel32.GetStdHandle.argtypes = [
            ctypes.wintypes.DWORD
        ]
        _WindowsCSBI.WINDLL.kernel32.GetStdHandle.restype = ctypes.wintypes.HANDLE
        _WindowsCSBI.WINDLL.kernel32.GetConsoleScreenBufferInfo.restype = ctypes.wintypes.BOOL
        _WindowsCSBI.WINDLL.kernel32.GetConsoleScreenBufferInfo.argtypes = [
            ctypes.wintypes.HANDLE,
            ctypes.POINTER(_WindowsCSBI.CSBI)
        ]

    @staticmethod
    def get_info(handle):
        """Get information about this current console window (for Microsoft Windows only).

        Raises IOError if attempt to get information fails (if there is no console window).

        Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.

        Positional arguments:
        handle -- either _WindowsCSBI.HANDLE_STDERR or _WindowsCSBI.HANDLE_STDOUT.

        Returns:
        Dictionary with different integer values. Keys are:
            buffer_width -- width of the buffer (Screen Buffer Size in cmd.exe layout tab).
            buffer_height -- height of the buffer (Screen Buffer Size in cmd.exe layout tab).
            terminal_width -- width of the terminal window.
            terminal_height -- height of the terminal window.
            bg_color -- current background color (http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088).
            fg_color -- current text color code.
        """
        # Query Win32 API.
        csbi = _WindowsCSBI.CSBI()
        try:
            if not _WindowsCSBI.WINDLL.kernel32.GetConsoleScreenBufferInfo(
                    handle, ctypes.byref(csbi)):
                raise IOError(
                    'Unable to get console screen buffer info from win32 API.')
        except ctypes.ArgumentError:
            raise IOError(
                'Unable to get console screen buffer info from win32 API.')

        # Parse data.
        result = dict(
            buffer_width=int(csbi.dwSize.X - 1),
            buffer_height=int(csbi.dwSize.Y),
            terminal_width=int(csbi.srWindow.Right - csbi.srWindow.Left),
            terminal_height=int(csbi.srWindow.Bottom - csbi.srWindow.Top),
            bg_color=int(csbi.wAttributes & 240),
            fg_color=int(csbi.wAttributes % 16),
        )
        return result
コード例 #8
0
def _api():
    def is_ctypes_subclass(other, main_class):
        while other:
            if other is main_class:
                return True
            other = getattr(other, "_type_", None)
        return False

    def is_ctypes_initialized(other):
        _other = other
        while other:
            if hasattr(other, "_fields_"):
                return True
            other = getattr(other, "_type_", None)
        print(_other, "NOT INIT")
        return False

    def is_ctypes_base(other):
        while type(getattr(other, "_type_", "")) != str:
            other = other._type_
        return other

    class MixIn:
        pass

    blend_cdll = ctypes.CDLL("")
    blend_lib = ctypes.LibraryLoader("")

    def blend_parse_dna():
        # from dna.c
        sdna_str_pt = blend_cdll.DNAstr
        sdna_len_pt = blend_cdll.DNAlen

        # cast
        sdna_len_pt = ctypes.c_void_p.from_address(
            ctypes.addressof(sdna_len_pt))
        sdna_len = ctypes.c_int.from_address(sdna_len_pt.value)

        blend_sdna = ctypes.string_at(sdna_str_pt, sdna_len)

        ofs = 0
        assert (blend_sdna[ofs:ofs + 8] == b'SDNANAME')
        ofs += 8

        sdna_names_len = struct.unpack("i", blend_sdna[ofs:ofs + 4])[0]
        ofs += 4

        blend_sdna_names = blend_sdna[ofs:].split(b'\0', sdna_names_len)
        blend_sdna_remainder = blend_sdna_names.pop(
            -1)  # last item is not a name.
        ofs = len(blend_sdna) - len(blend_sdna_remainder)
        ofs = (ofs + 3) & ~3

        assert (blend_sdna[ofs:ofs + 4] == b'TYPE')
        ofs += 4

        sdna_types_len = struct.unpack("i", blend_sdna[ofs:ofs + 4])[0]
        ofs += 4

        blend_sdna_types = blend_sdna[ofs:].split(b'\0', sdna_types_len)
        blend_sdna_remainder = blend_sdna_types.pop(-1)
        ofs = len(blend_sdna) - len(blend_sdna_remainder)
        ofs = (ofs + 3) & ~3

        assert (blend_sdna[ofs:ofs + 4] == b'TLEN')
        ofs += 4

        blend_sdna_typelens = struct.unpack(
            "%dh" % sdna_types_len, blend_sdna[ofs:ofs + (sdna_types_len * 2)])
        ofs += sdna_types_len * 2
        ofs = (ofs + 3) & ~3

        # array of pointers to short arrays
        assert (blend_sdna[ofs:ofs + 4] == b'STRC')
        ofs += 4

        sdna_structs_len = struct.unpack("i", blend_sdna[ofs:ofs + 4])[0]
        ofs += 4

        blend_sdna_structs = []

        for i in range(sdna_structs_len):
            struct_type, struct_tot = struct.unpack("hh",
                                                    blend_sdna[ofs:ofs + 4])
            ofs += 4
            struct_type_name_pairs = struct.unpack(
                "%dh" % struct_tot * 2, blend_sdna[ofs:ofs + (struct_tot * 4)])

            # convert into pairs, easier to understand (type, name)
            struct_type_name_pairs = [(struct_type_name_pairs[j],
                                       struct_type_name_pairs[j + 1])
                                      for j in range(0, struct_tot * 2, 2)]

            blend_sdna_structs.append((struct_type, struct_type_name_pairs))
            ofs += struct_tot * 4
            # ofs = (ofs + 1) & ~1

        return blend_sdna_names, blend_sdna_types, blend_sdna_typelens, blend_sdna_structs

    def create_dna_structs(blend_sdna_names, blend_sdna_types,
                           blend_sdna_typelens, blend_sdna_structs):

        # create all subclasses of ctypes.Structure
        ctypes_structs = {
            name: type(name.decode(), (ctypes.Structure, MixIn), {})
            for name in blend_sdna_types
        }
        ctypes_basic = {
            b"float": ctypes.c_float,
            b"double": ctypes.c_double,
            b"int": ctypes.c_int,
            b"short": ctypes.c_short,
            b"char": ctypes.c_char,
            b"void": ctypes.c_void_p
        }
        ctypes_fields = {}

        # collect fields
        for struct_id, struct_type_name_pairs in blend_sdna_structs:
            struct_name = blend_sdna_types[struct_id]
            ctype_struct = ctypes_structs[struct_name]
            fields = []

            for stype, sname in struct_type_name_pairs:
                name_string = blend_sdna_names[sname]
                type_string = blend_sdna_types[stype]
                type_py = ctypes_basic.get(type_string)
                if type_py is None:
                    type_py = ctypes_structs.get(type_string)

                # todo, these might need to be changed
                name_string = name_string.replace(b"(", b"")
                name_string = name_string.replace(b")", b"")

                # * First parse the pointer *
                pointer_count = 0
                while name_string[0] == 42:  # '*'
                    pointer_count += 1
                    name_string = name_string[1:]

                # alredy a pointer
                if type_py is ctypes.c_void_p:
                    pointer_count -= 1
                elif type_py is ctypes.c_char and pointer_count == 1:
                    type_py = ctypes.c_char_p
                    pointer_count = 0

                if pointer_count < 0:
                    Exception("error parsing pointer")

                for i in range(pointer_count):
                    type_py = ctypes.POINTER(type_py)

                # * Now parse the array [] *
                if b'[' in name_string:
                    name_string = name_string.replace(b'[', b' ')
                    name_string = name_string.replace(b']', b' ')
                    name_split = name_string.split()
                    name_string = name_split[0]
                    for array_dim in reversed(name_split[1:]):
                        type_py = type_py * int(array_dim)

                fields.append((name_string.decode(), type_py))

            ctypes_fields[struct_name] = fields

        # apply fields all in one go!
        for struct_id, struct_type_name_pairs in blend_sdna_structs:
            struct_name = blend_sdna_types[struct_id]
            ctype_struct = ctypes_structs[struct_name]
            try:
                ctype_struct._fields_ = ctypes_fields[struct_name]
            except:
                '''
                print("Error:", struct_name)
                import traceback
                traceback.print_exc()
                '''
                pass
                # print(fields)

        # test fields
        #for struct_id, struct_type_name_pairs in blend_sdna_structs:
        #    ctype_struct = ctypes_structs[blend_sdna_types[struct_id]]
        #    if blend_sdna_typelens[struct_id] != ctypes.sizeof(ctype_struct):
        #        print("Size Mismatch for %r blender:%d vs python:%d" % (blend_sdna_types[struct_id], blend_sdna_typelens[struct_id], ctypes.sizeof(ctype_struct)))

        return ctypes_structs

    def decorate_api(struct_dict):

        # * Decotate the api *

        # listbase iter

        type_cast_lb = struct_dict[b'ListBase']
        type_cast_link = struct_dict[b'Link']

        def list_base_iter(self, type_name):
            if type(type_name) == str:
                type_cast = struct_dict[type_name.encode('ASCII')]
            else:
                # allow passing types direcly
                type_cast = type_name

            # empty listbase
            if self.first is None:
                ret = None
            else:
                try:
                    ret = type_cast_link.from_address(
                        ctypes.addressof(self.first))
                except TypeError:
                    ret = type_cast_link.from_address(self.first)

            while ret is not None:
                return_value = type_cast.from_address(ctypes.addressof(ret))
                try:
                    next_pointer = getattr(ret.next, "contents")
                except:
                    next_pointer = None

                if next_pointer:
                    ret = type_cast_link.from_address(
                        ctypes.addressof(next_pointer))
                else:
                    ret = None

                yield return_value

        struct_dict[b'ListBase'].ITER = list_base_iter

        def CAST(self, to):
            if type(type_name) == str:
                type_cast = struct_dict[to.encode('ASCII')]
            else:
                type_cast = to

            return type_cast.from_address(ctypes.addressof(self))

        MixIn.CAST = CAST

    blend_sdna_names, blend_sdna_types, blend_sdna_typelens, blend_sdna_structs = blend_parse_dna(
    )
    struct_dict = create_dna_structs(blend_sdna_names, blend_sdna_types,
                                     blend_sdna_typelens, blend_sdna_structs)

    def printStructs(showStructs=None):
        for struct_id, struct_type_name_pairs in blend_sdna_structs:
            struct_name = blend_sdna_types[struct_id].decode()
            if not showStructs or struct_name in showStructs:
                print("typedef struct %s {" % struct_name)
                for stype, sname in struct_type_name_pairs:
                    print("    %s %s;" % (blend_sdna_types[stype].decode(),
                                          blend_sdna_names[sname].decode()))
                print("} %s;" % struct_name)

    decorate_api(struct_dict)  # not essential but useful

    # manually wrap Main
    Main = type("Main", (ctypes.Structure, ), {})
    _lb = struct_dict[b"ListBase"]
    Main._fields_ = [("next", ctypes.POINTER(Main)),
                     ("prev", ctypes.POINTER(Main)),
                     ("name", ctypes.c_char * 240),
                     ("versionfile", ctypes.c_short),
                     ("subversionfile", ctypes.c_short),
                     ("minversionfile", ctypes.c_short),
                     ("minsubversionfile", ctypes.c_short),
                     ("revision", ctypes.c_int),
                     ("curlib", ctypes.POINTER(struct_dict[b"Library"])),
                     ("scene", _lb), ("library", _lb), ("object", _lb),
                     ("mesh", _lb), ("curve", _lb), ("mball", _lb),
                     ("mat", _lb), ("tex", _lb), ("image", _lb), ("latt", _lb),
                     ("lamp", _lb), ("camera", _lb), ("ipo", _lb),
                     ("key", _lb), ("world", _lb), ("screen", _lb),
                     ("script", _lb), ("vfont", _lb), ("text", _lb),
                     ("sound", _lb), ("group", _lb), ("armature", _lb),
                     ("action", _lb), ("nodetree", _lb), ("brush", _lb),
                     ("particle", _lb), ("wm", _lb), ("gpencil", _lb),
                     ("movieclip", _lb), ("mask", _lb), ("linestyle", _lb)]
    del _lb

    # import bpy
    # main = Main.from_address(bpy.data.as_pointer())
    # main is the first pointer in Global.
    main_address = ctypes.POINTER(ctypes.c_void_p).from_address(
        ctypes.addressof(blend_cdll.G)).contents.value
    main = Main.from_address(main_address)

    return main, struct_dict, printStructs
コード例 #9
0
ファイル: baseconfig.py プロジェクト: CosmoLike/cocoa
mock_load = os.environ.get('READTHEDOCS', None)
if mock_load:
    # noinspection PyCompatibility
    from unittest.mock import MagicMock

    camblib = MagicMock()
    import_property = MagicMock()
else:

    if not osp.isfile(CAMBL):
        sys.exit(
            'Library file %s does not exist.\nMake sure you have installed or built the camb package '
            '(e.g. using "python setup.py make"); or remove any old conflicting installation and install again.'
            % CAMBL)

    camblib = ctypes.LibraryLoader(IfortGfortranLoader).LoadLibrary(CAMBL)

    try:
        c_int.in_dll(camblib, "handles_mp_set_cls_template_")
        gfortran = False
    except Exception:
        pass

    class _dll_value:
        __slots__ = ['f']

        def __init__(self, f):
            self.f = f

        def __get__(self, instance, owner):
            return self.f.value
コード例 #10
0
ファイル: win32.py プロジェクト: more-please/ndk
        ('ProcessMemoryLimit', ctypes.c_size_t),
        ('JobMemoryLimit', ctypes.c_size_t),
        ('PeakProcessMemoryUsed', ctypes.c_size_t),
        ('PeakJobMemoryUsed', ctypes.c_size_t),
    ]


class UseLastErrorWinDLL(ctypes.WinDLL):
    def __init__(self, name, mode=ctypes.DEFAULT_MODE, handle=None):
        super(UseLastErrorWinDLL, self).__init__(name,
                                                 mode,
                                                 handle,
                                                 use_last_error=True)


_LOADER = ctypes.LibraryLoader(UseLastErrorWinDLL)


def CreateJobObject(attributes=None, name=None):
    fn_CreateJobObjectW = _LOADER.kernel32.CreateJobObjectW
    fn_CreateJobObjectW.restype = ctypes.wintypes.HANDLE
    fn_CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
    job = fn_CreateJobObjectW(attributes, name)
    if job is None:
        # Automatically calls GetLastError and FormatError for us to create the
        # WindowsError exception.
        raise ctypes.WinError(ctypes.get_last_error())
    return job


def SetInformationJobObject(job, info_class, info):
コード例 #11
0
import time
import os
import array

import ctypes

#use "windll" for stdcall functions (eg. the Windows API)
#ctypes.

myLibrary = ctypes.LibraryLoader(ctypes.WinDLL).LoadLibrary(
    "D:\\GerryHendratno\\ProjekteBsp\\CANape\\CANape_Automatisierung\\Python\\API_DLL_mitPython\\CANapAPI.dll"
)

#"cdll" for cdecl functions
#myLibrary = ctypes.windll.LoadLibrary("D:\\GerryHendratno\\ProjekteBsp\\CANape\\CANape_Automatisierung\\Python\\API_DLL_mitPython\\CANapAPI.dll")

gWorkDir = ctypes.c_char_p("D:\\GerryHendratno\\00_MyTestSystem\\")
gDebugMode = ctypes.c_bool(True)
gClearDevList = ctypes.c_bool(False)
gModalMode = ctypes.c_bool(False)
hexmode = ctypes.c_bool(False)
Online = ctypes.c_bool(True)
myValueCalib = 0
MyXCPMdlHandle = ctypes.c_long(1)
myHandle = ctypes.c_long(1)
myValueCalib = ctypes.c_long(1)
ret = ctypes.c_bool(False)
#myRet = ctypes.c_int(1)
myRet = 1

ret = myLibrary.Asap3Init5(ctypes.byref(myHandle), ctypes.c_long(120000),
コード例 #12
0
    ctypes.HRESULT = HRESULT

    # Fix OleDLL.
    class OleDLL(ctypes.CDLL):
        """This class represents a dll exporting functions using the
        Windows stdcall calling convention, and returning HRESULT.
        HRESULT error values are automatically raised as WindowsError
        exceptions.
        """
        _func_flags_ = _FUNCFLAG_STDCALL
        _func_restype_ = HRESULT

    ctypes.OleDLL = OleDLL

    # Fix windll, oledll and GetLastError.
    ctypes.windll = ctypes.LibraryLoader(WinDLL)
    ctypes.oledll = ctypes.LibraryLoader(OleDLL)
    ctypes.GetLastError = ctypes.windll.kernel32.GetLastError

    # Fix get_last_error and set_last_error.
    ctypes.get_last_error = ctypes.windll.kernel32.GetLastError
    ctypes.set_last_error = ctypes.windll.kernel32.SetLastError

    # Fix FormatError.
    def FormatError(code):
        code = int(long(code))
        try:
            if GuessStringType.t_default == GuessStringType.t_ansi:
                FormatMessage = windll.kernel32.FormatMessageA
                FormatMessage.argtypes = [
                    DWORD, LPVOID, DWORD, DWORD, LPSTR, DWORD
コード例 #13
0
ファイル: symbolic.py プロジェクト: alexzucca90/MGCAMB
def compile_source_function_code(code_body,
                                 file_path='',
                                 compiler=None,
                                 fflags=None,
                                 cache=True):
    """
    Compile fortran code into function pointer in compiled shared library.
    The function is not intended to be called from python, but for passing back to compiled CAMB.

    :param code_body: fortran code to do calculation and assign sources(i) output array.
     Can start with declarations of temporary variables if needed.
    :param file_path: optional output path for generated f90 code
    :param compiler: compiler, usually on path
    :param fflags: options for compiler
    :param cache: whether to cache the result
    :return: function pointer for compiled code
    """

    if cache and code_body in _func_cache:
        return _func_cache[code_body].source_func_

    global _source_file_count

    template = """
    REAL*8 function source_func(sources, tau, a, adotoa, grho, gpres,w_lam, cs2_lam,  &
        grhob_t,grhor_t,grhoc_t,grhog_t,grhov_t,grhonu_t, &
        k,etak, etakdot, phi, phidot, sigma, sigmadot, &
        dgrho, clxg,clxb,clxc,clxr,clxnu, clxde, delta_p_b, &
        dgq, qg, qr, qde, vb, qgdot, qrdot, vbdot, &
        dgpi, pig, pir, pigdot, pirdot, diff_rhopi, &
        polter, polterdot, polterddot, octg, octgdot, E, Edot, &
        opacity, dopacity, ddopacity, visibility, dvisibility, ddvisibility, exptau, &
        tau0, tau_maxvis, Kf, f_K)
    implicit none
    real*8, intent(out) :: sources(:)
    REAL*8, intent(in) ::  tau, a, adotoa, grho, gpres,w_lam, cs2_lam,  &
            grhob_t,grhor_t,grhoc_t,grhog_t,grhov_t,grhonu_t, &
            k,  etak, etakdot, phi, phidot, sigma, sigmadot, &
            dgrho, clxg,clxb,clxc,clxr,clxnu, clxde, delta_p_b, &
            dgq, qg, qr, qde, vb, qgdot, qrdot, vbdot, &
            dgpi, pig, pir,  pigdot, pirdot, diff_rhopi, &
            polter, polterdot, polterddot, octg, octgdot, E(2:3), Edot(2:3), &
            opacity, dopacity, ddopacity, visibility, dvisibility, ddvisibility, exptau, &
            tau0, tau_maxvis, Kf(*)
    real*8, external :: f_K

    %s
    end function
    """

    import subprocess, tempfile, struct, platform

    compiler = compiler or get_default_compiler()
    fflags = fflags or _default_flags

    if struct.calcsize("P") == 4: fflags = "-m32 " + fflags
    if platform.system() == "Windows": fflags += ' -static'

    workdir = file_path or tempfile.gettempdir()
    if not os.access(workdir, os.F_OK):
        os.mkdir(workdir)

    oldwork = os.getcwd()
    source_file = None
    try:
        os.chdir(workdir)
        _source_file_count += 1
        while True:
            name_tag = 'camb_source%s' % _source_file_count
            dll_name = name_tag + '.dll'
            if not os.path.exists(dll_name):
                break
            try:
                os.remove(dll_name)
            except:
                _source_file_count += 1

        source_file = name_tag + '.f90'
        with open(source_file, 'w') as f:
            f.write(template % code_body)

        command = " ".join([compiler, fflags, source_file, "-o", dll_name])
        try:
            subprocess.check_output(command,
                                    stderr=subprocess.STDOUT,
                                    shell=True,
                                    cwd=workdir)
        except subprocess.CalledProcessError as E:
            print(command)
            print('Error compiling generated code:')
            print(E.output)
            print('Source is:\n %s' % code_body)
            raise
    finally:
        if not file_path and source_file: os.remove(source_file)
        os.chdir(oldwork)

    # Had weird crashes when LoadLibrary path was relative to current dir
    dll_name = os.path.join(workdir, dll_name)
    func_lib = ctypes.LibraryLoader(ctypes.CDLL).LoadLibrary(dll_name)

    if cache:
        _func_cache[code_body] = func_lib

    if not file_path:
        # won't work on Windows while DLL in use
        try:
            os.remove(dll_name)
        except:
            pass

    return func_lib.source_func_
コード例 #14
0
ファイル: t_pkinit.py プロジェクト: svd-zp/krb5
#!/usr/bin/python
from k5test import *

# Skip this test if pkinit wasn't built.
if not os.path.exists(os.path.join(plugins, 'preauth', 'pkinit.so')):
    skip_rest('PKINIT tests', 'PKINIT module not built')

# Check if soft-pkcs11.so is available.
try:
    import ctypes
    lib = ctypes.LibraryLoader(ctypes.CDLL).LoadLibrary('soft-pkcs11.so')
    del lib
    have_soft_pkcs11 = True
except:
    have_soft_pkcs11 = False

# Construct a krb5.conf fragment configuring pkinit.
certs = os.path.join(srctop, 'tests', 'dejagnu', 'pkinit-certs')
ca_pem = os.path.join(certs, 'ca.pem')
kdc_pem = os.path.join(certs, 'kdc.pem')
user_pem = os.path.join(certs, 'user.pem')
privkey_pem = os.path.join(certs, 'privkey.pem')
privkey_enc_pem = os.path.join(certs, 'privkey-enc.pem')
user_p12 = os.path.join(certs, 'user.p12')
user_enc_p12 = os.path.join(certs, 'user-enc.p12')
path = os.path.join(os.getcwd(), 'testdir', 'tmp-pkinit-certs')
path_enc = os.path.join(os.getcwd(), 'testdir', 'tmp-pkinit-certs-enc')

pkinit_krb5_conf = {
    'realms': {
        '$realm': {
コード例 #15
0
ファイル: triangle.py プロジェクト: fritsdeprenter/sambal
import numpy, ctypes
loader = ctypes.LibraryLoader(ctypes.CDLL)


def myproperty(f):
    name = f.__name__

    def property_getter(self):
        try:
            value = self.__dict__[name]
        except KeyError:
            value = f(self)
        return value

    def property_setter(self, value):
        self.__dict__[name] = value

    return property(fget=property_getter, fset=property_setter)


class Triangulate(ctypes.Structure):

    c_double = ctypes.c_double
    c_int = ctypes.c_int
    p_double = ctypes.POINTER(c_double)
    p_int = ctypes.POINTER(c_int)

    _fields_ = [
        ('pointlist', p_double),
        ('pointattributelist', p_double),
        ('pointmarkerlist', p_int),
コード例 #16
0
ファイル: baseconfig.py プロジェクト: sunt05/CAMB
mock_load = os.environ.get('READTHEDOCS', None)
if mock_load:
    from unittest.mock import MagicMock

    camblib = MagicMock()
    import_property = MagicMock()
else:

    if not osp.isfile(CAMBL):
        sys.exit(
            'Library file %s does not exist.\nMake sure you have installed or built the camb package '
            '(e.g. using "python setup.py make"); or remove any old conflicting installation and install again.'
            % (CAMBL))

    camblib = ctypes.LibraryLoader(ifort_gfortran_loader).LoadLibrary(CAMBL)

    try:
        c_int.in_dll(camblib, "handles_mp_set_cls_template_")
        gfortran = False
    except Exception:
        pass

    class _dll_value(object):
        __slots__ = ['f']

        def __init__(self, f):
            self.f = f

        def __get__(self, instance, owner):
            return self.f.value
コード例 #17
0
import sys
from .compiler import Compiler
from .extension import Extension
from .logger import Logger0, Logger1, Logger3
from .wheel import Wheel

__all__ = (
    "Compiler",
    "Extension",
    "Logger0",
    "Logger1",
    "Logger3",
    "Wheel",
)

# Enable console virtual terminal sequences on Windows
if sys.platform == "win32":
    import ctypes
    from ctypes import wintypes
    windll = ctypes.LibraryLoader(ctypes.WinDLL)
    set_console_mode = windll.kernel32.SetConsoleMode
    set_console_mode.argtypes = [wintypes.HANDLE, wintypes.DWORD]
    set_console_mode.restype = wintypes.BOOL

    get_std_handle = windll.kernel32.GetStdHandle
    get_std_handle.argtypes = [wintypes.DWORD]
    get_std_handle.restype = wintypes.HANDLE

    STDOUT = get_std_handle(-11)
    set_console_mode(STDOUT, 5)
コード例 #18
0
ファイル: reftools.py プロジェクト: darshangan/eoxserver
        ("pfnSrcDensityMaskFunc", C.c_void_p),
        ("pSrcDensityMaskFuncArg", C.c_void_p),
        ("pfnDstDensityMaskFunc", C.c_void_p),
        ("pDstDensityMaskFuncArg", C.c_void_p),
        ("pfnDstValidityMaskFunc", C.c_void_p),
        ("pDstValidityMaskFuncArg", C.c_void_p),
        ("pfnPreWarpChunkProcessor", C.c_void_p),
        ("pPreWarpProcessorArg", C.c_void_p),
        ("pfnPostWarpChunkProcessor", C.c_void_p),
        ("pPostWarpProcessorArg", C.c_void_p),
        ("hCutline", C.c_void_p),
        ("dfCutlineBlendDist", C.c_double),
    ]


_libgdal = C.LibraryLoader(C.CDLL).LoadLibrary(find_library("gdal"))

GDALGetGCPs = _libgdal.GDALGetGCPs
GDALGetGCPs.restype = C.c_void_p  # actually array of GCPs, but more info not required
GDALGetGCPs.argtypes = [C.c_void_p]

# baseline GDAL transformer creation functions

GDALCreateGCPTransformer = _libgdal.GDALCreateGCPTransformer
GDALCreateGCPTransformer.restype = C.c_void_p
# TODO: argtypes

GDALCreateTPSTransformer = _libgdal.GDALCreateTPSTransformer
GDALCreateTPSTransformer.restype = C.c_void_p
# TODO: argtypes
コード例 #19
0
ファイル: pyimod04_ctypes.py プロジェクト: pbraga88/study
def install():
    """Install the hooks.

    This must be done from a function as opposed to at module-level,
    because when the module is imported/executed, the import machinery
    is not completely set up yet.
    """

    import os

    try:
        import ctypes
    except ImportError:
        # ctypes is not included in the frozen application
        return

    def _frozen_name(name):
        # If the given (file)name does not exist, fall back to searching
        # for its basename in sys._MEIPASS, where PyInstaller usually
        # collects shared libraries.
        if name and not os.path.isfile(name):
            frozen_name = os.path.join(sys._MEIPASS, os.path.basename(name))
            if os.path.isfile(frozen_name):
                name = frozen_name
        return name

    class PyInstallerImportError(OSError):
        def __init__(self, name):
            self.msg = ("Failed to load dynlib/dll %r. "
                        "Most probably this dynlib/dll was not found "
                        "when the application was frozen.") % name
            self.args = (self.msg, )

    class PyInstallerCDLL(ctypes.CDLL):
        def __init__(self, name, *args, **kwargs):
            name = _frozen_name(name)
            try:
                super().__init__(name, *args, **kwargs)
            except Exception as base_error:
                raise PyInstallerImportError(name) from base_error

    ctypes.CDLL = PyInstallerCDLL
    ctypes.cdll = ctypes.LibraryLoader(PyInstallerCDLL)

    class PyInstallerPyDLL(ctypes.PyDLL):
        def __init__(self, name, *args, **kwargs):
            name = _frozen_name(name)
            try:
                super().__init__(name, *args, **kwargs)
            except Exception as base_error:
                raise PyInstallerImportError(name) from base_error

    ctypes.PyDLL = PyInstallerPyDLL
    ctypes.pydll = ctypes.LibraryLoader(PyInstallerPyDLL)

    if sys.platform.startswith('win'):

        class PyInstallerWinDLL(ctypes.WinDLL):
            def __init__(self, name, *args, **kwargs):
                name = _frozen_name(name)
                try:
                    super().__init__(name, *args, **kwargs)
                except Exception as base_error:
                    raise PyInstallerImportError(name) from base_error

        ctypes.WinDLL = PyInstallerWinDLL
        ctypes.windll = ctypes.LibraryLoader(PyInstallerWinDLL)

        class PyInstallerOleDLL(ctypes.OleDLL):
            def __init__(self, name, *args, **kwargs):
                name = _frozen_name(name)
                try:
                    super().__init__(name, *args, **kwargs)
                except Exception as base_error:
                    raise PyInstallerImportError(name) from base_error

        ctypes.OleDLL = PyInstallerOleDLL
        ctypes.oledll = ctypes.LibraryLoader(PyInstallerOleDLL)
コード例 #20
0
        _fields_ = [("dwSize", ctypes.c_ulong), ("bVisible", ctypes.c_bool)]

        def __init__(self, size=0, visible=True):
            self.dwSize = size
            self.bVisible = visible

    class ConsoleScreenBuffer:
        GENERIC_READ = 0x80000000
        GENERIC_WRITE = 0x40000000
        GENERIC_EXECUTE = 0x20000000
        GENERIC_ALL = 0x10000000

        FILE_SHARE_READ = 0x00000001
        FILE_SHARE_WRITE = 0x00000002

    kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32

    def pause():
        os.system("pause")

    def get_buffer_cursor_x(console_buffer):
        info = ctypes.create_string_buffer(22)
        kernel32.GetConsoleScreenBufferInfo(console_buffer, info)
        (bufx, bufy, cursor_x, cursor_y, wattr, left, top, right, bottom, maxx,
         maxy) = struct.unpack("hhhhHhhhhhh", info)
        return cursor_x

    def get_buffer_cursor_y(console_buffer):
        info = ctypes.create_string_buffer(22)
        kernel32.GetConsoleScreenBufferInfo(console_buffer, info)
        (bufx, bufy, cursor_x, cursor_y, wattr, left, top, right, bottom, maxx,