コード例 #1
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Windows implementation of local network interface enumeration.
"""

from socket import socket, AF_INET6, SOCK_STREAM
from ctypes import (WinDLL, byref, create_string_buffer, create_unicode_buffer,
                    c_int, c_void_p, POINTER, Structure, cast, wstring_at)

WS2_32 = WinDLL('ws2_32')

SOCKET = c_int
DWORD = c_int
LPVOID = c_void_p
LPSOCKADDR = c_void_p
LPWSAPROTOCOL_INFO = c_void_p
LPTSTR = c_void_p
LPDWORD = c_void_p
LPWSAOVERLAPPED = c_void_p
LPWSAOVERLAPPED_COMPLETION_ROUTINE = c_void_p

# http://msdn.microsoft.com/en-us/library/ms741621(v=VS.85).aspx
# int WSAIoctl(
#         __in   SOCKET s,
#         __in   DWORD dwIoControlCode,
#         __in   LPVOID lpvInBuffer,
#         __in   DWORD cbInBuffer,
#         __out  LPVOID lpvOutBuffer,
#         __in   DWORD cbOutBuffer,
#         __out  LPDWORD lpcbBytesReturned,
コード例 #2
0
 def __getattr__(self, name):
     library = WinDLL(name)
     self.__dict__[name] = library
     return library
コード例 #3
0
ファイル: common.py プロジェクト: rudresh2319/Xpra
# This file is part of Xpra.
# Copyright (C) 2017 Antoine Martin <*****@*****.**>
# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.

import ctypes

from ctypes import WinDLL, POINTER, WINFUNCTYPE, Structure, c_ulong, c_ushort, c_ubyte, c_int, c_long, c_void_p, c_size_t
from ctypes.wintypes import HWND, DWORD, WPARAM, LPARAM, HDC, HMONITOR, HMODULE, SHORT, ATOM, RECT, POINT
from ctypes.wintypes import HANDLE, LPCWSTR, UINT, INT, BOOL, HGDIOBJ, LONG, LPVOID, HBITMAP, LPCSTR, LPWSTR, HWINSTA

LRESULT = c_long
DEVMODE = c_void_p
LPDWORD = POINTER(DWORD)

kernel32 = WinDLL("kernel32", use_last_error=True)
SetConsoleTitleA = kernel32.SetConsoleTitleA
GetConsoleScreenBufferInfo = kernel32.GetConsoleScreenBufferInfo
GetModuleHandleA = kernel32.GetModuleHandleA
GetModuleHandleA.restype = HMODULE
SetConsoleCtrlHandler = kernel32.SetConsoleCtrlHandler
GetComputerNameW = kernel32.GetComputerNameW
GetComputerNameW.restype = BOOL
GetComputerNameW.argtypes = [LPWSTR, LPDWORD]
GetCurrentProcess = kernel32.GetCurrentProcess
GetCurrentProcess.restype = HANDLE
HeapAlloc = kernel32.HeapAlloc
HeapAlloc.restype = LPVOID
HeapAlloc.argtypes = [HANDLE, DWORD, c_size_t]
GetProcessHeap = kernel32.GetProcessHeap
GetProcessHeap.restype = HANDLE
コード例 #4
0
REINIT_VISIBLE_WINDOWS = envbool("XPRA_WIN32_REINIT_VISIBLE_WINDOWS", True)
SCREENSAVER_LISTENER_POLL_DELAY = envint(
    "XPRA_SCREENSAVER_LISTENER_POLL_DELAY", 10)
APP_ID = os.environ.get("XPRA_WIN32_APP_ID", "Xpra")

if PYTHON3:
    from ctypes import CDLL, pythonapi, c_void_p, py_object
    from ctypes.util import find_library
    PyCapsule_GetPointer = pythonapi.PyCapsule_GetPointer
    PyCapsule_GetPointer.restype = c_void_p
    PyCapsule_GetPointer.argtypes = [py_object]
    log("PyCapsute_GetPointer=%s", PyCapsule_GetPointer)
    gdkdll = CDLL(find_library("libgdk-3-0.dll"))
    log("gdkdll=%s", gdkdll)

shell32 = WinDLL("shell32", use_last_error=True)
try:
    from xpra.platform.win32.propsys import set_window_group  #@UnresolvedImport
except ImportError as e:
    log("propsys missing", exc_info=True)
    log.warn("Warning: propsys support missing:")
    log.warn(" %s", e)
    log.warn(" window grouping is not available")
    set_window_group = None

try:
    dwmapi = WinDLL("dwmapi", use_last_error=True)
    DwmGetWindowAttribute = dwmapi.DwmGetWindowAttribute
except:
    #win XP:
    DwmGetWindowAttribute = None
コード例 #5
0
ファイル: wechat.py プロジェクト: Bug-Maker/wechat_pc_api
class WeChatManager:
    # 加载器
    WXLOADER = None

    # wechatHelper.dll
    wxhelper_dll_path = ''

    # 可指定WeChat.exe路径,也可以设置为空
    wechat_exe_path = ''

    def __init__(self, libs_path, wechat_exe_path=''):
        self.wechat_exe_path = wechat_exe_path
        # 加载WxLoader.dll
        wechat_loader_path = os.path.join(
            libs_path,
            'WxLoader_{0}.dll'.format('x64' if is_64bit() else 'x86'))
        wechat_loader_path = os.path.realpath(wechat_loader_path)

        if not os.path.exists(wechat_loader_path):
            logger.error('libs path error or wechatLoader not exist: %s',
                         wechat_loader_path)
            return

        # 加载libs文件夹中的WxLoader.dll文件
        self.WXLOADER = WinDLL(wechat_loader_path)

        # 使用utf8编码
        self.WXLOADER.UseUtf8()

        # 初始化接口回调,调用WxLoader.dll的InitWeChatSocket接口
        self.WXLOADER.InitWeChatSocket(wechat_connect_callback,
                                       wechat_recv_callback,
                                       wechat_close_callback)

        # 加载WeChatHelper.dll(客户端程序,用于微信程序内部与外界通信,用于接收指令和消息通知)
        self.wxhelper_dll_path = '{0}/WeChatHelper_{1}.dll'.format(
            libs_path, self.get_user_wechat_version())
        if not os.path.exists(self.wxhelper_dll_path):
            logger.error('lib file:%s not exist', self.wxhelper_dll_path)
            return

        if wechat_exe_path != '' and not os.path.exists(wechat_exe_path):
            logger.warning('wechat.exe is the path set correctly?')

        self.wechat_exe_path = wechat_exe_path

    # 添加回溯句柄
    def add_callback_handler(self, callback_handler):
        add_callback_handler(callback_handler)

    # 调用WxLoader.GetUserWeChatVersion,获取当前用户的电脑上安装的微信版本
    @REQUIRE_WXLOADER()
    def get_user_wechat_version(self):
        out = create_string_buffer(20)
        self.WXLOADER.GetUserWeChatVersion(out)
        return out.value.decode('utf-8')

    # 调用WxLoader.InjectWeChat接口或者InjectWeChatMultiOpen接口,用于智能多开,并注入dll, 注入成功返回微信的进程ID, 失败返回0
    @REQUIRE_WXLOADER()
    def manager_wechat(self, smart=True):
        if smart:
            return self.WXLOADER.InjectWeChat2(
                c_string(self.wxhelper_dll_path),
                c_string(self.wechat_exe_path))
        else:
            return self.WXLOADER.InjectWeChatMultiOpen(
                c_string(self.wxhelper_dll_path),
                c_string(self.wechat_exe_path))

    # 调用WxLoader.InjectWeChatPid接口,注入指定的微信进程
    @REQUIRE_WXLOADER()
    def manager_wechat_by_pid(self, wechat_pid):
        return self.WXLOADER.InjectWeChatPid(wechat_pid,
                                             c_string(self.wxhelper_dll_path))

    # 调用WxLoader.DestroyWeChat接口,主程序退出前,执行释放函数,用于卸载DLL和关闭socket服务端
    @REQUIRE_WXLOADER()
    def close_manager(self):
        return self.WXLOADER.DestroyWeChat()

    # 调用WxLoader.SendWeChatData接口,用于向微信发送指令
    # 函数原型: BOOL SendWeChatData(IN CONNID dwClientId, IN LPCSTR szJsonData);
    @REQUIRE_WXLOADER()
    def send_message(self, client_id, message_type, params):
        send_data = {'type': message_type, 'data': params}
        return self.WXLOADER.SendWeChatData(client_id,
                                            c_string(json.dumps(send_data)))

    # 发送文本消息
    def send_text(self, client_id, to_wxid, text):
        data = {'to_wxid': to_wxid, 'content': text}
        return self.send_message(client_id, MessageType.MT_SEND_TEXTMSG, data)

    # 发送群at消息
    def send_chatroom_at_msg(self, client_id, to_wxid, content, at_list):
        data = {'to_wxid': to_wxid, 'content': content, 'at_list': at_list}
        return self.send_message(client_id, MessageType.MT_SEND_CHATROOM_ATMSG,
                                 data)

    # 发送名片
    def send_user_card(self, client_id, to_wxid, wxid):
        data = {'to_wxid': to_wxid, 'card_wxid': wxid}
        return self.send_message(client_id, MessageType.MT_SEND_CARDMSG, data)

    # 发送链接
    def send_link(self, client_id, to_wxid, title, desc, url, image_url):
        data = {
            'to_wxid': to_wxid,
            'title': title,
            'desc': desc,
            'url': url,
            'image_url': image_url
        }
        return self.send_message(client_id, MessageType.MT_SEND_LINKMSG, data)

    # 发送图片
    def send_image(self, client_id, to_wxid, file):
        data = {'to_wxid': to_wxid, 'file': file}
        return self.send_message(client_id, MessageType.MT_SEND_IMGMSG, data)

    # 发送文件
    def send_file(self, client_id, to_wxid, file):
        data = {'to_wxid': to_wxid, 'file': file}
        return self.send_message(client_id, MessageType.MT_SEND_FILEMSG, data)

    # 发送视频
    def send_video(self, client_id, to_wxid, file):
        data = {'to_wxid': to_wxid, 'file': file}
        return self.send_message(client_id, MessageType.MT_SEND_VIDEOMSG, data)

    # 发送gif
    def send_gif(self, client_id, to_wxid, file):
        data = {'to_wxid': to_wxid, 'file': file}
        return self.send_message(client_id, MessageType.MT_SEND_GIFMSG, data)

    # 获取所有联系人
    def get_friends(self, client_id):
        return self.send_message(client_id, MessageType.MT_DATA_FRIENDS_MSG,
                                 {})

    # 获取所有群组
    def get_chatrooms(self, client_id):
        return self.send_message(client_id, MessageType.MT_DATA_CHATROOMS_MSG,
                                 {})

    # 获取所有群成员
    def get_chatroom_members(self, client_id, room_wxid):
        data = {'room_wxid': room_wxid}
        return self.send_message(client_id,
                                 MessageType.MT_DATA_CHATROOM_MEMBERS_MSG,
                                 data)

    # 获取所有公众号
    def get_publics(self, client_id):
        return self.send_message(client_id, MessageType.MT_DATA_PUBLICS_MSG,
                                 {})
コード例 #6
0
ファイル: primitive.py プロジェクト: pombreda/pypy
    def __new__(self, name, bases, dct):
        try:
            tp = dct['_type_']
        except KeyError:
            for base in bases:
                if hasattr(base, '_type_'):
                    tp = base._type_
                    break
            else:
                raise AttributeError("cannot find _type_ attribute")
        if (not isinstance(tp, str) or not len(tp) == 1
                or tp not in SIMPLE_TYPE_CHARS):
            raise ValueError('%s is not a type character' % (tp))
        default = TP_TO_DEFAULT[tp]
        ffiarray = _rawffi.Array(tp)
        result = type.__new__(self, name, bases, dct)
        result._ffiargshape = tp
        result._ffishape = tp
        result._fficompositesize = None
        result._ffiarray = ffiarray
        if tp == 'z':
            # c_char_p
            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                else:
                    return _rawffi.charp2string(addr)

            def _setvalue(self, value):
                if isinstance(value, basestring):
                    if isinstance(value, unicode):
                        value = value.encode(ConvMode.encoding,
                                             ConvMode.errors)
                    #self._objects = value
                    array = _rawffi.Array('c')(len(value) + 1, value)
                    self._objects = CArgObject(value, array)
                    value = array.buffer
                elif value is None:
                    value = 0
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)
            result._ffiargtype = _ffi.types.Pointer(_ffi.types.char)

        elif tp == 'Z':
            # c_wchar_p
            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                else:
                    return _rawffi.wcharp2unicode(addr)

            def _setvalue(self, value):
                if isinstance(value, basestring):
                    if isinstance(value, str):
                        value = value.decode(ConvMode.encoding,
                                             ConvMode.errors)
                    #self._objects = value
                    array = _rawffi.Array('u')(len(value) + 1, value)
                    self._objects = CArgObject(value, array)
                    value = array.buffer
                elif value is None:
                    value = 0
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)
            result._ffiargtype = _ffi.types.Pointer(_ffi.types.unichar)

        elif tp == 'P':
            # c_void_p

            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                return addr

            def _setvalue(self, value):
                if isinstance(value, str):
                    array = _rawffi.Array('c')(len(value) + 1, value)
                    self._objects = CArgObject(value, array)
                    value = array.buffer
                elif value is None:
                    value = 0
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)

        elif tp == 'u':

            def _setvalue(self, val):
                if isinstance(val, str):
                    val = val.decode(ConvMode.encoding, ConvMode.errors)
                # possible if we use 'ignore'
                if val:
                    self._buffer[0] = val

            def _getvalue(self):
                return self._buffer[0]

            result.value = property(_getvalue, _setvalue)

        elif tp == 'c':

            def _setvalue(self, val):
                if isinstance(val, unicode):
                    val = val.encode(ConvMode.encoding, ConvMode.errors)
                if val:
                    self._buffer[0] = val

            def _getvalue(self):
                return self._buffer[0]

            result.value = property(_getvalue, _setvalue)

        elif tp == 'O':

            def _setvalue(self, val):
                num = pyobj_container.add(val)
                self._buffer[0] = num

            def _getvalue(self):
                return pyobj_container.get(self._buffer[0])

            result.value = property(_getvalue, _setvalue)

        elif tp == 'X':
            from ctypes import WinDLL
            # Use WinDLL("oleaut32") instead of windll.oleaut32
            # because the latter is a shared (cached) object; and
            # other code may set their own restypes. We need out own
            # restype here.
            oleaut32 = WinDLL("oleaut32")
            SysAllocStringLen = oleaut32.SysAllocStringLen
            SysStringLen = oleaut32.SysStringLen
            SysFreeString = oleaut32.SysFreeString

            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                else:
                    size = SysStringLen(addr)
                    return _rawffi.wcharp2rawunicode(addr, size)

            def _setvalue(self, value):
                if isinstance(value, basestring):
                    if isinstance(value, str):
                        value = value.decode(ConvMode.encoding,
                                             ConvMode.errors)
                    array = _rawffi.Array('u')(len(value) + 1, value)
                    value = SysAllocStringLen(array.buffer, len(value))
                elif value is None:
                    value = 0
                if self._buffer[0]:
                    SysFreeString(self._buffer[0])
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)

        elif tp == '?':  # regular bool

            def _getvalue(self):
                return bool(self._buffer[0])

            def _setvalue(self, value):
                self._buffer[0] = bool(value)

            result.value = property(_getvalue, _setvalue)

        elif tp == 'v':  # VARIANT_BOOL type

            def _getvalue(self):
                return bool(self._buffer[0])

            def _setvalue(self, value):
                if value:
                    self._buffer[0] = -1  # VARIANT_TRUE
                else:
                    self._buffer[0] = 0  # VARIANT_FALSE

            result.value = property(_getvalue, _setvalue)

        # make pointer-types compatible with the _ffi fast path
        if result._is_pointer_like():

            def _as_ffi_pointer_(self, ffitype):
                return as_ffi_pointer(self, ffitype)

            result._as_ffi_pointer_ = _as_ffi_pointer_

        return result
コード例 #7
0
 def __init__(self, pathToDLL):
     self.dll = WinDLL(pathToDLL)
コード例 #8
0
from ctypes import c_bool, c_char_p, c_double, c_float, c_int, c_uint, c_ulong, c_void_p, POINTER

import sys

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

    from ctypes import WinDLL

    _libGL = WinDLL('opengl32')

else:
    raise NotImplementedError

# Data types for OpenGL

GLbitfield = c_uint
GLubyte = c_char_p
GLclampf = c_float
GLclampd = c_double
GLdouble = c_double
GLenum = c_uint
GLfloat = c_float
GLint = c_int

GL_BLEND = 0x0BE2
GL_COLOR_BUFFER_BIT = 0x00004000
GL_DEPTH_BUFFER_BIT = 0x00000100
GL_DEPTH_TEST = 0x0B71
GL_MODELVIEW = 0x1700
GL_ONE_MINUS_SRC_ALPHA = 0x0303
GL_PROJECTION = 0x1701
コード例 #9
0
CRYPTPROTECT_PROMPT_ON_UNPROTECT = 1
CRYPTPROTECT_PROMPT_ON_PROTECT = 2

# Flags for CryptProtectData/CryptUnprotectData

CRYPTPROTECT_UI_FORBIDDEN = 0x01
CRYPTPROTECT_LOCAL_MACHINE = 0x04
CRYPTPROTECT_CRED_SYNC = 0x08
CRYPTPROTECT_AUDIT = 0x10
CRYPTPROTECT_NO_RECOVERY = 0x20
CRYPTPROTECT_VERIFY_PROTECTION = 0x40
CRYPTPROTECT_CRED_REGENERATE = 0x80

# Crypto API Functions

_dll = WinDLL('CRYPT32.DLL')

CryptProtectData = WINFUNCTYPE(wintypes.BOOL,
                               POINTER(DATA_BLOB),
                               POINTER(wintypes.WCHAR),
                               POINTER(DATA_BLOB),
                               c_void_p,
                               POINTER(CRYPTPROTECT_PROMPTSTRUCT),
                               wintypes.DWORD,
                               POINTER(DATA_BLOB))(('CryptProtectData', _dll))

CryptUnprotectData = WINFUNCTYPE(wintypes.BOOL,
                                 POINTER(DATA_BLOB),
                                 POINTER(wintypes.WCHAR),
                                 POINTER(DATA_BLOB),
                                 c_void_p,
コード例 #10
0
ファイル: amscope.py プロジェクト: Brow71189/PyAmScope
class Toupcam:
    def __init__(self, buffer=None):
        # Check operating system and load library
        # for Windows
        self.driver_path = os.path.join(str(Path.home()), 'PyAmScope')
        if platform.system() == "Windows":
            from ctypes import WinDLL
            self.is_windows = True
            self.dll = WinDLL(os.path.join(self.driver_path, 'toupcam.dll'))

        # for Linux
        elif platform.system() == "Linux":
            self.is_windows = False
            self.dll = cdll.LoadLibrary(os.path.join(self.driver_path, 'libtoupcam.so'))
            #self.dll = DummyDLL(self)
        else:
            logging.error("Cannot detect operating system, wil now stop")
            raise

        self.verbosity   = False
        #self.dll.Initialize.argtypes = [c_char_p]
        #self.dll.Initialize.restype = c_uint32
        self.buffer = buffer or Buffer(maxsize=10)
        self.cam = None
        #assert error == 'DRV_SUCCESS', str(error)
#        if error != 'DRV_SUCCESS':
#            raise RuntimeError(error)
        self.Toupcam_Open()
        # set maximum auto exposure time to 2s
        self.Toupcam_put_MaxAutoExpoTimeAGain(2000000, 500)
        
    def Toupcam_Open(self):
        class myPythonAPI(Structure):
            pass

        PmyPythonAPI = POINTER(myPythonAPI)

        self.dll.Toupcam_Open.restype = PmyPythonAPI
        
        self.cam = self.dll.Toupcam_Open(None)
        if not self.cam:
            logging.warn('Unable to open connection to camera.')
        
    def Toupcam_Close(self):
        if self.cam:
            self.dll.Toupcam_Close(self.cam)
            self.cam = None
    
    def Toupcam_StartPullModeWithCallback(self, callback_function):
        if self.cam:
            self.Toupcam_get_Size()
            prototype = CFUNCTYPE(None, c_uint)
            self.callback_ref = prototype(callback_function)
            self.string_buffer = create_string_buffer(10000)
            res = self.dll.Toupcam_StartPullModeWithCallback(self.cam,
                                                             self.callback_ref,
                                                             self.string_buffer)
    
    def Toupcam_PullImage(self):
        if self.cam:
            # get image heigth and width
            width = c_uint()
            height = c_uint()
#            res = self.dll.Toupcam_PullImage(self.cam,
#                                             None,
#                                             c_int(24),
#                                             c_int(0),
#                                             byref(width),
#                                             byref(height))
#            print('width, height:', width.value, height.value)
            dim = int(self.width * self.height * 3)
            rawimageArray = np.empty(dim, dtype=np.uint8)
            cimage = rawimageArray.ctypes.data_as(POINTER(c_uint))
            res = self.dll.Toupcam_PullImage(self.cam,
                                             cimage,
                                             c_int(24),
                                             c_int(0),
                                             byref(width),
                                             byref(height))
            rawimageArray = rawimageArray.reshape((self.height, self.width, 3))
            #rawimageArray = np.moveaxis(rawimageArray, 1, -1)
            self.buffer.put(rawimageArray)
            
    def Toupcam_Stop(self):
        if self.cam:
            res = self.dll.Toupcam_Stop(self.cam)
            
    def Toupcam_get_Size(self):
        if self.cam:
            width = c_int()
            height = c_int()
            
            self.dll.Toupcam_get_Size(self.cam, byref(width), byref(height))
            self.width = width.value
            self.height = height.value
    
    def Toupcam_get_ExpoTime(self):
        if self.cam:
            exp_time = c_uint()
            res = self.dll.Toupcam_get_ExpoTime(self.cam, byref(exp_time))
            return exp_time.value
        
    def Toupcam_put_MaxAutoExpoTimeAGain(self, max_time, max_a_gain):
        if self.cam:
            c_max_time = c_uint(max_time)
            c_max_a_gain = c_ushort(max_a_gain)
            res = self.dll.Toupcam_put_MaxAutoExpoTimeAGain(self.cam, c_max_time, c_max_a_gain)
            
    def callback_function(self, eventID):
        if eventID == TOUPCAM_EVENT_IMAGE:
            self.Toupcam_PullImage()
            
    def start_live(self):
        if not self.is_windows:
            exposure_time = self.Toupcam_get_ExpoTime()
            self.stop_event = threading.Event()
            def call_callback():
                while not self.stop_event.wait(exposure_time/1e6):
                    self.callback_function(TOUPCAM_EVENT_IMAGE)
            self.callback_thread = threading.Thread(target=call_callback)
        self.Toupcam_StartPullModeWithCallback(self.callback_function)
        if not self.is_windows:
                self.callback_thread.start()
    
    def stop_live(self):
        self.Toupcam_Stop()
        if not self.is_windows:
            self.stop_event.set()
            self.callback_thread.join(1)
コード例 #11
0
tobii_stream_engine = 'tobii_stream_engine.dll'


class tobii_gaze_point_t(Structure):
    _fields_ = [('timestamp_us', c_longlong), ('validity', c_int),
                ('position_xy', c_float * 2)]


class tobii_gaze_origin_t(Structure):
    _fields_ = [('timestamp_us', c_longlong), ('left_validity', c_int),
                ('left_xyz', c_float * 3), ('right_validity', c_int),
                ('right_xyz', c_float * 3)]


tse_dll = WinDLL(tobii_stream_engine)

tobii_api_create = tse_dll.tobii_api_create
tobii_api_create.argtypes = [POINTER(c_void_p), c_int, c_int]
tobii_api_create.restype = c_int

tobii_api_destroy = tse_dll.tobii_api_destroy
tobii_api_destroy.argtypes = [c_void_p]
tobii_api_destroy.restype = c_int

tobii_device_create = tse_dll.tobii_device_create
tobii_device_create.argtypes = [c_void_p, c_char_p, POINTER(c_void_p)]
tobii_device_create.restype = c_int

tobii_device_destroy = tse_dll.tobii_device_destroy
tobii_device_destroy.argtypes = [c_void_p]
コード例 #12
0
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import ctypes
from ctypes import WinDLL, CDLL, wintypes


shell32 = WinDLL("shell32")
kernel32 = WinDLL("kernel32")
shlwapi = WinDLL("shlwapi")
msvcrt = CDLL("msvcrt")

GetCommandLineW = kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = wintypes.LPCWSTR

CommandLineToArgvW = shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [
    wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)]
CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)

LocalFree = kernel32.LocalFree
LocalFree.argtypes = [wintypes.HLOCAL]
コード例 #13
0
# brailleViewer.py
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2019 NV Access Limited
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
from typing import List

from logHandler import log
import os
from ctypes import WinDLL
gdi32 = WinDLL("gdi32.dll")
"""
Loads custom fonts for use in NVDA.
"""

fontsDir = os.path.abspath("fonts")


def _isSupportedFontPath(f: str) -> bool:
	return os.path.isfile(f) and (
		f.endswith(".otf")
		or f.endswith(".ttf")
	)


def addFonts(_fontSearchPath) -> List[str]:
	searchPathFiles = [
		os.path.join(_fontSearchPath, f)
		for f in os.listdir(_fontSearchPath)
	]
	fonts = [
コード例 #14
0
logger = get_logger(__name__)


def _errcheck(is_error_result=(lambda result: not result)):
    def impl(result, func, args):
        # pylint: disable=unused-argument
        if is_error_result(result):
            raise WinError()

        return result

    return impl


# Win32 CreateJobObject
kernel32 = WinDLL("kernel32")
kernel32.CreateJobObjectW.errcheck = _errcheck(lambda result: result == 0)
kernel32.CreateJobObjectW.argtypes = (LPVOID, LPCWSTR)
kernel32.CreateJobObjectW.restype = HANDLE

# Win32 OpenProcess
PROCESS_TERMINATE = 0x0001
PROCESS_SET_QUOTA = 0x0100
PROCESS_SYNCHRONIZE = 0x00100000
kernel32.OpenProcess.errcheck = _errcheck(lambda result: result == 0)
kernel32.OpenProcess.restype = HANDLE
kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)

# Win32 WaitForSingleObject
INFINITE = 0xFFFFFFFF
# kernel32.WaitForSingleObject.errcheck = _errcheck()
コード例 #15
0
ファイル: libgdal.py プロジェクト: Myxir20/django
if lib_path is None:
    raise OGRException('Could not find the GDAL library (tried "%s"). '
                       'Try setting GDAL_LIBRARY_PATH in your settings.' %
                       '", "'.join(lib_names))

# This loads the GDAL/OGR C library
lgdal = CDLL(lib_path)

# On Windows, the GDAL binaries have some OSR routines exported with
# STDCALL, while others are not.  Thus, the library will also need to
# be loaded up as WinDLL for said OSR functions that require the
# different calling convention.
if os.name == 'nt':
    from ctypes import WinDLL
    lwingdal = WinDLL(lib_path)


def std_call(func):
    """
    Returns the correct STDCALL function for certain OSR routines on Win32
    platforms.
    """
    if os.name == 'nt':
        return lwingdal[func]
    else:
        return lgdal[func]


#### Version-information functions. ####
コード例 #16
0
ファイル: soundmod.py プロジェクト: TFB-code/Soundmod
## Soundmod, Copyright (c) 2021 TFB
## Use freely under zlib terms, see licence file.

from ctypes import WinDLL, c_buffer

global winmm
winmm=WinDLL('winmm.dll')

global aliasnum
aliasnum=0

class vl :
    off=0x00000000
    low=0x55555555
    mid=0x99999999
    high=0xCCCCCCCC
    full=0xFFFFFFFF

class sf :
    _sync=0
    _async=1
    _nodefault=2
    _memory=4
    _loop=8
    _nostop=16
    _nowait=8192
    _fromfile=131072

def buildwavheader(datasize=176400, samplerate=44100, channels=2, bps=16) :         # datasize of 176400 = 1 second of 16 bit stereo PCM audio
    header=bytes
    header=b'RIFF'
コード例 #17
0
"""Get Unicode argv strings in Python 2 on Windows

