Skip to content

Commit 3631452

Browse files
committed
Adds data on Pointers refs #1513
1 parent 2856dd3 commit 3631452

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

doc/Language/nativecall.pod6

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -499,15 +499,24 @@ say "foo is {$foo.a_string} and {$foo.an_int32}";
499499
500500
=comment TODO
501501
502-
TBD more
502+
You can type your C<Pointer> by passing the type as a parameter. It works with
503+
the native type but also with C<CArray> and C<CStruct> defined types. NativeCall
504+
will not implicitly allocate the memory for it even when calling C<new> on them.
505+
It's mostly useful in the case of a C routine returning a pointer, or if it's a
506+
pointer embedded in a C<CStruct>.
503507
504-
You can type your C<Pointer> by passing the type as a parameter. It works with the native type
505-
but also with C<CArray> and C<CStruct> defined types. NativeCall will not implicitly allocate the memory for it
506-
even when calling C<new> on them.
507-
It's mostly useful in the case of a C routine returning a pointer, or if it's a pointer
508-
embedded in a C<CStruct>.
508+
=begin code
509+
use NativeCall;
510+
sub strdup(Str $s --> Pointer[Str]) is native {*}
511+
my Pointer[Str] $p = strdup("Success!");
512+
say $p.deref;
513+
=end code
509514
510515
You have to call X<C<.deref>|deref> on C<Pointer>s to access the embedded type.
516+
In the example above, declaring the type of the pointer avoids typecasting error
517+
when dereferenced. Please note that the original
518+
L<C<strdup>|https://en.cppreference.com/w/c/experimental/dynamic/strdup> returns
519+
a pointer to C<char>; we are using C<Pointer<Str>>.
511520
512521
=begin code :skip-test
513522
my Pointer[int32] $p; #For a pointer on int32;
@@ -516,7 +525,9 @@ my MyCstruct $mc = $p2.deref;
516525
say $mc.field1;
517526
=end code
518527
519-
It's quite common for a native function to return a pointer to an array of elements. Typed pointers can be dereferenced as an array to obtain individual elements.
528+
It's quite common for a native function to return a pointer to an array of
529+
elements. Typed pointers can be dereferenced as an array to obtain individual
530+
elements.
520531
521532
=begin code :skip-test
522533
my $n = 5;

doc/Language/traps.pod6

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1820,6 +1820,9 @@ for @array-of-arrays -> @a {
18201820
}
18211821
# OUTPUT: «(exit code 1) Cannot use a Buf as a string, but you called the Stringy method on it␤»
18221822
1823+
In the code above, the first element of C<@array-of-array> will be reduced to an
1824+
empty string, causing the error when entering the second iteration.
1825+
18231826
So if you want to avoid this problem with L<Buf>s, initialize the array with an
18241827
empty element.
18251828

0 commit comments

Comments
 (0)