Mailing List Archive

File objects in extension module
Hi,

I am trying to use a file object passed from Python to a C extension
module (Windows 98). All the C runtime calls crash when I pass them the
FILE pointer (fwrite, fflush, etc.)

The pointer I get back from PyFile_AsFile seems okay -- the struct
members have reasonable values, etc.

I have seen the same behavior with MS VC++ (4.2) and egcs/mingw32
(1.1.2), and with Python-1.5.1 and 1.5.2b2.

What am I missing?

Here is a minimal code snippet, without the error checking code:

----- example.c
#include "Python.h"

static PyObject *
ex_flush(PyObject *self, PyObject *args)
{
PyObject *file;

/* ... code to check arg count and types removed ... */

file = PyTuple_GetItem(args, 0);
fflush(PyFile_AsFile(file));

Py_INCREF(Py_None);
return Py_None;
}

static PyMethodDef example_methods[] = {
{"flush", ex_flush, 1},
{NULL, NULL}
};

void
initexample()
{
Py_InitModule("example", example_methods);
}


----- on the Python side:
>>> import example
>>> f = open('test', 'w')
>>> example.flush(f) --> crash!


Puzzled,
Mike
File objects in extension module [ In reply to ]
Mike Steed writes:
>
> I am trying to use a file object passed from Python to a C extension
> module (Windows 98). All the C runtime calls crash when I pass them
> the FILE pointer (fwrite, fflush, etc.)
>
> The pointer I get back from PyFile_AsFile seems okay -- the struct
> members have reasonable values, etc.
>
> I have seen the same behavior with MS VC++ (4.2) and egcs/mingw32
> (1.1.2), and with Python-1.5.1 and 1.5.2b2.
>
> What am I missing?

You need the same build / link options as Python - specifically, you
need to use the Multithreaded DLL for c runtime support. Otherwise
you're trying to manipulate one file from 2 separate copies of the c
runtime. Kablooie.

- Gordon