Hi Monks,

When Perl communicate with XS, marshalling C to Perl SV is annoying and slow. So I try to just attach C data to a existing SV?:

use Devel::Peek; my $x = ""; Dump $x; ddd($x); Dump $x; use Inline 'C' => <<'CODE'; int ddd(SV* x){ char* dx = "dddddd\n"; char* bbb=NULL; Newx(bbb, 8, char); Copy(dx, bbb, 8, char); printf("string dx is %p \n", dx); printf("string bbb is %p \n", bbb); // sv_setpvn(x, dx, 8); #copy string to a SV // sv_usepvn(x, dx, 8); #segment fault! sv_usepvn(x, bbb, 8); #"attach" to a SV return 0; } CODE ########## output ########## SV = PV(0x559f4143cfd0) at 0x559f41461018 REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x559f414d58a0 ""\0 CUR = 0 LEN = 10 COW_REFCNT = 1 string dx is 0x7f12ed54f8d8 string bbb is 0x559f41462ad0 SV = PV(0x559f4143cfd0) at 0x559f41461018 REFCNT = 1 FLAGS = (POK,pPOK) PV = 0x559f41462ad0 "dddddd\n\0"\0 CUR = 8 LEN = 16
I found you can't attach a C point to a SV directly. You have to either create a mem chunk by Newx, then use sv_usepvn to attach, or use sv_setpvn to extend mem of SV by perl itself, otherwise you would got a segment fault(like sv_usepvn(x, dx, 8) do, dx is a char pointer to a C string as above). So, as the title of question, what difference between newX and C malloc? Is there a way to attach C memory to a existing SV( for performance)?

Thanks in advance!




I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction


In reply to What difference between malloc and Newx, how attach a C string to SV directly? by xiaoyafeng

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.