Created
March 28, 2019 23:12
-
-
Save CurtTilmes/bd3b515a6995c473990635e73a4b34a5 to your computer and use it in GitHub Desktop.
Start of a CStructArray module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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