1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#
# (C) Copyright 2014 Enthought, Inc., Austin, TX
# All right reserved.
#
# This file is open source software distributed according to the terms in
# LICENSE.txt
#
 
""" Utility functions to help with ctypes wrapping.
"""
from __future__ import absolute_import
 
from ctypes import GetLastError, FormatError, WinDLL
 
 
def function_factory(
        function, argument_types=None,
        return_type=None, error_checking=None):
    if argument_types is not None:
        function.argtypes = argument_types
    function.restype = return_type
    if error_checking is not None:
        function.errcheck = error_checking
    return function
 
 
def make_error(function, function_name=None):
    code = GetLastError()
    description = FormatError(code).strip()
    if function_name is None:
        function_name = function.__name__
    exception = WindowsError()
    exception.winerror = code
    exception.function = function_name
    exception.strerror = description
    return exception
 
 
def check_null_factory(function_name=None):
    def check_null(result, function, arguments, *args):
        if result is None:
            raise make_error(function, function_name)
        return result
    return check_null
 
 
check_null = check_null_factory()
 
 
def check_zero_factory(function_name=None):
    def check_zero(result, function, arguments, *args):
        if result == 0:
            raise make_error(function, function_name)
        return result
    return check_zero
 
 
check_zero = check_zero_factory()
 
 
def check_false_factory(function_name=None):
    def check_false(result, function, arguments, *args):
        if not bool(result):
            raise make_error(function, function_name)
        else:
            return True
    return check_false
 
 
check_false = check_false_factory()
 
 
class Libraries(object):
 
    def __getattr__(self, name):
        library = WinDLL(name)
        self.__dict__[name] = library
        return library
 
 
dlls = Libraries()