Skip to content

Commit 0bcf8fc

Browse files
committed
Apply "Initial documentation for CUnion + embedded structures." from cdc
1 parent e7051e3 commit 0bcf8fc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

lib/Language/nativecall.pod

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,40 @@ members: C<$!struct-member := StructObj.new;>
230230
As you may have predicted by now, a null is represented by the type object of the
231231
struct type.
232232
233+
=head2 CUnions
234+
235+
Likewise, it is possible to declare a Perl 6 class that stores its
236+
attributes the same way a C compiler would lay them out in a similar
237+
C<union> definition; using the C<CUnion> representation:
238+
239+
class MyUnion is repr('CUnion') {
240+
has int32 $.flags32;
241+
has int64 $.flags64;
242+
}
243+
244+
say nativesizeof(MyUnion.new); # 8, ie. max(sizeof(MyUnion.flags32), sizeof(MyUnion.flags64))
245+
246+
=head2 Embedding CStructs and CUnions
247+
248+
CStructs and CUnions can be in turn referenced by -- or embedded into
249+
-- a surrounding CStruct and CUnion. To say the former we use C<has>
250+
as usual, and to do the latter we use use the C<HAS> declarator
251+
instead:
252+
253+
class MyStruct is repr('CStruct') {
254+
has Point $.point; # referenced
255+
has int32 $.flags;
256+
}
257+
258+
say nativesizeof(MyStruct.new); # 16, ie. sizeof(struct Point *) + sizeof(int32_t)
259+
260+
class MyStruct2 is repr('CStruct') {
261+
HAS Point $.point; # embedded
262+
has int32 $.flags;
263+
}
264+
265+
say nativesizeof(MyStruct2.new); # 24, ie. sizeof(struct Point) + sizeof(int32_t)
266+
233267
=head1 Typed Pointers
234268
235269
TBD

0 commit comments

Comments
 (0)