----- Original Message -----
From: "Paulo Filipe Andrade" <[EMAIL PROTECTED]>
.
.
However, an optimization could be done if I could avoid copying the
string I'm working on before returning it.
I found the following demo on one of my boxes.
-----------------------------------------
use warnings;
use Devel::Peek;
use Inline C => Config =>
BUILD_NOISY => 1;
use Inline C => <<'EOC';
SV * foo_1(int len) {
char * str;
SV * outsv;
int i;
srand(time((time_t) NULL));
New(1, str, len * sizeof(char), char);
if(str == NULL)
croak("Failed to allocate memory in foo_1()");
for(i = 0; i < len; ++i)
str[i] = rand() % 256;
outsv = newSVpv(str, len);
Safefree(str);
return outsv;
}
SV * foo_2(int len) {
SV * outsv;
char c;
int i;
outsv = NEWSV(0, len);
srand(time((time_t) NULL));
for(i = 0; i < len; ++i) {
c = rand() % 256;
sv_insert(outsv, i, 1, &c, 1);
}
SvPOK_on(outsv);
SvCUR_set(outsv, len);
*SvEND(outsv) = 0;
return outsv;
}
SV * foo_3(int len) {
SV * outsv;
char c;
int i;
outsv = NEWSV(0, len);
srand(time((time_t) NULL));
for(i = 0; i < len; ++i)
SvPVX(outsv)[i] = rand() % 256;
SvPOK_on(outsv);
SvCUR_set(outsv, len);
*SvEND(outsv) = 0;
return outsv;
}
EOC
$len = 70;
$s1 = foo_1($len);
$s2 = foo_2($len);
$s3 = foo_3($len);
print "$s1\n$s2\n$s3\n";
Dump($s1);
print "\n11111111111111\n";
Dump($s2);
print "\n22222222222222\n";
Dump($s3);
print "\n33333333333333\n";
-----------------------------------------
It uses NEWSV(). I think newSV(), as already mentioned by Nicholas, is
deemed preferable.
foo_1() is essentially the same as presented earlier.
foo_2() fills the sv with random chars using sv_insert().
foo_3() fills the sv with random chars using SvPVX().
I haven't used the sv_2pvbyte_nolen() function that you mentioned. (It's
documented in perlapi, and therefore quite acceptable.)
In addition to SvCUR_set() and SvPOK_on(), which Nicholas also mentioned,
note the use of SvEND() to add the terminating "\0". I'm not entirely sure
whether that's necessary (or correct).
I also find that calling foo_2() produces a "Use of uninitialized value in
subroutine entry..." warning, for reasons that I can't immediately spot
(anyone ?), but foo_2() is probably a less desirable option than foo_3()
anyway.
Always happy to add to the confusion :-)
Cheers,
Rob