get_full_unicode_argv based on
http://code.activestate.com/recipes/572200/

argv_setter_hook based on
https://mail.python.org/pipermail/python-list/2016-June/710183.html
"""

import sys
from ctypes import WinDLL, c_int, POINTER, byref
from ctypes.wintypes import LPCWSTR, LPWSTR

kernel32 = WinDLL("kernel32", use_last_error=True)
shell32 = WinDLL("shell32", use_last_error=True)

GetCommandLineW = kernel32.GetCommandLineW
GetCommandLineW.argtypes = ()
GetCommandLineW.restype = LPCWSTR

CommandLineToArgvW = shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = (LPCWSTR, POINTER(c_int))
CommandLineToArgvW.restype = POINTER(LPWSTR)

LocalFree = kernel32.LocalFree


def get_full_unicode_argv():
	cmd = GetCommandLineW()
	argc = c_int(0)
	argv = CommandLineToArgvW(cmd, byref(argc))
コード例 #18
0
    for_seed, bound, x, y, target = [
        int(x) for x in input('Enter five integers: ').split()
    ]
    if bound < 1 or x not in range(10) or y not in range(10) or target < 0:
        raise ValueError
except ValueError:
    print('Incorrect input, giving up.')
    sys.exit()
seed(for_seed)
grid = [[randrange(bound) for _ in range(10)] for _ in range(10)]
print('Here is the grid that has been generated:')
display_grid()

dll_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        "pydll.dll")
dfsdll = WinDLL(dll_path)
dfsdll.DFS.restype = None
grid_arr = (c_int * 10) * 10
dfsdll.DFS.argtypes = [
    c_char_p,
    POINTER(grid_arr),
    POINTER(c_int),
    POINTER(c_int),
    POINTER(c_int)
]
c_grid = grid_arr()
for j in range(10):
    for i in range(10):
        c_grid[j][i] = grid[j][i]
c_x = c_int(x)
c_y = c_int(y)
コード例 #19
0
ファイル: pdfium.py プロジェクト: DiGuoZhiMeng/Xpra
# later version. See the file COPYING for details.

import os
import sys

from xpra.util import repr_ellipsized
from xpra.os_util import strtobytes
from xpra.platform.win32.common import GetDeviceCaps
from xpra.platform.win32 import win32con
from xpra.platform.win32.win32_printing import GDIPrinterContext, DOCINFO, StartDocA, EndDoc, LPCSTR
from ctypes.wintypes import HDC
from ctypes import WinDLL, c_void_p, Structure, c_int, c_uint, c_ulong, c_char_p, cast, pointer, POINTER

LIBPDFIUMDLL = os.environ.get("XPRA_LIBPDFIUMDLL", "libpdfium.dll")
try:
	pdfium = WinDLL(LIBPDFIUMDLL, use_last_error=True)
except WindowsError as e:		#@UndefinedVariable
	raise ImportError("cannot load %s: %s" % (LIBPDFIUMDLL, e))

class FPDF_LIBRARY_CONFIG(Structure):
	_fields_ = [
		("m_pUserFontPaths",	c_void_p),
		("version",				c_int),
		("m_pIsolate",			c_void_p),
		("m_v8EmbedderSlot",	c_uint),
		]

FPDF_DOCUMENT = c_void_p
FPDF_PAGE = c_void_p

FPDF_DestroyLibrary = pdfium.FPDF_DestroyLibrary
コード例 #20
0
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with EventGhost. If not, see <http://www.gnu.org/licenses/>.

from ctypes import byref, c_int, c_void_p, GetLastError, POINTER, WinDLL
from ctypes.wintypes import BOOL, DWORD, HANDLE, HWND, LPWSTR

# Local imports
import eg

PVOID = c_void_p
LPTSTR = LPWSTR

_WtsApi32 = WinDLL("WtsApi32")

WTSRegisterSessionNotification = _WtsApi32.WTSRegisterSessionNotification
WTSRegisterSessionNotification.restype = BOOL
WTSRegisterSessionNotification.argtypes = [HWND, DWORD]
WTSUserName = 5
WTSFreeMemory = _WtsApi32.WTSFreeMemory
WTSFreeMemory.restype = None
WTSFreeMemory.argtypes = [PVOID]
WTSUnRegisterSessionNotification = _WtsApi32.WTSUnRegisterSessionNotification
WTSUnRegisterSessionNotification.restype = BOOL
WTSUnRegisterSessionNotification.argtypes = [HWND]
WTS_CURRENT_SERVER_HANDLE = 0  # Variable c_void_p
NOTIFY_FOR_ALL_SESSIONS = 1  # Variable c_int

# values for enumeration '_WTS_INFO_CLASS'
コード例 #21
0
"""
import os
import glob

