Writing C Modules with XS
 Hash Values (HV)  section in Chapter 8, but instead of printing out keys and values, 
I'm pushing them onto the return stack with XPUSHs:
   // loop over key/value pairs
   for (i = 1; i <= count; i++) {
     value = hv_iternextsv(hv, &key, &len);
     // push key and value
     XPUSHs(sv_2mortal(newSVpvn(key, len)));
     XPUSHs(sv_mortalcopy(value));
   }
Notice that each value pushed onto the stack is made mortal. If this weren't done, 
then this subroutine would leak memory on every call.
After pushing the key/value pairs onto the return stack, the code explicitly 
frees the HV used by the XSUB:
   // free hv explicitly
   SvREFCNT_dec((SV *)hv);
At this point the HV and all SVs contained in it as values are freed. This is the 
reason that when pushing the values onto the stack I used sv_mortalcopy().
Actually, a slightly more efficient implementation would be as follows:
    SvREFCNT_inc(value);       // value will now survive the destruction of hv
    XPUSHs(sv_2mortal(value)); // and is mortal on the return stack
This avoids the copy of the value at the expense of some dangerous refcount 
manipulation. Now when the HV is freed, the value SVs will still be live with a ref 
count of 1 and mortal. This is dangerous since this kind of manipulation is easy to 
get wrong, resulting in memory leaks or crashes. Using sv_mortalcopy() offers a 
simpler solution at a the expense of a small amount of time and memory.
Once the list of return values is pushed onto the stack, the code returns early 
with the XSRETURN macro:
   // return two SVs for each key in the hash
   XSRETURN(count * 2);
This macro takes as an argument the number of items pushed on the stack, in this 
case twice the number of keys in the hash.
23
231
1






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

web hosting perl

 

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