I have a C function that looks like:
int myfunction(char* error_string)

This function returns an error description in error_string if there is an error. I want to call this function from my Perl code but I'm not sure how to get the string back correctly. The following test code seems to work (sort of):

my $error = " "; mylib::myfunction($error); print $error;

This works as long as the string being returned is shorter than the number of spaces in the initialization of $error (10 spaces in this case), however any additional spaces in $error will still be printed after the error. For example, if the error returned is "Error 1", "Error 1   " will be printed with 3 spaces at the end. If the error returned is longer than 10 characters, the additional characters are truncated. I'm assuming this is becuase Perl counts the characters in a string instead of using null termination. Is there any way I can get Perl to "recount" the length of the string after returning from the function? I suppose I could search for the end of the string but it seems like there should be a better way to do this. Also, is there a better way to define the string I want to pass in to the function? The actual string needs to be 400 characters long and I'm not sure how to specify that I want a string with 400 characters. I suppose I could use a loop or the x operator to fill the string with spaces or some other character, but is there a better way to just allocate space for 400 characters?


In reply to Passing a string from C to Perl by Anonymous Monk

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, details, 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, summary, 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.