[C++-sig] type convert: python file <-> C++ FILE*

David Abrahams dave at boost-consulting.com
Mon Oct 28 05:50:18 CET 2002


Liwei Peng <liwei_peng at yahoo.com> writes:

> Hi,
> 
> For converting python file to/from C++ FILE*,
> I tried the suggested code. It didn't work.
> I got the same error message like before.

Sorry. Try the following, which works for me:

  #include <boost/python.hpp>
  #include <stdio.h>

  namespace python = boost::python;

  struct FILE_to_pyfile
  {
      static PyObject* convert(FILE* x)
      {        
          return PyFile_FromFile(x, "", "", NULL);
      }
  };

  FILE* getfile(const char* fname)
  {
      printf("openning file: %s\n", fname);
      FILE* f = fopen(fname, "w");
      fprintf(f, "initial words\n");
      return f;
  }

  BOOST_PYTHON_MODULE(numbermod)
  {
      python::to_python_converter<FILE*, FILE_to_pyfile>();
      python::def("getfile", getfile
                 , python::return_value_policy<python::return_by_value>());
  }

> Can anyone please help me out?

I hope this gets you past the problem. As I said before, these
conversions should be built-in so you don't have to provide
special call policies yourself.

-- 
                    David Abrahams
dave at boost-consulting.com * http://www.boost-consulting.com





More information about the Cplusplus-sig mailing list