I'm working on a module which is a Perl interface to an existing C++ library at my work. In particular, there's a constant in the C++ header that I want to expose in Perl, rather than duplicating the definition and risking them drift out of sync if someone forgets to update the code in one place or the other. My XS experience to date is limited, but after looking through perlguts, perlapi and some Googling, here's what I've come up with so far:

MyModule.pm:

package MyModule; use vars qw(@ISA $VERSION $CONSTANT_NAME); BEGIN { @ISA = qw(DynaLoader); $VERSION = '0.01'; $CONSTANT_NAME = -1; } bootstrap MyModule $VERSION;

MyModule.xs:

#include "my_constants.h" MODULE = MyModule PACKAGE = MyModule BOOT: { SV* const_sv = get_sv( "MyModule::CONSTANT_NAME", 0 ); SvIV_set( const_sv, CONSTANT_VALUE_FROM_C_LIBRARY ); SvIOK_on( const_sv ); SvREADONLY_on( const_sv ); }

This works in the sense that it compiles and provides the expected value in my simple test one-liner (basically just "use MyModule; print $MyModule::CONSTANT_NAME"). However, I'm not sure whether this is actually the best way to go about it -- in particular, setting $CONSTANT_NAME in the BEGIN block and then changing it again in the XS seems clunky. It's also possible that this is subtly broken in some way that I haven't discerned yet (e.g. threads or something).

My question, then, is (a) whether this as written is incorrect in any specific way, and (b) whether there's a better approach that I ought to be using instead. What say ye, monks?


In reply to XS: exposing C++ library constant as package variable by wisnij

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.