This is almost the right way to do it. Altering parameters isn't a particularly perlish thing to do--it's a habit many people have because it's the only way to return multiple values from languages with more limited return semantics, such as C.

What you should do instead is switch from CODE to PPCODE and XPUSH() both the status and the return SV (which you built almost correctly--calling sv_2mortal on a value in the input list is dicey, but works correctly for return values) so that your function returns two values rather than one.

In general, you're on the right track--if you need to return a string, return an SV. (I'd go so far as to say always return an SV, but many folks would disagree)

Anyway, the code probably ought to look like:

SV * my_xs_func(p_struct, len) void *p_struct; IV len PPCODE: { char *tmp_buffer = (char *)malloc(len); XPUSHs(sv_2mortal(newSViv(my_func(p_struct, tmp_buffer, len) +))); XPUSHs(sv_2mortal(newSVpv(tmp_buffer, 0))); free(tmp_buffer); }

In reply to Re: Perl XS: garbage-collecting my malloc'd buffer by Elian
in thread Perl XS: garbage-collecting my malloc'd buffer by edan

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.