1FFI::Platypus::Buffer(3U)ser Contributed Perl DocumentatiFoFnI::Platypus::Buffer(3)
2
3
4

NAME

6       FFI::Platypus::Buffer - Convert scalars to C buffers
7

VERSION

9       version 1.56
10

SYNOPSIS

12        use FFI::Platypus::Buffer;
13        my($pointer, $size) = scalar_to_buffer $scalar;
14        my $scalar2 = buffer_to_scalar $pointer, $size;
15

DESCRIPTION

17       A common pattern in C is to pass a "buffer" or region of memory into a
18       function with a pair of arguments, an opaque pointer and the size of
19       the memory region.  In Perl the equivalent structure is a scalar
20       containing a string of bytes.  This module provides portable functions
21       for converting a Perl string or scalar into a buffer and back.
22
23       These functions are implemented using pack and unpack and so they
24       should be relatively fast.
25
26       Both functions are exported by default, but you can explicitly export
27       one or neither if you so choose.
28
29       A better way to do this might be with custom types see
30       FFI::Platypus::API and FFI::Platypus::Type.  These functions were taken
31       from the now obsolete FFI::Util module, as they may be useful in some
32       cases.
33
34       Caution: This module provides great power in the way that you interact
35       with C code, but with that power comes great responsibility.  Since you
36       are dealing with blocks of memory you need to take care to understand
37       the underlying ownership model of these pointers.
38

FUNCTIONS

40   scalar_to_buffer
41        my($pointer, $size) = scalar_to_buffer $scalar;
42
43       Convert a string scalar into a buffer.  Returned in order are a pointer
44       to the start of the string scalar's memory region and the size of the
45       region.
46
47       You should NEVER try to free $pointer.
48
49       When you pass this pointer and size into a C function, it has direct
50       access to the data stored in your scalar, so it is important that you
51       not resize or free the scalar while it is in use by the C code.
52       Typically if you are passing a buffer into a C function which reads or
53       writes to the buffer, but does not keep the pointer for later use you
54       are okay.  If the buffer is in use long term by the C code, then you
55       should consider copying the buffer instead.  For example:
56
57        use FFI::Platypus::Buffer qw( scalar_to_buffer );
58        use FFI::Platypus::Memory qw( malloc memcpy free )
59
60        my($ptr, $size) = scalar_to_buffer $string;
61        c_function_that_does_not_keep_ptr( $ptr, $size); # okay
62
63        my($ptr, $size) = scalar_to_buffer $string;
64        my $ptr_copy = malloc($size);
65        memcpy($ptr_copy, $ptr, $size);
66        c_function_that_DOES_keep_ptr( $ptr_copy, $size); # also okay
67
68        ...
69
70        # later when you know that the c code is no longer using the pointer
71        # Since you allocated the copy, you are responsible for free'ing it.
72        free($ptr_copy);
73
74   scalar_to_pointer
75        my $pointer = scalar_to_pointer $scalar;
76
77       Get the pointer to the scalar.  (Similar to "scalar_to_buffer" above,
78       but the size of the scalar is not computed or returned).
79
80       Not exported by default, but may be exported on request.
81
82   buffer_to_scalar
83        my $scalar = buffer_to_scalar $pointer, $size;
84
85       Convert the buffer region defined by the pointer and size into a string
86       scalar.
87
88       Because of the way memory management works in Perl, the buffer is
89       copied from the buffer into the scalar.  If this pointer was returned
90       from C land, then you should only free it if you allocated it.
91
92   grow
93        grow $scalar, $size, \%options;
94
95       Ensure that the scalar can contain at least $size bytes.  The following
96       are recognized:
97
98       clear => boolean
99           If true, $scalar is cleared prior to being enlarged.  This avoids
100           copying the existing contents to the reallocated memory if they are
101           not needed.
102
103             For example, after
104
105              $scalar = "my string";
106              grow $scalar, 100, { clear => 0 };
107
108           "$scalar == "my string"", while after
109
110              $scalar = "my string";
111              grow $scalar, 100;
112
113           "length($scalar) == 0"
114
115           It defaults to "true".
116
117       set_length => boolean
118           If true, the length of the string in the $scalar is set to $size.
119           (See the discussion in "set_used_length".)  This is useful if a
120           foreign function writes exactly $size bytes to $scalar, as it
121           avoids a subsequent call to "set_used_length".  Contrast this
122
123             grow my $scalar, 100;
124             read_exactly_100_bytes_into_scalar( scalar_to_pointer($scalar) );
125             @chars = unpack( 'c*', $scalar );
126
127           with this:
128
129             grow my $scalar, 100, { set_length => 0 };
130             read_exactly_100_bytes_into_scalar( scalar_to_pointer($scalar) );
131             set_used_length( $scalar, 100 );
132             @chars = unpack( 'c*', $scalar );
133
134           It defaults to "true".
135
136       Any pointers obtained with "scalar_to_pointer" or "scalar_to_buffer"
137       are no longer valid after growing the scalar.
138
139       Not exported by default, but may be exported on request.
140
141   set_used_length
142        set_used_length $scalar, $length;
143
144       Update Perl's notion of the length of the string in the scalar. A
145       string scalar keeps track of two lengths: the number of available bytes
146       and the number of used bytes.  When a string scalar is used as a buffer
147       by a foreign function, it is necessary to indicate to Perl how many
148       bytes were actually written to it so that Perl's string functions (such
149       as "substr" or "unpack") will work correctly.
150
151       If $length is larger than what the scalar can hold, it is set to the
152       maximum possible size.
153
154       In the following example, the foreign routine "read_doubles" may fill
155       the buffer with up to a set number of doubles, returning the number
156       actually written.
157
158         my $sizeof_double = $ffi->sizeof( 'double' );
159         my $max_doubles = 100;
160         my $max_length = $max_doubles * $sizeof_double;
161
162         my $buffer;                   # length($buffer) == 0
163         grow $buffer, $max_length;    # length($buffer) is still  0
164         my $pointer = scalar_to_pointer($buffer);
165
166         my $num_read = read_doubles( $pointer, $max_doubles );
167                                       # length($buffer) is still == 0
168
169         set_used_length $buffer, $num_read * $sizeof_double;
170                                       # length($buffer) is finally != 0
171
172         # unpack the native doubles into a Perl array
173         my @doubles = unpack( 'd*', $buffer );  # @doubles == $num_read
174
175       Not exported by default, but may be exported on request.
176
177   window
178        window $scalar, $pointer;
179        window $scalar, $pointer, $size;
180        window $scalar, $pointer, $size, $utf8;
181
182       This makes the scalar a read-only window into the arbitrary region of
183       memory defined by $pointer, pointing to the start of the region and
184       $size, the size of the region.  If $size is omitted then it will assume
185       a C style string and use the C "strlen" function to determine the size
186       (the terminating '\0' will not be included).
187
188       This can be useful if you have a C function that returns a buffer pair
189       (pointer, size), and want to access it from Perl without having to copy
190       the data.  This can also be useful when interfacing with programming
191       languages that store strings as a address/length pair instead of a
192       pointer to null-terminated sequence of bytes.
193
194       You can specify $utf8 to set the UTF-8 flag on the scalar.  Note that
195       the behavior of setting the UTF-8 flag on a buffer that does not
196       contain UTF-8 as understood by the version of Perl that you are running
197       is undefined.
198
199       Hint: If you have a buffer that needs to be free'd by C once the scalar
200       falls out of scope you can use Variable::Magic to apply magic to the
201       scalar and free the pointer once it falls out of scope.
202
203        use FFI::Platypus::Buffer qw( scalar_to_pointer );
204        use FFI::Platypus::Memory qw( strdup free );
205        use Variable::Magic qw( wizard cast );
206
207        my $free_when_out_of_scope = wizard(
208          free => sub {
209            my $ptr = scalar_to_pointer ${$_[0]};
210            free $ptr;
211          }
212        );
213
214        my $ptr = strdup "Hello Perl";
215        my $scalar;
216        window $scalar, $ptr, 10;
217        cast $scalar, $free_when_out_of_scope;
218        undef $ptr;  # don't need to track the pointer anymore.
219
220        # we can now use scalar as a regular read-only Perl variable
221        print $scalar, "\n";  # prints "Hello Perl" without the \0
222
223        # this will free the C pointer
224        undef $scalar;
225
226       Hint: Returning a scalar string from a Perl function actually copies
227       the value.  If you want to return a string without copying then you
228       need to return a reference.
229
230        sub c_string
231        {
232          my $ptr = strdup "Hello Perl";
233          my $scalar;
234          window $scalar, $ptr, 10;
235          cast $scalar, $free_when_out_of_scope;
236          \$scalar;
237        }
238
239        my $ref = c_string();
240        print $$ref, "\n";  # prints "Hello Perl" without the \0
241
242       Not exported by default, but may be exported on request.
243

