示例#1
0
    def CoCreateInstanceC2R(self, store, reg, clsid, iid):
        # Ugly code to find DLL in C2R version of COM object and get a COM
        # object despite the fact that COM doesn't handle C2R
        try:
            # Get DLL to load from 2R register
            aReg = winreg.ConnectRegistry(None, store)
            aKey = winreg.OpenKey(aReg, reg, 0,
                                  winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
            dummy_n, IconvDLL, dummy_t = winreg.EnumValue(aKey, 0)
            winreg.CloseKey(aKey)
            winreg.CloseKey(aReg)

            # Create OLE object from DLL
            IconvOLE = ctypes.OleDLL(IconvDLL)

            # Get COM Instance from OLE
            clsid_class = uuid.UUID(str(clsid)).bytes_le
            iclassfactory = uuid.UUID(str(
                pythoncom.IID_IClassFactory)).bytes_le
            com_classfactory = ctypes.c_long(0)
            IconvOLE.DllGetClassObject(clsid_class, iclassfactory,
                                       ctypes.byref(com_classfactory))
            MyFactory = pythoncom.ObjectFromAddress(
                com_classfactory.value, pythoncom.IID_IClassFactory)
            return MyFactory.CreateInstance(None, str(iid))
        except:
            return None
示例#2
0
文件: runner.py 项目: yanxxd/syzygy
 def _TearDown(self):
   try:
     cf_dll = ctypes.OleDLL(self._chrome_frame_dll)
     cf_dll.DllUnregisterServer()
   except Exception as e:
     # Squash any errors here.
     _LOGGER.info('Error unregistering Chrome Frame dll: %s', e)
示例#3
0
def fix_scaling():
    import sys
    if sys.platform == 'win32':
        try:
            import ctypes
            PROCESS_SYSTEM_DPI_AWARE = 1
            ctypes.OleDLL('shcore').SetProcessDpiAwareness(
                PROCESS_SYSTEM_DPI_AWARE)
        except (ImportError, AttributeError, OSError):
            pass
示例#4
0
def enable_hidpi_support():
    # Try to tell Windows we're HiDPI aware, to disable scaling
    if sys.platform == 'win32':
        try:
            import ctypes
            PROCESS_SYSTEM_DPI_AWARE = 1
            ctypes.OleDLL('shcore').SetProcessDpiAwareness(
                PROCESS_SYSTEM_DPI_AWARE)
        except (AttributeError, OSError):
            pass
示例#5
0
文件: runner.py 项目: yanxxd/syzygy
 def _SetUp(self):
   if self._ie_path:
     # Register the CF dll.
     try:
       cf_dll = ctypes.OleDLL(self._chrome_frame_dll)
       cf_dll.DllRegisterServer()
     except Exception:
       raise RunnerError('Could not load Chrome Frame dll at [%s].' %
                         self._chrome_frame_dll)
   else:
     raise RunnerError('Could not locate path to iexplore.exe.')
示例#6
0
def set_dpi_aware():
    # https://stackoverflow.com/questions/36134072/setprocessdpiaware-seems-not-to-work-under-windows-10
    # https://bugs.python.org/issue33656
    # https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx
    # https://github.com/python/cpython/blob/master/Lib/idlelib/pyshell.py
    if sys.platform == "win32":
        try:
            import ctypes

            PROCESS_SYSTEM_DPI_AWARE = 1
            ctypes.OleDLL("shcore").SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
        except (ImportError, AttributeError, OSError):
            pass
示例#7
0
def initModules():
    global g_h2langDll
    global g_user32Dll
    global g_BaseAddress
    global g_TagGroupListAddress

    # Get the idb folder which will contains the h2alang.dll file.
    modulePath = idautils.GetIdbDir() + "h2alang.dll"

    # Check if the h2alang.dll module exists.
    if os.path.isfile(modulePath) is False:
        # The file does not exist, display a message to the user.
        idaapi.warning("Could not find \"%s\"!" % modulePath)
        return False

    try:
        # Load the h2alang.dll module.
        g_h2langDll = ctypes.cdll.LoadLibrary(modulePath)

        # Try to load the user32.dll module.
        g_user32Dll = ctypes.OleDLL("user32.dll")
    except Exception:
        # Failed to load the h2alang.dll file.
        idaapi.warning("Failed to load \"%s\"!" % modulePath)
        return False

    # Check the input file name to determine which hek tool we have loaded.
    moduleName = idc.GetInputFile()
    if moduleName == "H2Guerilla.exe":
        # Load values for h2 guerilla executable.
        g_BaseAddress = 0x400000
        g_TagGroupListAddress = 0x00901B90
    elif moduleName == "H2Sapien.exe":
        # Load values for h2 sapien executable.
        idaapi.warning("H2Sapien currently not supported!")
        return False
    elif moduleName == "H2Tool.exe":
        # Load values for h2 tool executable.
        idaapi.warning("H2Tool currently not supported!")
        return False
    else:
        # Unknown module.
        idaapi.warning("Unknown HEK module loaded!")
        return False

    # Initialized successfully.
    return True
示例#8
0
文件: __init__.py 项目: 5Nap/Geometry
def register_server(source_dir):
    """ Register testing server appropriate for the python architecture.

    ``source_dir`` gives the absolute path to the comtype source in which the
    32- and 64-bit testing server, "AvmcIfc.dll" is defined.

    If the server is already registered, do nothing.

    """
    # The 64-bitness of the python interpreter determines the testing dll to
    # use.
    dll_name = "AvmcIfc_x64.dll" if sys.maxsize > 2**32 else "AvmcIfc.dll"
    dll_path = os.path.join(source_dir, "Debug", dll_name)
    # Register our ATL COM tester dll
    dll = ctypes.OleDLL(dll_path)
    dll.DllRegisterServer()
    return
示例#9
0
    def __init__(self, on_resize=None):
        super().__init__()

        if on_resize: self.on_resize = on_resize

        self.user32 = ctypes.WinDLL('user32', use_last_error=True)
        self.ole32 = ctypes.OleDLL('ole32')

        self.ole32.CoInitialize(0)

        WinEventProcType = ctypes.WINFUNCTYPE(
            None, ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD,
            ctypes.wintypes.HWND, ctypes.wintypes.LONG, ctypes.wintypes.LONG,
            ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)

        self.WinEventProc = WinEventProcType(self.callback)
        self.user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
示例#10
0
    def run(self):
        build = self.reinitialize_command('build')
        build.run()
        if build.build_lib is not None:
            sys.path.insert(0, build.build_lib)

        # Register our ATL COM tester dll
        dll = ctypes.OleDLL(r"source\debug\AvmcIfc.dll")
        dll.DllRegisterServer()

        import comtypes.test
        comtypes.test.use_resources.extend(self.use_resources)

        for name in self.tests:
            package = __import__(name, globals(), locals(), ['*'])
            sys.stdout.write("Testing package %s %s\n"
                             % (name, (sys.version, sys.platform, os.name)))
            comtypes.test.run_tests(package,
                                    "test_*.py",
                                    self.verbose,
                                    self.refcounts)
示例#11
0
def fix_scaling():
    import sys
    if sys.platform == 'win32':
        import ctypes
        PROCESS_SYSTEM_DPI_AWARE = 1
        ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
示例#12
0
# unittest for SOME ctypes com function calls.
# Can't resist from implementing some kind of mini-comtypes
# theller ;-)

import pytest
import sys
if sys.platform != "win32":
    # this doesn't work, it still tries to do module-level imports
    # pytestmark = pytest.mark.skip("skip_the_whole_module")
    pytest.importorskip('skip_the_whole_module')  # hack!

import ctypes, types, unittest
from ctypes import HRESULT
from _ctypes import COMError

oleaut32 = ctypes.OleDLL("oleaut32")


class UnboundMethod(object):
    def __init__(self, func, index, name):
        self.func = func
        self.index = index
        self.name = name
        self.__doc__ = func.__doc__

    def __repr__(self):
        return "<Unbound COM method index %d: %s at %x>" % (
            self.index, self.name, id(self))

    def __get__(self, instance, owner):
        if instance is None:
示例#13
0
#!/usr/bin/env python
from __future__ import print_function, absolute_import, division, unicode_literals
import ctypes as ct
from ctypes import wintypes as wt
from ctypes.util import find_library
from . import daqh

#initialize Daqx.dll
# Retocamos esto
dll = find_library('daqx')
#print("Dll = ", dll)
print('Estas usando el que esta en Anaconda3\lib')
daq = ct.OleDLL(r'C:\Users\Administrator\Downloads\PyIOTech-master\Daqx64.dll')


class deviceProps(ct.Structure):
    """
    This class emulates a C struct for the device properties calls
    """
    _fields_ = [("deviceType", wt.DWORD), ("basePortAddress", wt.DWORD),
                ("dmaChannel", wt.DWORD), ("socket", wt.DWORD),
                ("interruptLevel", wt.DWORD), ("protocol", wt.DWORD),
                ("alias", ct.c_char * 64), ("maxAdChannels", wt.DWORD),
                ("maxDaChannels", wt.DWORD), ("maxDigInputBits", wt.DWORD),
                ("maxDigOutputBits", wt.DWORD), ("maxCtrChannels", wt.DWORD),
                ("mainUnitAdChannels", wt.DWORD),
                ("mainUnitDaChannels", wt.DWORD),
                ("mainUnitDigInputBits", wt.DWORD),
                ("mainUnitDigOutputBits", wt.DWORD),
                ("mainUnitCtrChannels", wt.DWORD), ("adFifoSize", wt.DWORD),
                ("daFifoSize", wt.DWORD), ("adResolution", wt.DWORD),
示例#14
0
    print('Desktop:  ', kf.Desktop)
    print('Programs: ', kf.Programs)

Print all known folder names and paths:

    from knownfolders import table as kf_table
    for k,v in kf_table.items():
        print("{:<22}: {}".format(k,v))

'''
import ctypes
from ctypes import wintypes

__all__ = ['FOLDERID', 'get_known_folder_path']

_ole32 = ctypes.OleDLL('ole32')
_shell32 = ctypes.OleDLL('shell32')

class GUID(ctypes.Structure):
    _fields_ = (('Data1', ctypes.c_ulong),
                ('Data2', ctypes.c_ushort),
                ('Data3', ctypes.c_ushort),
                ('Data4', ctypes.c_char * 8))
    def __init__(self, guid_string):
        _ole32.IIDFromString(guid_string, ctypes.byref(self))

REFKNOWNFOLDERID = LPIID = ctypes.POINTER(GUID)

_ole32.IIDFromString.argtypes = (
    wintypes.LPCWSTR, # lpsz,
    LPIID)            # lpiid
示例#15
0
    def __init__(self, path, libtype=None, **kwargs):
        """Load a shared library.

        For example, a C/C++, FORTRAN, C#, Java, Delphi, LabVIEW, ActiveX, ... library.

        Based on the value of `libtype` this class will load the shared library as a:

            * :class:`~ctypes.CDLL` if `libtype` is ``'cdll'``,
            * :class:`~ctypes.WinDLL` if `libtype` is ``'windll'``,
            * :class:`~ctypes.OleDLL` if `libtype` is ``'oledll'``,
            * `System.Reflection.Assembly <Assembly_>`_ if `libtype` is ``'net'`` or ``'clr'`` ,
            * :class:`~.py4j.java_gateway.JavaGateway` if `libtype` is ``'java'``, or
            * comtypes.CreateObject_ if `libtype` is ``'com'``.

        .. versionchanged:: 0.4
           Added support for Java archives

        .. versionchanged:: 0.5
           Added support for COM_ libraries

        .. _Assembly: https://msdn.microsoft.com/en-us/library/system.reflection.assembly(v=vs.110).aspx
        .. _comtypes.CreateObject: https://pythonhosted.org/comtypes/#creating-and-accessing-com-objects
        .. _COM: https://en.wikipedia.org/wiki/Component_Object_Model

        Parameters
        ----------
        path : :class:`str`
            The path to the shared library.

            The search order for finding the shared library is:

                1. assume that a full or a relative (to the current working directory)
                   path is specified,
                2. use :func:`ctypes.util.find_library` to find the shared library file,
                3. search :data:`sys.path`, then
                4. search :data:`os.environ['PATH'] <os.environ>` to find the shared library.

            If loading a COM_ library then `path` represents the `progid <comtypes.CreateObject_>`_
            argument.

        libtype : :class:`str`, optional
            The library type. The following values are currently supported:

            * ``'cdll'`` -- for a library that uses the __cdecl calling convention
            * ``'windll'`` or ``'oledll'`` -- for a __stdcall calling convention
            * ``'net'`` or ``'clr'`` -- for Microsoft's .NET Framework (Common Language Runtime)
            * ``'java'`` -- for a Java archive, ``.jar``, or Java byte code, ``.class``, file
            * ``'com'`` -- for a COM_ library.

            Default is ``'cdll'``.

            .. tip::
               Since the ``.jar`` or ``.class`` extension uniquely defines a Java library,
               the `libtype` will be automatically set to ``'java'`` if `path` ends with
               ``.jar`` or ``.class``. If `path` starts with ``'{'`` and ends with ``'}'``
               then this uniquely defines the Class ID for a COM_ library and so `libtype`
               will be automatically set to ``'com'``.

        **kwargs
            Keyword arguments that are passed to the object that loads the library.

        Raises
        ------
        IOError
            If the shared library cannot be loaded.
        TypeError
            If `libtype` is not a supported library type.
        """
        # a reference to the shared library
        self._lib = None

        # a reference to the .NET Runtime Assembly
        self._assembly = None

        # a reference to the Py4J JavaGateway
        self._gateway = None

        if not path:
            raise ValueError(
                'You must specify the path, got {!r}'.format(path))

        # fixes Issue #8, if `path` is a <class 'pathlib.Path'> object
        if hasattr(path, 'as_posix'):
            path = path.as_posix()

        # try to automatically determine the libtype
        if libtype is None:
            if path.startswith('{') and path.endswith('}'):
                libtype = 'com'
            elif path.endswith('.jar') or path.endswith('.class'):
                libtype = 'java'
            else:
                libtype = 'cdll'
        else:
            libtype = libtype.lower()

        # create a new reference to `path` just in case the
        # DEFAULT_EXTENSION is appended below so that the
        # ctypes.util.find_library function call will use the
        # unmodified value of `path`
        _path = path

        # assume a default extension if no extension was provided
        ext = os.path.splitext(path)[1]
        if libtype != 'java' and libtype != 'com' and not ext:
            _path += DEFAULT_EXTENSION

        if IS_PYTHON2:
            _path = _path.encode(_encoding)

        if libtype != 'com':
            self._path = os.path.abspath(_path)
            if not os.path.isfile(self._path):
                # for find_library use the original 'path' value since it may be a library name
                # without any prefix like 'lib', suffix like '.so', '.dylib' or version number
                self._path = ctypes.util.find_library(path)
                if self._path is None:  # then search sys.path and os.environ['PATH']
                    success = False
                    search_dirs = sys.path + os.environ['PATH'].split(
                        os.pathsep)
                    for directory in search_dirs:
                        p = os.path.join(directory, _path)
                        if os.path.isfile(p):
                            self._path = p
                            success = True
                            break
                    if not success:
                        raise IOError(
                            'Cannot find the shared library {!r}'.format(path))
        else:
            self._path = _path

        if libtype == 'cdll':
            self._lib = ctypes.CDLL(self._path, **kwargs)
        elif libtype == 'windll':
            self._lib = ctypes.WinDLL(self._path, **kwargs)
        elif libtype == 'oledll':
            self._lib = ctypes.OleDLL(self._path, **kwargs)
        elif libtype == 'com':
            if not utils.is_comtypes_installed():
                raise IOError(
                    'Cannot load a COM library because comtypes is not installed.\n'
                    'To install comtypes run: pip install comtypes')
            from comtypes.client import CreateObject
            self._lib = CreateObject(self._path, **kwargs)
        elif libtype == 'java':
            if not utils.is_py4j_installed():
                raise IOError(
                    'Cannot load a Java file because Py4J is not installed.\n'
                    'To install Py4J run: pip install py4j')

            from py4j.version import __version__
            from py4j.java_gateway import JavaGateway, GatewayParameters

            # the address and port to use to host the py4j.GatewayServer
            address = kwargs.pop('address', '127.0.0.1')
            port = kwargs.pop('port', utils.get_available_port())

            # find the py4j JAR (needed to import py4j.GatewayServer on the Java side)
            root = os.path.dirname(sys.executable)
            filename = 'py4j' + __version__ + '.jar'
            py4j_jar = os.path.join(root, 'share', 'py4j', filename)
            if not os.path.isfile(py4j_jar):
                root = os.path.dirname(
                    root)  # then check one folder up (for unix or venv)
                py4j_jar = os.path.join(root, 'share', 'py4j', filename)
                if not os.path.isfile(py4j_jar):
                    py4j_jar = os.environ.get(
                        'PY4J_JAR', '')  # then check the environment variable
                    if not os.path.isfile(py4j_jar):
                        raise IOError(
                            'Cannot find {0}\nCreate a PY4J_JAR environment '
                            'variable to be equal to the full path to {0}'.
                            format(filename))

            # build the java command
            wrapper = os.path.join(os.path.dirname(__file__),
                                   'py4j-wrapper.jar')
            cmd = [
                'java', '-cp', py4j_jar + os.pathsep + wrapper, 'Py4JWrapper',
                str(port)
            ]

            # from the URLClassLoader documentation:
            #   Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL
            #   is assumed to refer to a JAR file which will be downloaded and opened as needed.
            if ext == '.jar':
                cmd.append(self._path)
            else:  # it is a .class file
                cmd.append(os.path.dirname(self._path) + '/')

            try:
                # start the py4j.GatewayServer, cannot use subprocess.call() because it blocks
                subprocess.Popen(cmd, stderr=sys.stderr, stdout=sys.stdout)
                err = None
            except IOError as e:
                err = str(
                    e
                ) + '\nYou must have a Java Runtime Environment installed and available on PATH'

            if err:
                raise IOError(err)

            utils.wait_for_server(address, port, 5.0)

            self._gateway = JavaGateway(gateway_parameters=GatewayParameters(
                address=address, port=port, **kwargs))

            self._lib = self._gateway.jvm

        elif libtype == 'net' or libtype == 'clr':
            if not utils.is_pythonnet_installed():
                raise IOError(
                    'Cannot load a .NET Assembly because pythonnet is not installed.\n'
                    'To install pythonnet run: pip install pythonnet')

            import clr
            try:
                # By default, pythonnet can only load libraries that are for .NET 4.0+.
                #
                # In order to allow pythonnet to load a library from .NET <4.0 the
                # useLegacyV2RuntimeActivationPolicy property needs to be enabled
                # in a <python-executable>.config file. If the following statement
                # raises a FileLoadException then attempt to create the configuration
                # file that has the property enabled and then notify the user why
                # loading the library failed and ask them to re-run their Python
                # script to load the .NET library.
                self._assembly = clr.System.Reflection.Assembly.LoadFile(
                    self._path)

            except clr.System.IO.FileLoadException as err:
                # Example error message that can occur if the library is for .NET <4.0,
                # and the useLegacyV2RuntimeActivationPolicy is not enabled:
                #
                # " Mixed mode assembly is built against version 'v2.0.50727' of the
                #  runtime and cannot be loaded in the 4.0 runtime without additional
                #  configuration information. "
                if str(err).startswith('Mixed mode assembly'):
                    status, msg = utils.check_dot_net_config(sys.executable)
                    if not status == 0:
                        raise IOError(msg)
                    else:
                        update_msg = 'Checking .NET config returned "{}" '.format(
                            msg)
                        update_msg += 'and still cannot load library.\n'
                        update_msg += str(err)
                        raise IOError(update_msg)
                raise IOError(
                    'The above "System.IO.FileLoadException" is not handled.\n'
                )

            # the shared library must be available in sys.path
            head, tail = os.path.split(self._path)
            if IS_PYTHON2:
                head = head.decode(_encoding)
            sys.path.append(head)

            # don't include the library extension
            clr.AddReference(os.path.splitext(tail)[0])

            import System
            dotnet = {'System': System}

            try:
                types = self._assembly.GetTypes()
            except Exception as e:
                logger.error(e)
                logger.error('The LoaderExceptions are:')
                for item in e.LoaderExceptions:
                    logger.error('  ' + item.Message)
            else:
                for t in types:
                    try:
                        if t.Namespace:
                            obj = __import__(t.Namespace)
                        else:
                            obj = getattr(__import__('clr'), t.FullName)
                    except:
                        obj = t
                        obj.__name__ = t.FullName

                    if obj.__name__ not in dotnet:
                        dotnet[obj.__name__] = obj

            self._lib = DotNet(dotnet, self._path)

        else:
            raise TypeError('Cannot load libtype={}'.format(libtype))

        if IS_PYTHON2:
            self._path = self._path.decode(_encoding)

        logger.debug('Loaded ' + self._path)
示例#16
0
    def __init__(self, path, libtype='cdll'):

        self._net = None

        #  assume a default extension if no extension was provided
        if not os.path.splitext(path)[1]:
            if IS_WINDOWS:
                path += '.dll'
            elif IS_LINUX:
                path += '.so'
            elif IS_MAC:
                path += '.dylib'

        self._path = os.path.abspath(path)
        if not os.path.isfile(self._path):
            raise IOError('Cannot find the shared library ' + self._path +
                          '\n')

        if libtype == 'cdll':
            self._lib = ctypes.CDLL(self._path)
        elif libtype == 'windll':
            self._lib = ctypes.WinDLL(self._path)
        elif libtype == 'oledll':
            self._lib = ctypes.OleDLL(self._path)
        elif libtype == 'net' and self.is_python_net_installed():
            import clr
            try:
                # pythonnet can only load libraries that are .NET 4.0+
                self._net = clr.System.Reflection.Assembly.LoadFile(self._path)
            except clr.System.IO.FileLoadException as err:
                # Example error message that can be displayed if the library is for .NET <4.0 is:
                #
                # " Mixed mode assembly is built against version 'v2.0.50727' of the
                #  runtime and cannot be loaded in the 4.0 runtime without additional
                #  configuration information. "
                #
                # To solve this problem, a <python-executable>.config file must exist and it must
                # contain a useLegacyV2RuntimeActivationPolicy property that is set to be True
                if "Mixed mode assembly" in str(err):
                    status, msg = self.check_dot_net_config(sys.executable)
                    if not status == 0:
                        raise IOError(msg)
                    else:
                        update_msg = 'Checking .NET config returned "{}"'.format(
                            msg)
                        update_msg += ' and still cannot load library.\n'
                        update_msg += str(err)
                        raise IOError(update_msg)
                raise IOError(
                    'The above "System.IO.FileLoadException" is not handled.\n'
                )

            # the shared library must available be in sys.path
            head, tail = os.path.split(self._path)
            sys.path.insert(0, head)

            # don't include the library extension
            clr.AddReference(os.path.splitext(tail)[0])

            # import the .NET module from the library
            exports = self._net.GetExportedTypes()
            self._lib = __import__(exports[0].Namespace)

        else:
            raise TypeError('Invalid library type: {}'.format(libtype))
示例#17
0
            self.file.flush(data)
            self.stream.flush(data)

    logfile = open(args.output, 'w')
    # this is not ideal: we monkeypatch stdout/stderr a second time
    # (already did for Unbuffered), so here we can't easily detect what
    # state we're in on closedown. Just hope it's okay...
    sys.stdout = Tee(logfile, sys.stdout)
    sys.stderr = Tee(logfile, sys.stderr)

# --- define helpers ----
if sys.platform == 'win32':
    # thanks to Eryk Sun for this recipe
    import ctypes

    shlwapi = ctypes.OleDLL('shlwapi')
    shlwapi.AssocQueryStringW.argtypes = (
        ctypes.c_ulong,  # flags
        ctypes.c_ulong,  # str
        ctypes.c_wchar_p,  # pszAssoc
        ctypes.c_wchar_p,  # pszExtra
        ctypes.c_wchar_p,  # pszOut
        ctypes.POINTER(ctypes.c_ulong),  # pcchOut
    )

    ASSOCF_NOTRUNCATE = 0x00000020
    ASSOCF_INIT_IGNOREUNKNOWN = 0x00000400
    ASSOCSTR_COMMAND = 1
    ASSOCSTR_EXECUTABLE = 2
    E_POINTER = ctypes.c_long(0x80004003).value
示例#18
0
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, font
import pathlib
import configparser
import itertools
import sys

import widgets
import file
import toolbar

if sys.platform == "win32":
    try:
        import ctypes
        PROCESS_SYSTEM_DPI_AWARE = 1
        shcore = ctypes.OleDLL("shcore")
        shcore.SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
    except (ImportError, AttributeError, OSError):
        pass

COUNTER = itertools.count().__next__
BASE = pathlib.Path()
SETTINGS = configparser.ConfigParser()
if (BASE / ".config").exists():
    SETTINGS.read(".config")
else:
    SETTINGS["default"] = {
        "current_directory": str(BASE.home()),
        "opened_files": [],
    }
示例#19
0
    def __init__(self, path, libtype=None, **kwargs):
        """Load a shared library.

        For example, a C/C++, FORTRAN, C#, Java, Delphi, LabVIEW, ActiveX, ... library.

        .. versionchanged:: 0.4
           Added support for Java archives.

        .. versionchanged:: 0.5
           Added support for COM_ libraries.

        .. versionchanged:: 0.9
           Added support for ActiveX_ libraries.

        .. _Assembly: https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly
        .. _comtypes.CreateObject: https://pythonhosted.org/comtypes/#creating-and-accessing-com-objects
        .. _COM: https://en.wikipedia.org/wiki/Component_Object_Model
        .. _ActiveX: https://en.wikipedia.org/wiki/ActiveX

        Parameters
        ----------
        path : :class:`str`
            The path to the shared library.

            The search order for finding the shared library is:

                1. assume that a full or a relative (to the current working directory)
                   path is specified,
                2. use :func:`ctypes.util.find_library` to find the shared library file,
                3. search :data:`sys.path`, then
                4. search :data:`os.environ['PATH'] <os.environ>` to find the shared library.

            If loading a COM_ library then `path` is either the `ProgID`, e.g.
            ``"InternetExplorer.Application"``, or the `CLSID`, e.g.
            ``"{2F7860A2-1473-4D75-827D-6C4E27600CAC}"``.

        libtype : :class:`str`, optional
            The library type. The following values are currently supported:

            * ``'cdll'`` -- for a library that uses the __cdecl calling convention
            * ``'windll'`` or ``'oledll'`` -- for a __stdcall calling convention
            * ``'net'`` or ``'clr'`` -- for Microsoft's .NET Framework (Common Language Runtime)
            * ``'java'`` -- for a Java archive, ``.jar``, or Java byte code, ``.class``, file
            * ``'com'`` -- for a COM_ library
            * ``'activex'`` -- for an ActiveX_ library

            Default is ``'cdll'``.

            .. tip::
               Since the ``.jar`` or ``.class`` extension uniquely defines a Java library,
               the `libtype` will be automatically set to ``'java'`` if `path` ends with
               ``.jar`` or ``.class``.

        **kwargs
            All additional keyword arguments are passed to the object that loads the library.

            If `libtype` is

                * ``'cdll'`` then :class:`~ctypes.CDLL`
                * ``'windll'`` then :class:`~ctypes.WinDLL`
                * ``'oledll'`` then :class:`~ctypes.OleDLL`
                * ``'net'`` or ``'clr'`` then all keyword arguments are ignored
                * ``'java'`` then :class:`~.py4j.java_gateway.JavaGateway`
                * ``'com'`` then comtypes.CreateObject_
                * ``'activex'`` then :meth:`Application.load <msl.loadlib.activex.Application.load>`

        Raises
        ------
        OSError
            If the shared library cannot be loaded.
        ValueError
            If the value of `libtype` is not supported.
        """
        # a reference to the shared library
        self._lib = None

        # a reference to the .NET Runtime Assembly
        self._assembly = None

        # a reference to the Py4J JavaGateway
        self._gateway = None

        if not path:
            raise ValueError(
                'You must specify the path, got {!r}'.format(path))

        # fixes Issue #8, if `path` is a <class 'pathlib.Path'> object
        if hasattr(path, 'as_posix'):
            path = path.as_posix()

        # try to automatically determine the libtype
        if libtype is None:
            if path.endswith('.jar') or path.endswith('.class'):
                libtype = 'java'
            else:
                libtype = 'cdll'
        else:
            libtype = libtype.lower()

        if libtype not in LoadLibrary.LIBTYPES:
            raise ValueError('Cannot load libtype={!r}.\n'
                             'Must be one of: {}'.format(
                                 libtype, ', '.join(LoadLibrary.LIBTYPES)))

        # create a new reference to `path` just in case the
        # DEFAULT_EXTENSION is appended below so that the
        # ctypes.util.find_library function call will use the
        # unmodified value of `path`
        _path = path

        # assume a default extension if no extension was provided
        ext = os.path.splitext(path)[1]
        if not ext and libtype not in ['java', 'com', 'activex']:
            _path += DEFAULT_EXTENSION

        if IS_PYTHON2:
            _path = _path.encode(_encoding)

        if libtype not in ['com', 'activex']:
            self._path = os.path.abspath(_path)
            if not os.path.isfile(self._path):
                # for find_library use the original 'path' value since it may be a library name
                # without any prefix like 'lib', suffix like '.so', '.dylib' or version number
                self._path = ctypes.util.find_library(path)
                if self._path is None:  # then search sys.path and os.environ['PATH']
                    success = False
                    search_dirs = sys.path + os.environ['PATH'].split(
                        os.pathsep)
                    for directory in search_dirs:
                        p = os.path.join(directory, _path)
                        if os.path.isfile(p):
                            self._path = p
                            success = True
                            break
                    if not success:
                        raise OSError(
                            "Cannot find '{}' for libtype='{}'".format(
                                path, libtype))
        else:
            self._path = _path

        if libtype == 'cdll':
            self._lib = ctypes.CDLL(self._path, **kwargs)
        elif libtype == 'windll':
            self._lib = ctypes.WinDLL(self._path, **kwargs)
        elif libtype == 'oledll':
            self._lib = ctypes.OleDLL(self._path, **kwargs)
        elif libtype == 'com':
            if not utils.is_comtypes_installed():
                raise OSError(
                    'Cannot load a COM library because comtypes is not installed.\n'
                    'Run: pip install comtypes')

            from comtypes import GUID
            from comtypes.client import CreateObject

            try:
                clsid = GUID.from_progid(self._path)
            except (TypeError, OSError):
                clsid = None

            if clsid is None:
                raise OSError(
                    "Cannot find '{}' for libtype='com'".format(path))

            self._lib = CreateObject(clsid, **kwargs)

        elif libtype == 'activex':
            from .activex import Application
            self._lib = Application.load(self._path, **kwargs)

        elif libtype == 'java':
            if not utils.is_py4j_installed():
                raise OSError(
                    'Cannot load a Java file because Py4J is not installed.\n'
                    'Run: pip install py4j')

            from py4j.version import __version__
            from py4j.java_gateway import JavaGateway, GatewayParameters

            # the address and port to use to host the py4j.GatewayServer
            address = kwargs.pop('address', '127.0.0.1')
            port = kwargs.pop('port', utils.get_available_port())

            # find the py4j*.jar file (needed to import the py4j.GatewayServer on the Java side)
            filename = 'py4j' + __version__ + '.jar'
            py4j_jar = os.environ.get('PY4J_JAR')
            if py4j_jar:
                if not os.path.isfile(
                        py4j_jar) or os.path.basename(py4j_jar) != filename:
                    raise OSError(
                        'A PY4J_JAR environment variable exists, '
                        'but the full path to the {} file is invalid\n'
                        'PY4J_JAR={}'.format(filename, py4j_jar))
            else:
                root = os.path.dirname(sys.executable)
                for item in [
                        root,
                        os.path.dirname(root),
                        os.path.join(os.path.expanduser('~'), '.local')
                ]:
                    py4j_jar = os.path.join(item, 'share', 'py4j', filename)
                    if os.path.isfile(py4j_jar):
                        break
                if not os.path.isfile(py4j_jar):
                    raise OSError(
                        'Cannot find {0}\nCreate a PY4J_JAR environment '
                        'variable to be equal to the full path to {0}'.format(
                            filename))

            # build the java command
            wrapper = os.path.join(os.path.dirname(__file__),
                                   'py4j-wrapper.jar')
            cmd = [
                'java', '-cp', py4j_jar + os.pathsep + wrapper, 'Py4JWrapper',
                str(port)
            ]

            # from the URLClassLoader documentation:
            #   Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL
            #   is assumed to refer to a JAR file which will be downloaded and opened as needed.
            if ext == '.jar':
                cmd.append(self._path)
            else:  # it is a .class file
                cmd.append(os.path.dirname(self._path) + '/')

            err = None
            try:
                # start the py4j.GatewayServer
                flags = 0x08000000 if IS_WINDOWS else 0  # fixes issue 31, CREATE_NO_WINDOW = 0x08000000
                subprocess.Popen(cmd,
                                 stderr=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 creationflags=flags)
            except OSError as e:
                err = str(e).rstrip()
                err += '\nYou must have a Java Runtime Environment installed and available on PATH'

            if err:
                raise OSError(err)

            try:
                utils.wait_for_server(address, port, 10.0)
            except OSError as e:
                err = str(e).rstrip()
                err += '\nCould not start the Py4J GatewayServer'

            if err:
                raise OSError(err)

            self._gateway = JavaGateway(gateway_parameters=GatewayParameters(
                address=address, port=port, **kwargs))

            self._lib = self._gateway.jvm

        elif libtype == 'net' or libtype == 'clr':
            if not utils.is_pythonnet_installed():
                raise OSError(
                    'Cannot load a .NET Assembly because pythonnet is not installed.\n'
                    'Run: pip install pythonnet')

            import clr
            import System
            dotnet = {'System': System}

            # the shared library must be available in sys.path
            head, tail = os.path.split(self._path)
            sys.path.insert(0, head)

            try:
                # don't include the library extension
                clr.AddReference(os.path.splitext(tail)[0])
            except (System.IO.FileNotFoundException,
                    System.IO.FileLoadException):
                # The file must exist since its existence is checked above.
                # There must be another reason why loading the DLL raises this
                # error. Calling LoadFile (below) provides more information
                # in the error message.
                pass

            try:
                # By default, pythonnet can only load libraries that are for .NET 4.0+
                #
                # In order to allow pythonnet to load a library from .NET <4.0 the
                # useLegacyV2RuntimeActivationPolicy property needs to be enabled
                # in a <python-executable>.config file. If the following statement
                # raises a FileLoadException then attempt to create the configuration
                # file that has the property enabled and then notify the user why
                # loading the library failed and ask them to re-run their Python
                # script to load the .NET library.
                self._assembly = System.Reflection.Assembly.LoadFile(
                    self._path)

            except System.IO.FileLoadException as err:
                # Example error message that can occur if the library is for .NET <4.0,
                # and the useLegacyV2RuntimeActivationPolicy is not enabled:
                #
                # " Mixed mode assembly is built against version 'v2.0.50727' of the
                #  runtime and cannot be loaded in the 4.0 runtime without additional
                #  configuration information. "
                if str(err).startswith(
                        'Mixed mode assembly is built against version'):
                    status, msg = utils.check_dot_net_config(sys.executable)
                    if not status == 0:
                        raise OSError(msg)
                    else:
                        update_msg = 'Checking .NET config returned "{}" '.format(
                            msg)
                        update_msg += 'and still cannot load library.\n'
                        update_msg += str(err)
                        raise OSError(update_msg)
                raise OSError(
                    'The above "System.IO.FileLoadException" is not handled.\n'
                )

            try:
                types = self._assembly.GetTypes()
            except Exception as e:
                utils.logger.error(e)
                utils.logger.error('The LoaderExceptions are:')
                for item in e.LoaderExceptions:
                    utils.logger.error('  ' + item.Message)
            else:
                for t in types:
                    try:
                        if t.Namespace:
                            obj = __import__(t.Namespace)
                        else:
                            obj = getattr(__import__('clr'), t.FullName)
                    except:
                        obj = t
                        obj.__name__ = t.FullName

                    if obj.__name__ not in dotnet:
                        dotnet[obj.__name__] = obj

            self._lib = DotNet(dotnet, self._path)

        else:
            assert False, 'Should not get here -- contact developers'

        if IS_PYTHON2:
            self._path = self._path.decode(_encoding)

        utils.logger.debug('Loaded ' + self._path)
示例#20
0
            basedir = tempfile.gettempdir()

        gen_dir = os.path.join(basedir, subdir)
        if not os.path.exists(gen_dir):
            logger.info("Creating writeable comtypes cache directory: '%s'",
                        gen_dir)
            os.makedirs(gen_dir)
        gen_path.append(gen_dir)
    result = os.path.abspath(gen_path[-1])
    logger.info("Using writeable comtypes cache directory: '%s'", result)
    return result


################################################################

SHGetSpecialFolderPath = ctypes.OleDLL("shell32.dll").SHGetSpecialFolderPathW
GetModuleFileName = ctypes.WinDLL("kernel32.dll").GetModuleFileNameW
SHGetSpecialFolderPath.argtypes = [
    ctypes.c_ulong, ctypes.c_wchar_p, ctypes.c_int, ctypes.c_int
]
GetModuleFileName.restype = ctypes.c_ulong
GetModuleFileName.argtypes = [ctypes.c_ulong, ctypes.c_wchar_p, ctypes.c_ulong]

CSIDL_APPDATA = 26
MAX_PATH = 260


def _create_comtypes_gen_package():
    """Import (creating it if needed) the comtypes.gen package."""
    try:
        import comtypes.gen
示例#21
0
文件: pysepia.py 项目: lsegui/smellie
# THIS SCRIPT SHOULD NOT BE ALTERED
import ctypes, sys, os, time, heapq

# Check the dll path is correct
dll_path = "C:\Users\LocalAdmin\Desktop\Pysepia\Sepia2_Lib.dll"

if (os.path.exists(dll_path) == True):
    print '\n PYSEPIA: The .dll path is correct \n'
else:
    sys.exit(
        '\n PYSEPIA: The .dll path is incorrect - please give the correct path for the Sepia2_Lib.dll file \n'
    )
print dll_path
#sepiadll = ctypes.WinDLL(dll_path)
sepiadll = ctypes.OleDLL(dll_path)


# Open the .dll library and returns the library's version number
def SEPIA2_LIB_GetVersion():
    cLibVersion = " "
    SEPIA2_LIB_GetVersion_Proto = ctypes.WINFUNCTYPE(ctypes.c_int,
                                                     ctypes.c_char_p)
    SEPIA2_LIB_GetVersion_Params = (1, "p1", 0),
    SEPIA2_LIB_GetVersion_API = SEPIA2_LIB_GetVersion_Proto(
        ("SEPIA2_LIB_GetVersion", sepiadll), SEPIA2_LIB_GetVersion_Params)
    p1 = ctypes.c_char_p(cLibVersion)
    SEPIA2_LIB_GetVersion_API(p1)
    return p1.value


def SEPIA2_LIB_DecodeError():
示例#22
0
        bytes = lambda x: str(buffer(x))

    from ctypes import wintypes
    from win32com.shell import shell, shellcon
    from win32com.propsys import propsys, pscon

    # KNOWNFOLDERID
    # https://msdn.microsoft.com/en-us/library/dd378457
    # win32com defines most of these, except the ones added in Windows 8.
    FOLDERID_AppsFolder = pywintypes.IID(
        "{1e87508d-89c2-42f0-8a7e-645a0f50ca58}")

    # win32com is missing SHGetKnownFolderIDList, so use ctypes.

    _ole32 = ctypes.OleDLL("ole32")
    _shell32 = ctypes.OleDLL("shell32")

    _REFKNOWNFOLDERID = ctypes.c_char_p
    _PPITEMIDLIST = ctypes.POINTER(ctypes.c_void_p)

    _ole32.CoTaskMemFree.restype = None
    _ole32.CoTaskMemFree.argtypes = (wintypes.LPVOID, )

    _shell32.SHGetKnownFolderIDList.argtypes = (
        _REFKNOWNFOLDERID,  # rfid
        wintypes.DWORD,  # dwFlags
        wintypes.HANDLE,  # hToken
        _PPITEMIDLIST,
    )  # ppidl
示例#23
0
# ctypes needed to convert parameters from python to C representation and vice versa
import ctypes as ct
from ctypes import wintypes as wt
from ctypes.util import find_library

import sys
import traceback
import daqxh              #definitions found in daqx.h

import numpy as np

#detect if OS is 64bit or 32bit; this code is a bit of a hack, but found no better solution
is_64bit = sys.maxsize > 2**32
if is_64bit:
    daq = ct.OleDLL("daqx64")  #load 64bit dll 'daqx64.dll'
else:
    daq = ct.OleDLL("daqx")    #load 32bit dll 'daqx.dll'

#
# assume enum types in header file are 32bit integers
#


#======================================================================
#
#Error Handling
#
#======================================================================

class IOTechLibraryBaseError( Exception ):