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

Liwei Peng lpeng at bcm.tmc.edu
Thu Oct 24 23:35:04 CEST 2002


Hi,

I am using Boost Python V2 to wrap my C++ code. I failed
to convert python file to/from C++ FILE*. Here is my code:

----------------------------------------
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_internal_reference<>());
}

-----------------------------------------------
After I compiled the code, in python run

  f = getfile("hello.txt")
  
gave me the following error:

Traceback (most recent call last):
  File "./test.py", line 18, in ?
    f1 = getfile("hello.txt")
TypeError: bad argument type for built-in operation


Can you kindly tell me
  1) what's wrong with the above code? 

  2) The above code is from C++ 'FILE*' to python file.
     If I want to convert python file to C++ file,
     how can I do that?

Thanks in advance.

Liwei






More information about the Cplusplus-sig mailing list