0

I am trying to write a C library for python that will return some data about a value that is passed to it in string from. The returned data is in a c structure format and I need to get this information back to python to use it.

So far my research has found a few ways this can be done one is in the form of a list and another is in the form of a python dictionary. The problem I have with either of these is memory management. I don't want to have to deal with allocation and management of memory if I can avoid it. The structure is a fixed size so I do not see this as something that is needed. Another Idea I had was to pass in a structure object of some sorts and populate it.

Code examples can be found below, any help would be appreciated.

C Code:

    static PyObject* GetValue(PyObject* self, PyObject* args)
    {
        const char* name;
        const tSomeObject* pointer = NULL;

        if (!PyArg_ParseTuple(args, "s", &name))
            return NULL;

        pointer = FindIO(inOutName);

        if(!LibSwitch(inOutPointer))
        {
            /// @todo Do something if this call fails.
            printf("IO Not Found!\r\n");
        }

        /// @todo Return the result some how????
        Py_RETURN_NONE;
    }

Python Code:

     import SomeModule
     SomeStruct = SomeModule.GetValue("Some Value")
     Print(SomeStruct)
kiyah
  • 1,502
  • 2
  • 18
  • 27
rutri
  • 13
  • 4
  • 1
    A very comfortable way to do this is by using cffi http://cffi.readthedocs.io/en/release-1.3/overview.html you can use C header and source files directly and use the C types directly in Python. – Joe Feb 27 '18 at 08:08
  • I did look into this as a possibility, it would do the trick however the module is written as a C extension and this is the last step. What I did end up doing was converting the structure to a delimited string and then converting it to a list in python. Its not the most clean way of doing this but the other options did not seem preferable for this application. Another option would be to make your only python type but that would require you to handle the garbage collection for it. – rutri Mar 01 '18 at 04:47

0 Answers0