if os.name == "nt":
    # convention for storing / loading the DLL from
    # numpy/.libs/, if present
    try:
        from ctypes import WinDLL

        basedir = os.path.dirname(__file__)
    except:
        pass
    else:
        libs_dir = os.path.abspath(os.path.join(basedir, ".libs"))
        DLL_filenames = []
        if os.path.isdir(libs_dir):
            for filename in glob.glob(os.path.join(libs_dir, "*openblas*dll")):
                # NOTE: would it change behavior to load ALL
                # DLLs at this path vs. the name restriction?
                WinDLL(os.path.abspath(filename))
                DLL_filenames.append(filename)
        if len(DLL_filenames) > 1:
            import warnings

            warnings.warn(
                "loaded more than 1 DLL from .libs:"
                "\n%s" % "\n".join(DLL_filenames),
                stacklevel=1,
            )
コード例 #22
0
ファイル: common.py プロジェクト: gitmirrors2/xpra
        ]
class _inner_union(Union):
    _fields_  = [
        ('anon_struct', _inner_struct),
        ('Pointer',     c_void_p),
        ]
class OVERLAPPED(Structure):
    _fields_ = [
        ('Internal',        POINTER(ULONG)),
        ('InternalHigh',    POINTER(ULONG)),
        ('union',           _inner_union),
        ('hEvent',          HANDLE),
        ]
