How to receive a FILE* from Python under MinGW?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Mar 21 01:48:07 EDT 2007


En Wed, 21 Mar 2007 01:30:34 -0300, John Pye <john.pye at gmail.com> escribió:

> On Mar 21, 3:15 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> En Wed, 21 Mar 2007 00:46:03 -0300, John Pye
>> <john.... at student.unsw.edu.au> escribió:
>>
>> > This is not an option for me, as I want to pass the
>> > FILE* from Python and all the way into into a existing shared-library
>> > code. I can't change the latter; it must work ok with standard fprintf
>> > (etc) functions.
>>
>> You can get the file descriptor from the Python file object using its
>> fileno() method. The file descriptor lives at the OS level, so it's safe
>> to pass around. You can regenerate a new FILE struct (using the other
>> runtime library) with fdopen.
>>
>> --
>> Gabriel Genellina
>
> Hi Gabriel
>
> Are you sure about this? My understanding is that 'fileno' is just a
> FILE* cast to an integer. So it's a pointer to something (check out
> stdio.h to see what it points to). Problem is (AFAICT) that Python 2.4

A FILE struct usually *contains* a file descriptor, among other things.  
But I think the FILE struct is opaque and not specified. Perhaps one  
should go even at a lower level, using open_osfhandle and get_osfhandle.  
(From python you can use the msvcrt module). See  
http://msdn2.microsoft.com/en-us/library/kdfaxaay(VS.71).aspx
h=get_osfhandle(f.fileno()) returns a Windows file handle that you can  
pass around.
On the Mingw side: fd=open_osfhandle(h); FILE *f=fdopen(fd)

> uses a different version of the C runtime DLL (MSVCRT*.DLL) to that
> which MinGW links against. And it turns out that the different C
> runtime libraries have incompatible implementations of the FILE
> struct. And therefore if you try to pass a FILE* (fileno?) from Python
> to MinGW you will get a segfault.

Exactly; the idea is not to pass a foreign FILE struct, but to *contruct*  
another one based on an existing open file; this is what fdopen does.

> If there is more to your suggestion that I'm not seeing, please
> clarify. Have you tried this with  MinGW actually?

No, but I'm rather confident it should work... as always, it can fail  
miserably :)

-- 
Gabriel Genellina




More information about the Python-list mailing list