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

I'd like to wrap a C++ class that looks something like this (shortened to show only relevant details):

struct fqz { public: fqz(); fqz(fqz_params *p); ~fqz(); int encode(int in_fd, int out_fd); int decode(int in_fd, int out_fd); }

My intended usage in Perl is something like this:

my $fh = Compress::FQZ::Reader->new($fn); while (<$fh>) { # ... } my $fh = Compress::FQZ::Writer->new($fn); while ($foo) { print {$fh} $bar; }

Under the hood, the constructors will: (1) create a new fqz object, (2) create a new object as subclass of FileHandle (with proper mode depending on Reader or Writer subclass), (3) get a file descriptor based on the filename passed, (4) call the encode() or decode() methods with those file descriptors, and then (5) return the FileHandle object to the caller.

The questions I'm trying to address are (1) how to do the conversions between Perl filehandle and file descriptors (I've looked at http://perldoc.perl.org/perlxstut.html#EXAMPLE-9-Passing-open-files-to-XSes which seems to be the correct concept but I'm having trouble understanding how to implement this), and (2) After finishing the reads/writes to the filehandle in Perl, do I need to call some sort of cleanup code explicity to destroy the underlying C++ objects? Can anyone point me to existing code that is doing something of this sort?

Replies are listed 'Best First'.
Re: XS filehandle/descriptor conversions and cleanup
by Anonymous Monk on Jan 12, 2016 at 17:06 UTC

    Check the standard compression support included with perl: Compress::Raw::Bzip2, IO::Compress::Bzip2, etc. The raw module implements buffer to buffer routines; higher level routines operate on streams. Neither wants file descriptors, which really belong to OS level of abstraction.