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:
This returned my int return value and the buffer to my perl program...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
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!
In reply to Perl XS: garbage-collecting my malloc'd buffer by edan
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |