[PyKDE] Sip support for FILE */PyFileObject

Phil Thompson phil at riverbankcomputing.co.uk
Tue Oct 11 08:32:10 BST 2005


> Hello all,
>
> We'd like to be able to mix C++ and Python for reading
> and writing of heavy-weight streams of data.  Although
> QFile can be used across both C++ and Python using PyQt,
> it is somewhat more appealing to use native python files
> in Python and native FILE * in C/C++.
>
> We've come up with a working solution to convert
> a PyFileObject to a FILE * using sip:
>
>      MyWriter(SIP_PYOBJECT);
> %MethodCode
>          if (PyFile_Check(a0))
>              sipCpp = new MyWriter(PyFile_AsFile(a0));
>          else
>          {
>              sipCpp = NULL;
>              sipIsErr = 1;
>              PyErr_SetNone(PyExc_TypeError);
>          }
> %End
>
> We can think of two other variations that would
> require changes to sip, but would reduce the need
> for method code...
>
> (a)
>
>      MyWriter(SIP_PYFILE);
> %MethodCode
>          sipCpp = new MyWriter(PyFile_AsFile(a0));
> %End
>
> (b)
>
>      MyWriter(FILE *);
>
> Another thing we've tried is creating a binding
> for struct FILE, but the sip-generated code
> is inclined to delete it once passed to
> MyWriter...
>
> struct FILE
> {
> %TypeHeaderCode
> #include <cstdio>
> using namespace std;
> %End
>
> private:
>      FILE();
>      FILE(const FILE &);
>      ~FILE();
>
> %ConvertToTypeCode
>
>      if (sipIsErr == NULL)
>          return PyFile_Check(sipPy);
>
>      if (PyFile_Check(sipPy))
>      {
>         *sipCppPtr = PyFile_AsFile(sipPy);
>         return 1;
>      }
>
>      *sipIsErr = 1;
>      return 0;
> %End
> };
>
> Any hints or suggestions appreciated.

I don't know what you mean by "inclined to delete it". It should follow
the normal garbage collection rules. If you want MyWriter to take
ownership of the FILE then take ownership of it in the ctor.

As file is a C structure I would also wrap it in a %CModule rather than a
C++ %Module.

Phil




More information about the PyQt mailing list