I've written a C library that exposes certain functionality via FILE * streams:

void foo_read_stuff(foo_t *ctx, FILE *stream); /* reads text from stre +am, updates internals of ctx with the data */ void foo_write_stuff(foo_t *ctx, FILE *stream); /* writes text to stre +am based on contents of ctx */

The intention was that the C applications using these functions either use stdin/stdout or open a file with fopen().

Now I want to write a perl wrapper around the library where the equivalents of these functions read from, or write to Perl strings instead of stdin or stdout or a file.

What's the best way to accomplish this?

Obviously, I could open a temporary file, let the library functions do their job, then reopen the file from the XS code and dump its contents into an SV (or write the contents of the SV to the file then reopen and call the function), but this seems clumsy and unnecessary.

There are also the GNU libc functions fmemopen() and open_memstream(), which allow me to treat a memory buffer as a FILE * stream, but these are not portable and I don't know whether they can be used safely in an XS function.

Since I wrote the C library myself, I could modify it that the functions in question could operate on strings as well as streams, but I'd rather not do that as I'd like to keep the library free of bloat.

Is there a more Perlish solution to this?


In reply to Use a string as a FILE * stream in XS code by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.