Expected LP_c_double instance instead of c_double_Array - python ctypes error

后端 未结 2 1264
情话喂你
情话喂你 2021-01-20 07:30

I have a function in a DLL that I have to wrap with python code. The function is expecting a pointer to an array of doubles. This is the error I\'m getting:

         


        
相关标签:
2条回答
  • 2021-01-20 08:20

    Are you writing the wrapper in Python yourself? The error saying "expected LP_c_double instance" means it's expecting a pointer to a single double, not an array as you've suggested.

    >>> ctypes.POINTER(ctypes.c_double * 10)()
    <__main__.LP_c_double_Array_10 object at 0xb7eb24f4>
    >>> ctypes.POINTER(ctypes.c_double * 20)()
    <__main__.LP_c_double_Array_20 object at 0xb7d3a194>
    >>> ctypes.POINTER(ctypes.c_double)()
    <__main__.LP_c_double object at 0xb7eb24f4>
    

    Either you need to fix your argtypes to correctly expect a pointer to an array of doubles, or you need to pass in a pointer to a single double like the function currently expects.

    0 讨论(0)
  • 2021-01-20 08:23

    LP_c_double is created dynamically by ctypes when you create a pointer to a double. i.e.

    LP_c_double = POINTER(c_double)
    

    At this point, you've created a C type. You can now create instances of these pointers.

    my_pointer_one = LP_c_double()
    

    But here's the kicker. Your function isn't expecting a pointer to a double. It's expecting an array of doubles. In C, an array of type X is represented by a pointer (of type X) to the first element in that array.

    In other words, to create a pointer to a double suitable for passing to your function, you actually need to allocate an array of doubles of some finite size (the documentation for ReturnPulse should indicate how much to allocate), and then pass that element directly (do not cast, do not de-reference).

    i.e.

    size = GetSize()
    # create the array type
    array_of_size_doubles = c_double*size
    # allocate several instances of that type
    ptrpulse = array_of_size_doubles()
    ptrtdl = array_of_size_doubles()
    ptrtdP = array_of_size_doubles()
    ptrfdl = array_of_size_doubles()
    ptrfdP = array_of_size_doubles()
    ReturnPulse(ptrpulse, ptrtdl, ptrtdP, ptrfdl, ptrfdP)
    

    Now the five arrays should be populated with the values returned by ReturnPulse.

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