perlclib - Interacting with standard C library functions
The perl interpreter is written in C; XS code also expands to C. Inevitably, this code will call some functions from the C library, libc
. This document gives some guidance on interfacing with that library.
One thing Perl porters should note is that perl doesn't tend to use that much of the C standard library internally; you'll see very little use of, for example, the ctype.h functions in there. This is because Perl tends to reimplement or abstract standard library functions, so that we know exactly how they're going to operate.
There are many many libc functions. Most of them are fair game to use, but some are not. Some of the possible reasons are:
They likely will interfere with the perl interpreter's functioning, such as its bookkeeping, or signal handling, or memory allocation, or any number of harmful things.
They aren't implemented on all platforms, but there is an alternative that is.
Or they may be buggy or deprecated on some or all platforms.
They aren't suitable for multi-threaded operation, but there is an alternative that is, and is just as easily usable.
You may not expect your code to ever be used under threads, but code has a way of being adapted beyond our initial expectations. If it is just as easy to use something that can be used under threads, it's better to use that now, just in case.
In functions that deal with strings, complications may arise because the string may be encoded in different ways, for example in UTF-8. For these, it is likely better to place the string in a SV and use the Perl SV string handling functions that contain extensive logic to deal with this.
In functions that deal with numbers, complications may arise because the numbers get too big or small, and what those limits are depends on the current platform. Again, the Perl SV numeric data types have extensive logic to take care of these kinds of issues.
They are locale-aware, and your caller may not want this.
The following commentary and tables give some functions in the first column that shouldn't be used in C or XS code, with the preferred alternative (if any) in the second column.
In the following tables:
~
marks the function as deprecated; it should not be used regardless.
t
is a type.
p
is a pointer.
n
is a number.
s
is a string.
sv
, av
, hv
, etc. represent variables of their respective types.
Instead of the stdio.h functions, you should use the Perl abstraction layer. Instead of FILE*
types, you need to be handling PerlIO*
types. Don't forget that with the new PerlIO layered I/O abstraction FILE*
types may not even be available. See also the perlapio
documentation for more information about the following functions:
Instead Of: Use:
stdin PerlIO_stdin()
stdout PerlIO_stdout()
stderr PerlIO_stderr()
fopen(fn, mode) PerlIO_open(fn, mode)
freopen(fn, mode, stream) PerlIO_reopen(fn, mode, perlio) (Dep-
recated)
fflush(stream) PerlIO_flush(perlio)
fclose(stream) PerlIO_close(perlio)