Hi monks, I need a bit of input here...

I am writing my first perl (V5.6.1) extension...
I am calling a C-function which returns a string in pre-allocated buffer,
like this:

// my_func() puts up to len bytes into buffer int my_func(void *p_struct, char *buffer, int len)

Now, I want to call the function and return the buffer to my perl program.
My first shot at the XS code looked like this:

int my_xs_func(p_struct, OUTLIST buffer, len) void *p_struct; char *buffer; int len; CODE: buffer = (char *)malloc(len); RETVAL = my_func(p_struct, buffer, len); OUTPUT: RETVAL
This returned my int return value and the buffer to my perl program...

Of course, calling malloc() without calling free() rang
the memory-leak bells. So I poked around for a way to
write the XS code so perl will know about the buffer I malloc'd
and GC the buffer automagically...

So now, my code looks like this:

int my_xs_func(p_struct, OUTLIST buffer, len) void *p_struct; SV *buffer; int len; PREINIT: char *tmp_buffer; CODE: tmp_buffer = (char *)malloc(len); RETVAL = my_func(p_struct, tmp_buffer, len); buffer = sv_2mortal(newSVpv(tmp_buffer, 0)); free(tmp_buffer); OUTPUT: RETVAL

I think this solves my memory-leak problem, but
I am by no means sure that this is the right way to do it.
I got to this solution by poking around in comp.lang.perl, and
in perlxs, perlguts, etc., with a healthy dose of trial-and-error.

Can someone tell me if I am going in the right direction, and give a few pointers?

Thanks!

3dan


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

Title:
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.