Hi,
I have (for demonstration purposes) an XS sub that prints "hello" to a filehandle.
It will print to STDOUT, STDERR and to any real filehandle (opened for writing) that gets passed to it.
But, if I pass it a filehandle to a memory file, then nothing gets written to the referenced scalar.
Here's the demo script:
use warnings;
use strict;
use Inline C => Config =>
BUILD_NOISY => 1;
use Inline C => <<'EOC';
void to_FH(FILE * stream) {
fprintf(stream, "hello");
fflush(stream);
}
EOC
my ($got1, $got2);
$got1 = get_string_1();
chomp($got1); # just in case ...
print "OK 1\n" if $got1 eq "hello";
$got2 = get_string_2();
chomp($got2); # just in case ...
print "OK 2\n" if $got2 eq "hello";
sub get_string_1 {
# Write to a temporary file
open TEMPFILE, '+>', undef or die $!;
to_FH(*TEMPFILE);
seek TEMPFILE, 0, 0;
my $ret = <TEMPFILE>;
close TEMPFILE;
return $ret;
}
sub get_string_2 {
# Write to a memory file
my $out;
open MEM, '+>', \$out or die $!;
to_FH(*MEM);
#close MEM; # Makes no difference
return $out; # returns undef ... why ?
}
__END__
For me, outputs:
OK 1
Use of uninitialized value $got2 in scalar chomp at try.pl line 24.
Use of uninitialized value $got2 in string eq at try.pl line 25.
So ... sub get_string_1 works fine and passes the string to the temporary file associated with the filehandle, from which I successfully retrieve what was written.
With sub get_string_2, my expectation is that the string "hello" will be written to the sub's $out - but that's not happening, and $out remains uninitialized.
What needs to be done here, to get it working as I expect ?
I also tried an alternative version of the XSub:
void to_FH(PerlIO * stream) {
FILE * stdio_stream = PerlIO_exportFILE(stream, NULL);
fprintf(stdio_stream, "hello");
fflush(stdio_stream);
PerlIO_releaseFILE(stream, stdio_stream);
}
But this made no discernible difference to the behaviour.
Cheers,
Rob
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.