有没有办法确保我所有的ctypes都有argtypes?

时间:2017-09-07 05:01:21

标签: ctypes

我知道我应该为我的C / C ++函数指定argtypes,因为我的一些调用会导致堆栈损坏。

    myCfunc.argtypes = [ct.c_void_p, ct.POINTER(ct.c_void_p)]
    myCfunc.errcheck = my_error_check

事实上,我想验证我没有忘记为我的大约100个函数调用指定函数原型(argtypes / errcheck)...

现在我只是浏览我的Python文件,并在视觉上与包含原型定义的文件进行比较。

是否有更好的方法可以验证我是否为我的所有电话定义了argtypes / errcheck

2 个答案:

答案 0 :(得分:1)

@eryksun提到命名空间让我将dll包装在一个只暴露显式注释函数的类中。只要dll没有函数名称"注释"或" _error_check" (我没有),以下方法似乎对我有用:

import ctypes as ct

class MyWinDll:
    def __init__(self, dll_filename):
        self._dll = ct.WinDLL(dll_filename)
        # Specify function prototypes using the annotate function
        self.annotate(self._dll.myCfunc, [ct.POINTER(ct.c_void_p)], self._error_check)
        self.annotate(self._dll.myCfunc2, [ct.c_void_p], self._error_check)
        ...

    def annotate(self, function, argtypes, errcheck):
        # note that "annotate" may not be used as a function name in the dll...
        function.argtypes = argtypes
        function.errcheck = errcheck
        setattr(self, function.__name__, function)

    def _error_check(self, result, func, arguments):
        if result != 0:
            raise Exception

if __name__ == '__main__':
    dll = MyWinDll('myWinDll.dll')
    handle = ct.c_void_p(None)
    # Now call the dll functions using the wrapper object
    dll.myCfunc(ct.byref(handle))
    dll.myCfunc2(handle)

更新: @eryksun的评论让我尝试通过授予用户对WinDLL构造函数的控制并尝试减少重复代码来改进代码:

import ctypes as ct

DEFAULT = object()

def annotate(dll_object, function_name, argtypes, restype=DEFAULT, errcheck=DEFAULT):
    function = getattr(dll_object._dll, function_name)
    function.argtypes = argtypes
    # restype and errcheck is optional in the function_prototypes list
    if restype is DEFAULT:
        restype = dll_object.default_restype
    function.restype = restype
    if errcheck is DEFAULT:
        errcheck = dll_object.default_errcheck
    function.errcheck = errcheck
    setattr(dll_object, function_name, function)


class MyDll:
    def __init__(self, ct_dll, **function_prototypes):
        self._dll = ct_dll
        for name, prototype in function_prototypes.items():
            annotate(self, name, *prototype)


class OneDll(MyDll):
    def __init__(self, ct_dll):
        # set default values for function_prototypes
        self.default_restype = ct.c_int
        self.default_errcheck = self._error_check
        function_prototypes = {
            'myCfunc': [[ct.POINTER(ct.c_void_p)]],
            'myCfunc2': [[ct.c_void_p]],
            # ...
            'myCgetErrTxt': [[ct.c_int, ct.c_char_p, ct.c_size_t], DEFAULT, None]
        }
        super().__init__(ct_dll, **function_prototypes)

    # My error check function actually calls the dll, so I keep it here...
    def _error_check(self, result, func, arguments):
        msg = ct.create_string_buffer(255)
        if result != 0:
            raise Exception(self.myCgetErrTxt(result, msg, ct.sizeof(msg)))


if __name__ == '__main__':
    ct_dll = ct.WinDLL('myWinDll.dll')
    dll = OneDll(ct_dll)
    handle = ct.c_void_p(None)
    dll.myCfunc(ct.byref(handle))
    dll.myCfunc2(handle)

(我不知道是否应该删除原始代码,我将其保留以供参考。)

答案 1 :(得分:0)

这是一个虚拟类,可以通过简单的检查来替换DLL对象的函数调用,以查看已定义的属性:

class DummyFuncPtr(object):
    restype = False
    argtypes = False
    errcheck = False

    def __call__(self, *args, **kwargs):
        assert self.restype
        assert self.argtypes
        assert self.errcheck

    def __init__(self, *args):
        pass

    def __setattr__(self, key, value):
        super(DummyFuncPtr, self).__setattr__(key, True)

要使用它,请替换您的DLL对象的_FuncPtr类,然后调用每个函数来运行检查,例如:

dll = ctypes.cdll.LoadLibrary(r'path/to/dll')

# replace the DLL's function pointer
# comment out this line to disable the dummy class
dll._FuncPtr = DummyFuncPtr

some_func = dll.someFunc
some_func.restype = None
some_func.argtypes = None
some_func.errcheck = None

another_func = dll.anotherFunc
another_func.restype = None
another_func.argtypes = None

some_func()     # no error
another_func()  # Assertion error due to errcheck not defined

虚拟类完全阻止了函数被调用,所以只需注释掉替换行以切换回正常操作。

请注意,它只会在调用该函数时检查每个函数,因此最好在某个单元测试文件中保证函数被调用。