Search code examples
pythondlltypeerrorctypes

Python ctypes TypeError while calling a DLL function


I have a DLL which I load with ctypes CDLL and then I am calling DLL functions via python. Sadly I do not have the original DLL coding, however I have an C header file where the function INPUTS and OUTPUTS and their types can be seen.

When I checked the header file for the following function it says:

INT32 DllExport load_active(
/* OUT */                      INT32  *h_nw,
/* IN  */                      INT32   flags);

So I am trying to run the load_active function in python via:

import ctypes as ct
    
dll = ct.CDLL('example.dll')
dll.load_active.argtypes = [ct.POINTER(ct.c_int32), ct.c_int32]
dll.load_active.errcheck = _validate_result

h_nw = ct.POINTER(ct.c_int32)
flags = ct.c_int32(0)

status = dll.load_active(h_nw, flags)

I am getting the following error:

    status = dll.load_active(h_nw, flags)
ctypes.ArgumentError: argument 1: TypeError: expected LP_c_long instance instead of _ctypes.PyCPointerType

Solution

  • h_nw is a type in your code where a value is expected. Try:

    h_nw = ct.c_int32(0)
    flags = ct.c_int32(0)
    
    status = dll.load_active(ct.byref(h_nw), flags)
    

    h_nw will then contain the value set by load_active.

    Alternatively, h_nw can be set as

    h_nw = ct.pointer(ct.c_int32())
    

    and used as

    status = dll.load_active(h_nw, flags)
    

    if the pointer itself should be kept for any reason but is less efficient.