Chapter 8
System Wrappers
The Perl API provides a number of wrappers around common system functions.
These allow you to do things like dynamically allocate memory and perform IO
operations without needing to worry about the underlying platform details. Using
these wrappers instead of calling the functions directly will improve the portability
of your code.
Memory Allocation
Perl provides a wrapper around malloc() called New(). For example, the following
allocates a buffer of 1024 bytes:
char *buffer = NULL;
New(0, buffer, 1024, char);
if (buffer == NULL) croak("Memory allocation failed!");
The first argument to all of these functions is an ID used to track memory alloca
tions during debugging; for most purposes it can be left at 0. The second parame
ter is a pointer variable to receive the newly allocated pointer. The third is the
number of items to be allocated. Finally, the last argument is the type of object to
be allocated, in this case a char.
New() allocates memory without initializing it. Use Newz() to allocate a zero
filled buffer:
char *zbuffer = NULL;
Newz(0, zbuffer, 1024, char);
if (zbuffer == NULL) croak("Memory allocation failed!");
To access realloc(), use Renew:
Renew(buffer, 2048, char); // increase buffer to 2048 bytes
The Perl API interface to free() is called Safefree():
Safefree(buffer); // free buffer
You must call Safefree() on every pointer allocated with New() or Newz() to avoid
leaking memory. No garbage collection is performed on buffers allocated with
these functions.
Also provided are wrappers around memcpy() (Copy()) and memmove() (Move())
that can be used to efficiently copy sections of memory. For example:
202
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved