Programming Perl in C
SV *sv_rv = NEWSV(0,0);
sv_setref_iv(sv_rv, Nullch, 10); // sv_rv now a ref to an SV containing 10
sv_setref_uv(sv_rv, Nullch, 10); // sv_rv now a ref to an SV containing 10
sv_setref_nv(sv_rv, Nullch, 10.5); // sv_rv now a ref to an SV containing 10.5
sv_setref_pvn(sv_rv, Nullch, "foo", 3); // sv_rv now a ref to an SV
// containing "foo"
The Nullch argument indicates that I'm not creating a blessed reference (that is, an
object). If you pass a class name here, you'll create a blessed reference:
sv_setref_iv(sv_rv, "Math::BigInt", 10); // sv_rv is now a reference blessed
// into the Math::BigInt class.
One function in the sv_setref family was left out of the preceding list:
sv_setref_pv(). This function is a bit of an oddball it doesn't copy the string
passed to it. Instead it copies the pointer itself into the new SV. It's easy to misuse
this function; for example:
sv_setref_pv(sv_rv, Nullch, "foo"); // ERROR!
This is an error because I just copied a pointer to an immutable string into a new
SV. When the SV eventually tries to call free() on the string, it will cause the pro
gram to crash or at least misbehave. Instead the pointer passed to sv_setref_pv()
must be dynamically allocated. I'll cover Perl's API for dynamically allocating
memory later in the System Wrappers section. In general, it's best to avoid this
function unless you have a good reason to want to copy a pointer into a new SV.
Type Checking
You can find out what type of object an RV points to using the SvTYPE macro on the
result of dereferencing the RV with SvRV. For example:
if (SvTYPE(SvRV(sv_rv)) == SVt_PVAV) printf("sv_rv is a ref to an AV.\n");
if (SvTYPE(SvRV(sv_rv)) == SVt_PVHV) printf("sv_rv is a ref to an HV.\n");
if (SvTYPE(SvRV(sv_rv)) == SVt_IV ||
SvTYPE(SvRV(sv_rv)) == SVt_NV ||
SvTYPE(SvRV(sv_rv)) == SVt_PV) printf("sv_rv is a ref to an SV.\n");
You can find the complete table of possible SvTYPE return values in perlapi.
19
191
1
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