wisnij has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|