LPOVERLAPPED = POINTER(OVERLAPPED)

kernel32 = WinDLL("kernel32", use_last_error=True)
WaitForSingleObject = kernel32.WaitForSingleObject
WaitForSingleObject.argtypes = [HANDLE, DWORD]
WaitForSingleObject.restype = DWORD
CreateEventA = kernel32.CreateEventA
CreateEventA.restype = HANDLE
SetEvent = kernel32.SetEvent
SetEvent.argtypes = [HANDLE]
SetEvent.restype = BOOL
ReadFile = kernel32.ReadFile
ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED]
ReadFile.restype = BOOL
WriteFile = kernel32.WriteFile
WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED]
WriteFile.restype = BOOL
CreateFileA = kernel32.CreateFileA
コード例 #23
0
def _readlink(path):
    # Read https://eklausmeier.wordpress.com/2015/10/27/working-with-windows-junctions-in-python/
    """
    Read the target link

    Args

        link (string):
            link to read the target

    Returns

        string:
            target of the link
    """
    kernel32 = WinDLL("kernel32")
    LPDWORD = POINTER(DWORD)
    UCHAR = c_ubyte

    GetFileAttributesW = kernel32.GetFileAttributesW
    GetFileAttributesW.restype = DWORD
    GetFileAttributesW.argtypes = (LPCWSTR, )  # lpFileName In

    INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
    FILE_ATTRIBUTE_REPARSE_POINT = 0x00400

    CreateFileW = kernel32.CreateFileW
    CreateFileW.restype = HANDLE
    CreateFileW.argtypes = (
        LPCWSTR,  # lpFileName In
        DWORD,  # dwDesiredAccess In
        DWORD,  # dwShareMode In
        LPVOID,  # lpSecurityAttributes In_opt
        DWORD,  # dwCreationDisposition In
        DWORD,  # dwFlagsAndAttributes In
        HANDLE,
    )  # hTemplateFile In_opt

    CloseHandle = kernel32.CloseHandle
    CloseHandle.restype = BOOL
    CloseHandle.argtypes = (HANDLE, )  # hObject In

    INVALID_HANDLE_VALUE = HANDLE(-1).value
    OPEN_EXISTING = 3
    FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
    FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000

    DeviceIoControl = kernel32.DeviceIoControl
    DeviceIoControl.restype = BOOL
    DeviceIoControl.argtypes = (
        HANDLE,  # hDevice In
        DWORD,  # dwIoControlCode In
        LPVOID,  # lpInBuffer In_opt
        DWORD,  # nInBufferSize In
        LPVOID,  # lpOutBuffer Out_opt
        DWORD,  # nOutBufferSize In
        LPDWORD,  # lpBytesReturned Out_opt
        LPVOID,
    )  # lpOverlapped Inout_opt

    FSCTL_GET_REPARSE_POINT = 0x000900A8
    IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
    IO_REPARSE_TAG_SYMLINK = 0xA000000C
    MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 0x4000

    class GENERIC_REPARSE_BUFFER(Structure):
        _fields_ = (("DataBuffer", UCHAR * 1), )

    class SYMBOLIC_LINK_REPARSE_BUFFER(Structure):
        _fields_ = (
            ("SubstituteNameOffset", USHORT),
            ("SubstituteNameLength", USHORT),
            ("PrintNameOffset", USHORT),
            ("PrintNameLength", USHORT),
            ("Flags", ULONG),
            ("PathBuffer", WCHAR * 1),
        )

        @property
        def PrintName(self):
            arrayt = WCHAR * (self.PrintNameLength // 2)
            offset = type(self).PathBuffer.offset + self.PrintNameOffset
            return arrayt.from_address(addressof(self) + offset).value

    class MOUNT_POINT_REPARSE_BUFFER(Structure):
        _fields_ = (
            ("SubstituteNameOffset", USHORT),
            ("SubstituteNameLength", USHORT),
            ("PrintNameOffset", USHORT),
            ("PrintNameLength", USHORT),
            ("PathBuffer", WCHAR * 1),
        )

        @property
        def PrintName(self):
            arrayt = WCHAR * (self.PrintNameLength // 2)
            offset = type(self).PathBuffer.offset + self.PrintNameOffset
            return arrayt.from_address(addressof(self) + offset).value

    class REPARSE_DATA_BUFFER(Structure):
        class REPARSE_BUFFER(Union):
            _fields_ = (
                ("SymbolicLinkReparseBuffer", SYMBOLIC_LINK_REPARSE_BUFFER),
                ("MountPointReparseBuffer", MOUNT_POINT_REPARSE_BUFFER),
                ("GenericReparseBuffer", GENERIC_REPARSE_BUFFER),
            )

        _fields_ = (
            ("ReparseTag", ULONG),
            ("ReparseDataLength", USHORT),
            ("Reserved", USHORT),
            ("ReparseBuffer", REPARSE_BUFFER),
        )
        _anonymous_ = ("ReparseBuffer", )

    def islink(path):
        result = GetFileAttributesW(path)
        if result == INVALID_FILE_ATTRIBUTES:
            raise WinError()
        return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)

    def readlink(path):
        reparse_point_handle = CreateFileW(
            path,
            0,
            0,
            None,
            OPEN_EXISTING,
            FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
            None,
        )
        if reparse_point_handle == INVALID_HANDLE_VALUE:
            raise WinError()
        target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
        n_bytes_returned = DWORD()
        io_result = DeviceIoControl(
            reparse_point_handle,
            FSCTL_GET_REPARSE_POINT,
            None,
            0,
            target_buffer,
            len(target_buffer),
            byref(n_bytes_returned),
            None,
        )
        CloseHandle(reparse_point_handle)
        if not io_result:
            raise WinError()
        rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
        if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
            return rdb.SymbolicLinkReparseBuffer.PrintName
        elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
            return rdb.MountPointReparseBuffer.PrintName
        raise ValueError("not a link")

    return readlink(path)
コード例 #24
0
'''
Helper to preload the OpenMP dll to prevent "dll not found"
errors.
Once a DLL is preloaded, its namespace is made available to any
subsequent DLL. This file originated in the scikit-learn-wheels
github repo, and is created as part of the scripts that build the
wheel.
'''
import os
import os.path as op
from ctypes import WinDLL

if os.name == 'nt':
    # Pre-load the DLL stored in sklearn/.libs by convention.
    dll_path = op.join(op.dirname(__file__), '.libs', 'vcomp140.dll')
    WinDLL(op.abspath(dll_path))
コード例 #25
0
ファイル: win32.py プロジェクト: leileigong/pyserial
# (C) 2001-2015 Chris Liechti <*****@*****.**>
#
# SPDX-License-Identifier:    BSD-3-Clause

# pylint: disable=invalid-name,too-few-public-methods,protected-access,too-many-instance-attributes

from ctypes import c_ulong, c_void_p, c_int64, c_char, \
                   WinDLL, sizeof, Structure, Union, POINTER
from ctypes.wintypes import HANDLE
from ctypes.wintypes import BOOL
from ctypes.wintypes import LPCWSTR
from ctypes.wintypes import DWORD
from ctypes.wintypes import WORD
from ctypes.wintypes import BYTE
_stdcall_libraries = {}
_stdcall_libraries['kernel32'] = WinDLL('kernel32')

INVALID_HANDLE_VALUE = HANDLE(-1).value


# some details of the windows API differ between 32 and 64 bit systems..
def is_64bit():
    """Returns true when running on a 64 bit system"""
    return sizeof(c_ulong) != sizeof(c_void_p)

# ULONG_PTR is a an ordinary number, not a pointer and contrary to the name it
# is either 32 or 64 bits, depending on the type of windows...
# so test if this a 32 bit windows...
if is_64bit():
    ULONG_PTR = c_int64
else:
コード例 #26
0
        if check_error_cmd(result):
            raise UcanCmdError(result, func, arguments)
        else:
            raise UcanError(result, func, arguments)
    return result


if os.name != "nt":
    log.warning("SYSTEC ucan library does not work on %s platform.",
                sys.platform)
else:
    from ctypes import WinDLL

    try:
        # Select the proper dll architecture
        lib = WinDLL('usbcan64.dll' if sys.maxsize > 2**32 else 'usbcan32.dll')

        # BOOL PUBLIC UcanSetDebugMode (DWORD dwDbgLevel_p, _TCHAR* pszFilePathName_p, DWORD dwFlags_p);
        UcanSetDebugMode = lib.UcanSetDebugMode
        UcanSetDebugMode.restype = BOOL
        UcanSetDebugMode.argtypes = [DWORD, LPWSTR, DWORD]

        # DWORD PUBLIC UcanGetVersionEx (VersionType VerType_p);
        UcanGetVersionEx = lib.UcanGetVersionEx
        UcanGetVersionEx.restype = DWORD
        UcanGetVersionEx.argtypes = [VersionType]

        # DWORD PUBLIC UcanGetFwVersion (Handle UcanHandle_p);
        UcanGetFwVersion = lib.UcanGetFwVersion
        UcanGetFwVersion.restype = DWORD
        UcanGetFwVersion.argtypes = [Handle]
コード例 #27
0
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import errno

from ctypes import WinDLL, get_last_error, FormatError, WinError, addressof
from ctypes import c_buffer, c_ubyte, Structure, Union, byref
from ctypes.wintypes import BOOL, BOOLEAN, LPCWSTR, DWORD, HANDLE
from ctypes.wintypes import WCHAR, USHORT, LPVOID, ULONG, LPDWORD

kernel32 = WinDLL('kernel32', use_last_error=True)

UCHAR = c_ubyte

# Win32 error codes
ERROR_SUCCESS = 0
ERROR_NOT_SUPPORTED = 50
ERROR_PRIVILEGE_NOT_HELD = 1314

# Win32 API entry points
CreateSymbolicLinkW = kernel32.CreateSymbolicLinkW
CreateSymbolicLinkW.restype = BOOLEAN
CreateSymbolicLinkW.argtypes = (
    LPCWSTR,  # lpSymlinkFileName In
    LPCWSTR,  # lpTargetFileName In
    DWORD)  # dwFlags In
コード例 #28
0

class COORD(Structure):
    _fields_ = [
        ("X", SHORT),
        ("Y", SHORT),
    ]


class CONSOLE_FONT_INFOEX(Structure):
    _fields_ = [("cbSize", ULONG), ("nFont", DWORD), ("dwFontSize", COORD),
                ("FontFamily", UINT), ("FontWeight", UINT),
                ("FaceName", WCHAR * LF_FACESIZE)]


kernel32_dll = WinDLL("kernel32.dll")

get_last_error_func = kernel32_dll.GetLastError
get_last_error_func.argtypes = []
get_last_error_func.restype = DWORD

get_std_handle_func = kernel32_dll.GetStdHandle
get_std_handle_func.argtypes = [DWORD]
get_std_handle_func.restype = HANDLE

get_current_console_font_ex_func = kernel32_dll.GetCurrentConsoleFontEx
get_current_console_font_ex_func.argtypes = [
    HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)
]
get_current_console_font_ex_func.restype = BOOL
コード例 #29
0
ファイル: _ntdll.py プロジェクト: aamlima/pyWSendInput
from ctypes import wintypes, WinDLL, Structure

