----- Original Message ----- From: "Paulo Filipe Andrade" <[EMAIL PROTECTED]>
To: <inline@perl.org>
Sent: Thursday, July 31, 2008 2:59 AM
Subject: Allocating a char* and returning to Perl from a C function


Hello,

I have a C function that I need to call from Perl.
It goes a little something like this:

char *work(char *inString){
char *stringToReturn = (char *)malloc(2*sizeof(inString));

while(*inString){
// do some work on stringToReturn
inString++;
}
return stringToReturn;
}

The thing is, since I can't free stringToReturn, I need to have it garbage collected in the perl side. I have tried creating an SV * with the newSVpv* methods, passing in the stringToReturn and then freeing it, but I am always getting segmentation faults.


Better to allocate/free memory using New/Safefree instead of malloc/free.

One solution is to copy stringToReturn to an SV, free the memory associated with stringToReturn, and then return the SV. Here's an example:

-----------------------------------------
use warnings;
#use Devel::Peek;

use Inline C => <<'EOC';

SV * foo(char *x) {
   SV * ret;
   char * str2ret;
   STRLEN len = strlen(x);

   printf("%d\n", len);

   New(0, str2ret, len * 2, char);
   if(str2ret == NULL) croak("Failed to allocate memory for str2ret");

   // Do stuff

   ret = newSVpv(str2ret, len * 2);

   Safefree(str2ret);
   return ret;
}

EOC

$s = "hello world";
$r = foo($s);

print length($r), "\n";
#Devel::Peek::Dump($r);
-----------------------------------------

Not sure if I've allowed as you would want for the \0 (NULL) string terminator ... but hopefully you get the picture.
For me that script outputs:

11
22

Cheers,
Rob

Reply via email to