I don't see anything particularly wrong with your approach, but I have a few thoughts:

  1. buf[i] = (int)SvNV(*elem);

    buf[] is define as unsigned char, but you're retrieving reals, and casting them to signed ints?

  2. If you are going to pass in an array of ints or reals, you should really check they will fit into an unsigned char or cast appropriately to ensure they will.

    Maybe that should be buf[i] = (unsigned char)SvNV(*elem); or even buf[i] = (unsigned char)SvUV(*elem);

  3. I'll be passing the char buffer and len to an external C function.

    Perl's string scalars can hold any unsigned char value, and carry their length, so why not just pass the pointer and length from a scalar argument?

    That way you cannot be passed out of range values so don't have to deal with them.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
In the absence of evidence, opinion is indistinguishable from prejudice.

In reply to Re: Is this a sane/safe way to pass an aref into a C function? by BrowserUk
in thread Is this a sane/safe way to pass an aref into a C function? by stevieb

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.