oxone has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Bit vector fiddling with Inline C
by chrestomanci (Priest) on May 09, 2011 at 08:34 UTC | |
by oxone (Friar) on May 09, 2011 at 08:40 UTC | |
Re: Bit vector fiddling with Inline C
by BrowserUk (Patriarch) on May 09, 2011 at 12:33 UTC | |
by oxone (Friar) on May 09, 2011 at 12:54 UTC | |
by BrowserUk (Patriarch) on May 09, 2011 at 13:47 UTC | |
by oxone (Friar) on May 09, 2011 at 16:52 UTC | |
by BrowserUk (Patriarch) on May 09, 2011 at 19:22 UTC | |
| |
Re: Bit vector fiddling with Inline C
by anonymized user 468275 (Curate) on May 09, 2011 at 09:34 UTC | |
by oxone (Friar) on May 09, 2011 at 09:50 UTC | |
by anonymized user 468275 (Curate) on May 09, 2011 at 12:44 UTC |