Skip to content

Latest commit

 

History

History
46 lines (33 loc) · 1.59 KB

multiple-outputs.rst

File metadata and controls

46 lines (33 loc) · 1.59 KB

Return multiple values from a function

In Python, if a function has more than one output you return a tuple. In C, the best you can do is return a struct <Passing a Struct from C to Python> which is a lot of work for something so simple. Alternatively you can pass arguments by reference which the C function can write to.

For example, the following function has two outputs, even though it doesn't use a return value. Instead it takes pointer inputs min and max which will be written to:

../../demos/multi-output/multi-output.c

To use it we the usual setup:

../../demos/multi-output/multi-output.py

We do have to do some leg-work to interact with this function. Lets give ourselves an input array of the correct type we'd like to use:

values = array.array("d", range(20))

Now to finally run our C code. The ctypes.byref calls are where the magic is happening.

../../demos/multi-output/multi-output.py

Obviously you don't want to go through this every time you use this function so write a wrapper function containing the above. Whilst you're at it, you can incorporate some type normalising.

../../demos/multi-output/multi-output.py

Now you can almost forget that this function is implemented in C:

>>> range_of([6, 9, 3, 13.5, 8.7, -4])
(-4., 13.5)