NTDLL = WinDLL('ntdll')

NTSTATUS = wintypes.LONG
KAFFINITY = wintypes.ULONG
KPRIORITY = wintypes.ULONG


class CLIENTID(Structure):
    _fields_ = [('UniqueProcess', wintypes.HANDLE),
                ('UniqueThread', wintypes.HANDLE)]


class THREADBASICINFORMATION(Structure):
    _fields_ = [
        ('ExitStatus', NTSTATUS),
        ('TebBaseAddress', wintypes.LPVOID),
        ('ClientId', CLIENTID),
        ('AffinityMask', KAFFINITY),
        ('Priority', KPRIORITY),
        ('BasePriority', KPRIORITY)]


NTQUERYINFORMATIONTHREAD = NTDLL.NtQueryInformationThread
NTQUERYINFORMATIONTHREAD.argtypes = [
    wintypes.HANDLE, wintypes.LONG, wintypes.LPVOID, wintypes.ULONG, wintypes.PULONG]
NTQUERYINFORMATIONTHREAD.restype = NTSTATUS
コード例 #30
0
ファイル: camera_wrapper.py プロジェクト: wcyjames/stackbot
    def __init__(self, callbackFunc = None, debug = True):
        
        global camlib
        if camlib == None :
            if debug: print 'Loading Camera driver...'
            dllpath = os.path.dirname(__file__) + "\\atmcd32d.dll"
            if debug: print 'Searching for ', dllpath
            camlib = WinDLL(dllpath)
            if debug: print camlib
        
        print 'Initializing Camera...'
        
        self.debug = debug
        self._pixelsX = c_int(1)
        self._pixelsY = c_int(1)
        
        if camlib.Initialize("") != consts.DRV_SUCCESS :
            print "Initialization failed"
        else :
            print "Initialization Successfull"
            
        headModel = ctypes.create_string_buffer('Hello', consts.MAX_PATH)
        if camlib.GetHeadModel(headModel) != consts.DRV_SUCCESS :
            print "Error Getting head model"
        else:
            print "Head model: ", headModel.raw
        
        serialNumber = c_int(-1)
        assert camlib.GetCameraSerialNumber(pointer(serialNumber)) == consts.DRV_SUCCESS
        self._serialNumber = serialNumber.value
        print 'Serial Number: ', self._serialNumber
        
        HW = [];
        for i in range(6):
            HW.append(c_int(i))    
        ans = camlib.GetHardwareVersion(
                pointer(HW[0]), pointer(HW[1]), pointer(HW[2]),
                pointer(HW[3]), pointer(HW[4]), pointer(HW[5]))
        if ans != consts.DRV_SUCCESS :
            print "Error Getting Hardware Version."
        else: 
            print 'Hardware information: ', HW
        
        SW = [];
        for i in range(6):
            SW.append(c_int(i))    
        ans = camlib.GetHardwareVersion(
                pointer(SW[0]), pointer(SW[1]), pointer(SW[2]),
                pointer(SW[3]), pointer(SW[4]), pointer(SW[5]))
        if ans != consts.DRV_SUCCESS :
            print "Error Getting Software Version."
        else: 
            print 'Software information: ', SW
        
        ans = camlib.GetDetector(pointer(self._pixelsX), pointer(self._pixelsY))
        if ans != consts.DRV_SUCCESS :
            print "Couldn't get dimensions."
        else :
            print "Dimensions: ", self._pixelsX.value, self._pixelsY.value
        
        numADChan = c_int(-1)
        assert camlib.GetNumberADChannels(pointer(numADChan)) == consts.DRV_SUCCESS
        print '# of AD channels [expecting one]: ', numADChan.value
