包裝函式用於 ctypes

在某些情況下,C 函式接受函式指標。作為狂熱的 ctypes 使用者,我們希望使用這些函式,甚至將 python 函式作為引數傳遞。

讓我們定義一個函式:

>>> def max(x, y):
        return x if x >= y else y

現在,該函式接受兩個引數並返回相同型別的結果。為了示例,我們假設 type 是 int。

就像我們在陣列示例中所做的那樣,我們可以定義一個表示該原型的物件:

>>> CFUNCTYPE(c_int, c_int, c_int)
<CFunctionType object at 0xdeadbeef>

該原型表示返回 c_int(第一個引數)的函式,並接受兩個 c_int 引數(其他引數)。

現在讓我們包裝函式:

>>> CFUNCTYPE(c_int, c_int, c_int)(max)
<CFunctionType object at 0xdeadbeef>

函式原型有更多用法:它們可以包含 ctypes 函式(如 libc.ntohl)並驗證在呼叫函式時使用了正確的引數。

>>> libc.ntohl() # garbage in - garbage out
>>> CFUNCTYPE(c_int, c_int)(libc.ntohl)()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: this function takes at least 1 argument (0 given)