Affix
view release on metacpan or search on metacpan
t/019_fileio.t view on Meta::CPAN
use v5.40;
use lib '../lib', 'lib';
use blib;
use Test2::Tools::Affix qw[:all];
use Path::Tiny qw[path tempfile tempdir];
use Test2::V0 -no_srand => 1;
use Affix qw[:all];
$|++;
#
subtest simple => sub {
my $lib = compile_ok(<<'END_C');
#include "std.h"
//ext: .c
#include <stdio.h>
#include <string.h>
// Write to a FILE* passed from Perl
DLLEXPORT int c_write_to_file(FILE* fp, const char* text) {
if (!fp) return -1;
return fprintf(fp, "%s", text);
}
// Read from a FILE* passed from Perl
DLLEXPORT int c_read_char(FILE* fp) {
if (!fp) return -2;
return fgetc(fp);
}
// Return a new FILE* created in C
DLLEXPORT FILE* c_create_tmpfile(void) {
FILE* fp = tmpfile();
if (fp) {
fprintf(fp, "Content from C");
fflush(fp);
rewind(fp);
}
return fp;
}
// Identity function to test round-tripping a PerlIO pointer.
// Since we don't link against libperl here, we treat PerlIO* as void*.
DLLEXPORT void* c_perlio_identity(void* p) {
return p;
}
// Check if FILE* is NULL (to verify failure cases)
DLLEXPORT int c_is_null_file(FILE* fp) {
return fp == NULL;
}
END_C
subtest 'Standard C FILE* (Affix::File)' => sub {
# File represents the FILE struct, so Pointer[File] is FILE*
affix $lib, 'c_write_to_file', [ Pointer [File], String ] => Int;
affix $lib, 'c_read_char', [ Pointer [File] ] => Int;
affix $lib, 'c_create_tmpfile', [] => Pointer [File];
affix $lib, 'c_is_null_file', [ Pointer [File] ] => Int;
#
subtest 'Writing to a Perl filehandle from C' => sub {
my $file = tempfile( { realpath => 1 } );
my $fh = $file->filehandle('>');
( run in 1.604 second using v1.01-cache-2.11-cpan-ff9377addf4 )