Skip to content

Instantly share code, notes, and snippets.

@CurtTilmes
Created March 28, 2019 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CurtTilmes/bd3b515a6995c473990635e73a4b34a5 to your computer and use it in GitHub Desktop.
Save CurtTilmes/bd3b515a6995c473990635e73a4b34a5 to your computer and use it in GitHub Desktop.
Start of a CStructArray module
use NativeCall;
class foo is repr('CStruct')
{
has int32 $.a is rw;
has int64 $.b is rw;
}
sub calloc(size_t, size_t --> Pointer) is native {}
sub free(Pointer) is native {}
role CStructArray[::cstruct] does Positional
{
has Pointer $.base;
has Int $.size;
method new(int $size)
{
my $base = calloc($size, nativesizeof(cstruct)) // die "Out of Memory";
self.bless(:$size, :$base);
}
submethod DESTROY()
{
free($_) with $!base;
}
method AT-POS(Int $field where 0 <= $field < $!size )
{
nativecast(cstruct, Pointer.new($!base + $field * nativesizeof(cstruct)))
}
}
my $array = CStructArray[foo].new(5);
$array[1].a = 12;
say $array[1].a;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment