Question
How can I support autovivified filehandle arguments in an XS function?
I'm XS-wrapping a C function which returns a file descriptor, and I'd like to present that file descriptor as a perl filehandle argument in the manner of open(). E.g.,
myfunc(my $fh) or die "Error: $!";
do_something_with_fh($fh);
What I've done so far
Right now I'm using a perl wrapper on top of the XS function:
# -- in perl
sub myfunc {
my $fd = _myfunc();
return open($_[0], '+<&=', $fd) if defined($fd);
}
/* -- in XS */
SysRet
_myfunc()
CODE:
RETVAL = some_c_function_returning_an_fd();
OUTPUT:
RETVAL
This works Just Fine (tm), but, again, I'd like to move the implementation entirely into XS.
So far I've tried sv_2io
on an argument typemapped as SV *
, but that throws an exception on undefined scalars. I have not tried mapping the first argument to a FILE *
or PerlIO *
object, since I don't know how I'd "fdreopen" (if you will) those objects.
IO
object from thePerlIO
returned byPerlIO_fdopen
. The code behind Perl'sopen
does it itself rather than calling a library function. Eventually, you'd callsv_replace(fh, rv)
to move what you created into the argument (givenmyfunc(SV* fh)
). – Straight