#        self._numADChan = numADChan.value
        assert camlib.SetADChannel(0) == consts.DRV_SUCCESS
        print 'Set as active channel'
        
        ampNum = c_int(-1)
        assert camlib.GetNumberAmp(pointer(ampNum)) == consts.DRV_SUCCESS
        print 'Number of output amplifiers: ', ampNum.value
        
        numHSSpeeds = c_int(-1)
        assert camlib.GetNumberHSSpeeds(0, 0, pointer(numHSSpeeds)) == consts.DRV_SUCCESS
        print '# of horizontal speeds: ', numHSSpeeds.value
        self._HSSpeeds = []
        speed = c_float(0)
        for i in range(numHSSpeeds.value):
            assert camlib.GetHSSpeed(0, 0, i, pointer(speed)) == consts.DRV_SUCCESS
            self._HSSpeeds.append(speed.value)
        print 'Horizontal speeds [MHz]: ', self._HSSpeeds
        assert camlib.SetHSSpeed(0, 0) == consts.DRV_SUCCESS
        print 'Horizontal speed set to maximum.'
        
        numVSSpeeds = c_int(-1)
        assert camlib.GetNumberVSSpeeds(pointer(numVSSpeeds)) == consts.DRV_SUCCESS
        print '# of vertical speeds: ', numVSSpeeds.value
        self._VSSpeeds = []
        for i in range(numVSSpeeds.value):
            assert camlib.GetVSSpeed(i, pointer(speed)) == consts.DRV_SUCCESS
            self._VSSpeeds.append(speed.value)
        print 'Vertical speeds [microseconds per pixel shift]: ' , self._VSSpeeds
        index = c_int(-1)
        assert camlib.GetFastestRecommendedVSSpeed(pointer(index), pointer(speed)) == consts.DRV_SUCCESS
        print ('Recommended speed is %f, at index %d' % ( speed.value, index.value))
        assert camlib.SetVSSpeed(index) == consts.DRV_SUCCESS
        print 'Vertical speed set to recommended value.'
        
        numGains = c_int(-1)
        assert camlib.GetNumberPreAmpGains(pointer(numGains)) == consts.DRV_SUCCESS
        print '# of gains: ', numGains.value
        self._preampGains = []
        gain = c_float(-1);
        for i in range(numGains.value) :
            assert camlib.GetPreAmpGain(i, pointer(gain)) == consts.DRV_SUCCESS
            self._preampGains.append(gain.value)
        print 'Preamp gains available: ', self._preampGains
        ind = 1
        assert camlib.SetPreAmpGain(ind) == consts.DRV_SUCCESS
        print 'Preamp gain set to  = ', self._preampGains[ind]
        assert camlib.SetPreAmpGain(0) == consts.DRV_SUCCESS
        
        self._minTemp = c_int(0)
        self._maxTemp = c_int(0)
        ans = camlib.GetTemperatureRange(pointer(self._minTemp), pointer(self._maxTemp))       
        if ans != consts.DRV_SUCCESS :
            print "Error getting acceptable temperature range."
        else:
            print "Acceptable Temperatures: ", self._minTemp.value, self._maxTemp.value
            
            
        self._lastTemp = c_int(0)
        ans = camlib.GetTemperature(pointer(self._lastTemp))
        if ans == consts.DRV_NOT_INITIALIZED or ans == consts.DRV_ERROR_ACK :
            print "Error getting current temperature"
        else:
            print "Current Temperature", self._lastTemp.value
        
        
        if camlib.SetTemperature(DEFUALT_TEMPERATURE) != consts.DRV_SUCCESS:
            print "Error setting desired temperature."
        else:
            print "Operating temperature set to ", DEFUALT_TEMPERATURE
        
        if camlib.CoolerON() != consts.DRV_SUCCESS :
            print "Failed to start cooler."
        else :
            print "Cooler On."
            
#        print "Waiting for device to cool down"
#        t = self.getTemperature()
#        while (t > DEFUALT_TEMPERATURE) :
#            sleep(3)
#            t = self.getTemperature();
#            if self.debug : print "Cooling: ", t
#        
#        print "Device sufficiently cool for operations"
        
        self._setAcquisitionParameters()
        self._callbackFunc = callbackFunc
        self._waiting = False
        self._callbackParams = None
        self._setCallbackThread()
        return