SEE ALSO

245       FFI::Platypus
246           Main Platypus documentation.
247

AUTHOR

249       Author: Graham Ollis <plicease@cpan.org>
250
251       Contributors:
252
253       Bakkiaraj Murugesan (bakkiaraj)
254
255       Dylan Cali (calid)
256
257       pipcet
258
259       Zaki Mughal (zmughal)
260
261       Fitz Elliott (felliott)
262
263       Vickenty Fesunov (vyf)
264
265       Gregor Herrmann (gregoa)
266
267       Shlomi Fish (shlomif)
268
269       Damyan Ivanov
270
271       Ilya Pavlov (Ilya33)
272
273       Petr Písař (ppisar)
274
275       Mohammad S Anwar (MANWAR)
276
277       Håkon Hægland (hakonhagland, HAKONH)
278
279       Meredith (merrilymeredith, MHOWARD)
280
281       Diab Jerius (DJERIUS)
282
283       Eric Brine (IKEGAMI)
284
285       szTheory
286
287       José Joaquín Atria (JJATRIA)
288
289       Pete Houston (openstrike, HOUSTON)
290
292       This software is copyright (c) 2015,2016,2017,2018,2019,2020 by Graham
293       Ollis.
294
295       This is free software; you can redistribute it and/or modify it under
296       the same terms as the Perl 5 programming language system itself.
297
298
299
300perl v5.34.0                      2021-10-29          FFI::Platypus::Buffer(3)
Impressum