@@ -99,19 +99,33 @@ routine itself.
99
99
Note that a C < NULL > string pointer can be passed by using the C < Str > type
100
100
object; a C < NULL > return will also be represented by the type object.
101
101
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:
104
111
105
112
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
107
115
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') { * }
110
119
111
120
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);
115
129
116
130
set_foo($array);
117
131
# ...
0 commit comments