I'd be very grateful for any feedback from experts on Inline C and Perl internals. I'm working with bit vectors and creating several Inline C functions which (among other things) need to test/set bits.

The example code below illustrates how I am passing a bit vector from Perl into C, and testing/setting bits in C, such that the original Perl variable is changed (=intended).

use strict; use warnings; use Inline C => 'DATA'; my $vector = "\0" x 100; # Bit vector with 800 bits mytest($vector, 12); # Pass it to Inline C function print "Result:" . vec($vector, 12, 1) . "\n"; # Prints '1' __DATA__ __C__ int mytest(SV* sv_vec, unsigned int bit) { STRLEN vecbytes; // Length of vector in bytes unsigned char *myvec = (unsigned char *) SvPV(sv_vec, vecbytes); if (bit/8 >= vecbytes) return 0; // Check in range if (myvec[bit/8] & 1U<<(bit%8)) return 1; // Test if a bit is set myvec[bit/8] |= 1U<<(bit%8); // Set bit (CHANGES $vector) return 1; }

This works, but I am wondering if this approach is safe & correct, or if there are hidden gotchas or better/more efficient ways to do this with Inline C?


In reply to Bit vector fiddling with Inline C by oxone

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.