How to receive/get C struct from Python
Question: I have a standalone Python module used to perform analysis on some raw data.
The module is working great.

Now I need the output generated by the Python module in C source that will do
further processing on output.

Here is the rough idea of flow:

  1. C source will call the Python module.
  2. Python module will fill the results generated into a C structure and then somehow pass it to C source.

So what is the best way to get the results from Python module in C source
code?

Should I use something like the following to fill the results?

    
    
    from ctypes import *
    class result(Structure):       
        _fields_ = [("status", c_int), ...]
    


Answer: I don't think you'll want to use the ctypes module — that module is for
accessing DLLs and shared objects _from_ Python code, not the other way
around.

You don't specify how the C program is going to invoke the Python module. Will
it

  * invoke the Python script using something like `popen` from C? If so, then you can write data to `stdout` in Python and interpret the data appropriately in C. You'll have to design your own little protocol for this. This can be an ad-hoc protocol, or you can use existing formats like JSON, for which you'll find libraries for both C and Python.

  * [embed the Python VM in your C program?](http://docs.python.org/extending/embedding.html) Then you'll need to convert the C values into appropriate `Py*` values and put them into a `PyTuple` that you can pass as an argument to the Python function, from C. The output of the Python function will be a [`PyObject`](http://docs.python.org/c-api/structures.html#PyObject), which you'll have to unpack (in C) to get the data.

In both cases, you'll need to do the packing and unpacking yourself.

