ctypes: returning an array from a subroutine

Alex van der Spek zdoor at xs4all.nl
Sun Apr 20 08:35:19 EDT 2014


I have a C code function like this:

++++++++++++++++++++++++++

int __declspec(dllexport) __stdcall bnd2prb(float *in, float *out, int init)
{enum {OK, Error, Not_Valid};
 ...
return(OK):
}

++++++++++++++++++++++++++

And in Python I am trying to call this C function:

++++++++++++++++++++++++++

import ctypes
import struct
import array

_snns = 
ctypes.windll.LoadLibrary(r'C:\MSDEV\Projects\Cyctrac\Debug\Cyctrac.dll')

_cosm = getattr(_snns, '_bnd2prb at 12')

_cosm.argtypes = (ctypes.POINTER(ctypes.c_float),
                  ctypes.POINTER(ctypes.c_float),
                  ctypes.c_long)

_cosm.restype = ctypes.c_float

def snns(indata, outdat):
    """Calls the neural net, returns a vector of 4.

    """
    global _cosm

    init = ctypes.c_long(0)

    ilen = len(indata)
    olen = len(outdat)

    itype = ctypes.c_float * ilen
    otype = ctypes.c_float * olen

    iok = _cosm(itype(*indata), ctypes.pointer(otype(*outdat)), init)

    if not iok:
        return True
    else:
        return False

indata = [0.5 for x in range(31)]
outdat = [0.0 for x in range(4)]

indata[1]=3.14

ok = snns(indata, outdat)

if ok:
    print indata
    print outdat

+++++++++++++++++++++++++++++++

This executes but leaves the outdat array unchanged.

Obviously I haven't understood ctypes well enough.

Returning arrays from FORTRAN I routinely do through a string_buffer.

That works very well but did not work here at all.

Any and all help welcome.

Alex van der Spek 




More information about the Python-list mailing list