http://www.perlmonks.org?node_id=488179

kamesh3183 has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,
I am writing a wrapper for a C function:
int fun1(FILE *, char *);

Can somebody tell me how to convert the Perl filehandle into a C FILE * ?
presently I am using code like this:
arg1 = IoIFP(sv_2io(ST(1));
but the IoIFP is returning struct _PerlIO * type. Can anybody tell me how can I convert into FILE *?
Thanks
Kamesh

Replies are listed 'Best First'.
Re: converting perl file handle into C FILE *
by merlyn (Sage) on Aug 31, 2005 at 18:12 UTC
    If you're using PerlIO instead of STDIO, you probably won't be able to do what you want, because the buffer layout is likely incompatible.

    If all you want is a FILE * that is open on the same filedescriptor (which means that buffered I/O will almost certainly be broken), you can get the fileno from Perl, then create a FILE * on that using fdopen(3). That's probably not very safe though, because Perl will eventually close the handle leaving your FILE * pointing at a dead handle.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: converting perl file handle into C FILE *
by Roger (Parson) on Aug 31, 2005 at 18:14 UTC
    You can use the XS::Typemap module, and use the convertion function T_STDIO to convert perl I/O structure to FILE * structure to pass to your XS.