1. 程式人生 > >python ctypes 回撥函式

python ctypes 回撥函式

定義結構體

'''
typedef struct pborca_direntry 
{
					                        /* Comments */
    TCHAR            szComments[PBORCA_MAXCOMMENT + 1];

    LONG            lCreateTime;            /* Time of entry create/mod */ 
    LONG            lEntrySize;             /* Size of entry */
    LPTSTR           lpszEntryName;          /* Pointer to entry name */
    PBORCA_TYPE     otEntryType;            /* Entry type */

} PBORCA_DIRENTRY
'''
class PBORCA_DIRENTRY(ctypes.Structure):
    _fields_ = [('szComments'   ,c_char*256),
                ('lCreateTime'  ,c_long),
                ('lEntrySize'   ,c_long),
                ('lpszEntryName',c_char_p),
                ('otEntryType'  ,c_int)]

定義結構體指標

ctypes.POINTER(KBDLLHOOKSTRUCT)

stdcall呼叫約定

'''
void (__stdcall *pbcall )(PPBORCA_DIRENTRY,LPVOID);
'''
def pbcallback(pd, a):
  print pd.contents.lpszEntryName

pbcall = ctypes.WINFUNCTYPE(ctypes.POINTER(PPBORCA_DIRENTRY),c_void_p)
c_pbcallback = KHOOK(pbcallback)

 cdecl呼叫約定

CmpFuncType = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))

def py_cmp_func(a, b):
    if a[0] > b[0]:
        return 1
    elif a[0] < b[0]:
        return -1
    else:
        return 0
        
cmpfunc = CmpFuncType(py_cmp_func)

呼叫dll 

#stdcall
Objdll = ctypes.windll.LoadLibrary("dllpath")
Objdll = ctypes.WinDLL("dllpath") 

#cdecl
Objdll = ctypes.cdll.LoadLibrary("dllpath")
Objdll = ctypes.CDLL("dllpath")


#呼叫函式
# 方法1
szPara = create_string_buffer('/0'*100)
dll.PrintInfo(byref(szPara), 100);
print szPara.value
 
# 方法2
sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
pStr = c_char_p( )
pStr.value = sBuf
#pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
dll.PrintInfo(pStr, len(pStr.value))
print pStr.value
 
# 方法3
strMa = "/0"*20
FunPrint  = dll.PrintInfo
FunPrint.argtypes = [c_char_p, c_int]
#FunPrint.restypes = c_void_p
nRst = FunPrint(strMa, len(strMa))
print strMa,len(strMa)
 
# 方法4
pStr2 = c_char_p("/0")
print pStr2.value
#pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
dll.PrintInfo(pStr2, len(pStr.value))
print pStr2.value

#參考https://blog.csdn.net/magictong/article/details/3075478/