[Python] How to return an array in ctypes when calling a function

Discussão em 'Python' iniciado por Stack, Setembro 18, 2025.

  1. Stack

    Stack Membro Participativo

    What I want to do is to convert a C function into python function.

    For example, I have a C function prototype which is pre-defined:

    function_test(ViInt32 Arraysize, ViReal64 readingArray[], ViInt32 *Actual_rraysize)


    The input of the above function is Arraysize, which is the number of elements in the readingArray parameter.

    The outputs of the above function are readingArray[] and Arraysize. readingArray[] returns an array of the result and Actual_arraysize indicates the actual size of the returned array.

    And the following is the Python function I wrote by using this C function prototype:

    from ctypes import *
    def Py_function_test(self, arraysize, readingarray = [], actualarraysize = [-1e-10]):
    while len(readingarray) < arraysize:
    readingarray.append(0)
    _c_actualarraysize = c_int()
    ArrayOfDouble = c_double * arraysize
    _c_readingarray = ArrayOfDouble()
    self.function_test(c_int(arraysize),
    byref(_c_readingarray),
    byref(_actualarraysize))
    for n in range(arraysize):
    readingarray[n] = _c_readingarray[n]
    actualarraysize[0] = _c_actualarraysize.value


    In the end, it turned out the value of acutalarraysize is successfully changed. But the value of readingarray didn't change after calling the c function prototype.

    How to deal with this situation, is it because I should not have used the byref?

    Continue reading...

Compartilhe esta Página