Skip to content

Commit cf18fa8

Browse files
authored
Merge pull request #3171 from taboege/nativecall-gh3169
Add NUL byte in NativeCall example
2 parents 4bff6d5 + 6f9798b commit cf18fa8

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

doc/Language/nativecall.pod6

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -99,19 +99,33 @@ routine itself.
9999
Note that a C<NULL> string pointer can be passed by using the C<Str> type
100100
object; a C<NULL> return will also be represented by the type object.
101101
102-
If the C function requires the lifetime of a string to exceed the function
103-
call, the argument must be manually encoded and passed as C<CArray[uint8]>:
102+
If the C function requires the lifetime of data, say some buffer of type
103+
C<CArray[uint8]>, passed by pointer to exceed the function call, you have
104+
to ensure that the backing C<CArray[uint8]> Raku object is not destroyed
105+
before the C function expects it.
106+
107+
This is particularly important for strings, as the (usually preferable)
108+
C<is encoded>-way of passing strings creates only a temporary object that
109+
is automatically destroyed after the call. In this case, the argument
110+
must be manually encoded:
104111
105112
use NativeCall;
106-
# C prototype is void set_foo(const char *)
113+
# void set_foo(const char *)
114+
# Records a char pointer for later usage
107115
sub set_foo(CArray[uint8]) is native('foo') { * }
108-
# C prototype is void use_foo(void)
109-
sub use_foo() is native('foo') { * } # will use pointer stored by set_foo()
116+
# void use_foo(void)
117+
# Uses the pointer stored by set_foo()
118+
sub use_foo() is native('foo') { * }
110119
111120
my $string = "FOO";
112-
# The lifetime of this variable must be equal to the required lifetime of
113-
# the data passed to the C function.
114-
my $array = CArray[uint8].new($string.encode.list);
121+
# Manually marshal the $string into $array. Take care that $array
122+
# is not destroyed (e.g. by going out of scope) while the library
123+
# still holds on to it, after set_foo().
124+
#
125+
# $string.encode takes care of UTF-8 encoding. If $array is used
126+
# as a string by the native function, don't forget to append the
127+
# NUL byte that terminates a C string: ------------v
128+
my $array = CArray[uint8].new($string.encode.list, 0);
115129
116130
set_foo($array);
117131
# ...

0 commit comments

Comments
 (0)