Don't write Perl code in XS. Write in XS only the parts that wrap the C library. And write the XS wrapper using a C-friendly interface (you might even want to use Inline::C to write the wrapper to encourage not trying to write Perl code in XS). Then make a nice Perl-like interface over that by writing that interface in Perl.

This will reduce how buggy your code is (XS code is so easy to write bugs in), will surely give you a more robust and Perl-friendly interface, will make it easier to maintain, enhance, and debug your code.

And even with this approach, I would avoid writing subs that try to act as both a method and as a non-method. If you want to support exporting non-method subroutines, then just have exportable tiny wrappers that call the methods (or, if there is absolutely no object data, then you can make the methods be tiny wrappers around the non-methods).

double cos( double x ) /* No need to write the trivial XS wrapper, just the declaration */
package Math::MyWrapper; use Math::MyWrapper::XS(); use Exporter 'import'; our @EXPORT_OK = qw< cos ... >; sub new { require Math::MyWrapper::Class; return "Math::MyWrapper::Class"; } sub cos { my( $x ) = @_; return Math::MyWrapper::XS::cos( $x ); } ...
package Math::MyWrapper::Class; use Math::MyWrapper(); for my $sub ( @Math::MyWrapper::EXPORT_OK ) { eval "sub $sub { Math::MyWrapper::$sub( \@_[1..\$#_] ) }; 1" or die "Error building $sub method: $@\n"; } 1

- tye        


In reply to Re: Procedural and object oriented interface in Perl/XS (minimize XS) by tye
in thread Procedural and object oriented interface in Perl/XS by stewa02

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.