Steve Hay <[EMAIL PROTECTED]> writes: >What's the best way to have an XSUB return a string (char *) when the >caller doesn't know how big that string will be?
At a mortal string SV: void my_xsub() CODE: { ST(0) = sv_2mortal(newSVpv(string,strlen(string)); XSRETURN(1); } I like that style because as soon as you have created the SV you know perl has a copy and can cleanup. You should get the same effect via char * my_xsub() CODE: { RETVAL = string; } OUTPUT: RETVAL or SV * my_xsub() CODE: { RETVAL = sv_2mortal(newSVpv(string,strlen(string)); } OUTPUT: RETVAL > >In C a function can't return a pointer to a function-static variable, >but in Perl you can get away with a function returning a reference to a >function-scoped lexical variable. > >Can you do (fake) this sort of thing in an XSUB? > >Presumably, if I malloced the space that I'm "returning a pointer to" >then it needs freeing up afterwards, but not before Perl has copied it >somewhere! Is a CLEANUP section good for that? > >As a (silly) test, the following XSUB seems to work, but I'd just like >to check that this is alright. > > char * > hello() > PREINIT: > char *text; > > CODE: > Newz(0, text, 13, char); > strcpy(text, "Hello, world"); > RETVAL = text; > > OUTPUT: > RETVAL > > CLEANUP: > Safefree(text); > >It's a cheat really, because the return value is not a pointer to "local >data" -- it's a pointer to a copy of it, the malloced local data itself >being freed again -- but at least the caller doesn't have to provide the >space for the data to be copied to. Perl never does provide space. In cases like this where you are going to Newz() the space anyway you can avoid an extra copy when returning the value with sv_usepvn() > >Is there a better way to have a "Perlish" calling style like > > $text = my_xsub(); > >when the caller doesn't know in advance how big that $text is going to be? > >Thanks, >- Steve