Writing Python ctypes for Function pointer callback function in C

后端 未结 1 1608
天命终不由人
天命终不由人 2021-01-05 02:09

I am trying to write python code to call dll functions and stuck at the function below, which I believe is related to the typedef callback function or the function pointer

1条回答
  •  别那么骄傲
    2021-01-05 03:02

    Your callback type has the wrong signature; you forgot the result type. It's also getting garbage collected when the function exits; you need to make it global.

    Your GetStatus call is missing the argument pArg. Plus when working with pointers you need to define argtypes, else you'll have problems on 64-bit platforms. ctypes' default argument type is a C int.

    from ctypes import * 
    
    api = CDLL('API.dll')
    StatusCB = WINFUNCTYPE(None, c_int, c_int, c_void_p)
    
    GetStatus = api.GetStatus
    GetStatus.argtypes = [StatusCB, c_void_p]
    GetStatus.restype = None
    
    def status_fn(nErrorCode, nSID, pArg):        
        print 'Hello world'
        print pArg[0]  # 42?
    
    # reference the callback to keep it alive
    _status_fn = StatusCB(status_fn)
    
    arg = c_int(42) # passed to callback?    
    
    def start():        
        GetStatus(_status_fn, byref(arg))
    

    0 讨论(0)
提交回复
热议问题