[Tutor] passing values and C pointers

eryk sun eryksun at gmail.com
Sun May 6 16:02:12 EDT 2018


On Sun, May 6, 2018 at 2:17 AM, Brad M <thebigwurst at gmail.com> wrote:
>
> Say I have an array of values, say addresses or int produced by a c module/
> c function that's in a DLL , how do I pass that array back to
> the python code?

C arrays are passed and returned automatically as pointers to the
first element. The array length has to be passed separately, unless
there's a known sentinel value.

A simple pattern is to let the caller allocate the array and pass a
pointer and the length. This gives the caller explicit control over
the lifetime of the array, which is especially simple for ctypes since
it uses reference-counted objects.

Say you have a function in C such as the following:

    int
    DLLAPI
    get_data(int *data, size_t length)
    {
        size_t i;
        for (i=0, i < length; i++) {
            if (do_something(i, &data[i]) == -1) {
                return -1; /* failure */
            }
        }
        return 0; /* success */
    }

In Python, set up and call this function as follows:

    import ctypes

    mydll = ctypes.CDLL('mydll')

    # setup
    mydll.get_data.argtypes = (
        ctypes.POINTER(ctypes.c_int), # data
        ctypes.c_size_t)              # length

    # call
    data = (ctypes.c_int * 10)()
    status = mydll.get_data(data, len(data))
    if status == -1:
        raise MyDllException('get_data: ...')

    for i, value in enumerate(data):
        result = do_something_else(i, value)


More information about the Tutor mailing list