xs - Perl SV value from pointer without copy -
how create sv value null terminated string without copy? newsvpv(const char*, strlen)
without copy , moving ownership perl (so perl must release string memory). need avoid huge memory allocation , copy.
i found following example:
sv *r = sv_newmortal(); svpok_on(r); sv_usepvn_mg(r, string, strlen(string) + 1);
but don't have deep knowledge of xs internals , have doubts.
if want perl manage memory block, needs know how reallocate , deallocate it. memory knows how reallocate , deallocate memory allocated using allocator, newx
. (otherwise, have associate reallocator , deallocator each memory block.)
if can't allocate memory block using newx
, best option might create read-only sv svlen
set zero. tells perl doesn't own memory. sv blessed class has destructor deallocate memory using appropriate deallocator.
if can allocate memory block using newx
, can use following:
sv* newsvpvn_steal_flags(pthx_ const char* ptr, strlen len, const u32 flags) { #define newsvpvn_steal_flags(a,b,c) newsvpvn_steal_flags(athx_ a,b,c) sv* sv; assert(!(flags & ~(svf_utf8|svs_temp|sv_has_trailing_nul))); sv = newsv(0); sv_usepvn_flags(sv, ptr, len, flags & sv_has_trailing_nul); if ((flags & svf_utf8) && svok(sv)) { svutf8_on(sv); } svtaint(sv); if (flags & svs_temp) { sv_2mortal(sv); } return sv; }
note: ptr
should point memory allocated newx
, , must point start of block returned newx
.
note: accepts flags svf_utf8
(to specify ptr
utf-8 encoding of string seen in perl), svs_temp
(to have sv_2mortal
called on sv) , sv_has_trailing_nul
(see below).
note: code expects string buffer of scalars have trailing nul (even though length of buffer known , though buffer can contain nuls). if memory block allocated has trailing nul beyond end of data (e.g. c-style nul-terminated string), pass sv_has_trailing_nul
flag. if not, function attempt extend buffer , add nul.
Comments
Post a Comment