in reply to Embedding Perl in C - C structs

A way to do it, is to create a perl object directly on top of the C struct using XS. An example:

Create perl object from C struct:

/* assume "buffer" is a C struct */ /* assume "package" is a perl string naming the package to bless the object in */ SV* self = newSViv(PTR2IV(buffer)); SV* ref = sv_bless(newRV_noinc(self),gv_stashsv(package,1)); /* ref is now a perl object containing a pointer to the "buffer" s +truct */

and vice versa:

if (sv_derived_from(sv, "Expected::Package")) buffer_pointer = (buffer_type*) SvIV((SV*)SvRV(perlobject));

See the perlxstut manpage for an intro into writing XS.

update: ofcourse, you then need to write accessor methods in XS to handle getting/setting struct data. Also, I recommend reading the "Extending and Embedding Perl" book.

Replies are listed 'Best First'.
Re^2: Embedding Perl in C - C structs
by ReinhardE (Sexton) on Feb 05, 2005 at 09:20 UTC
    Thx, this helps very much, I'll try it out immediately. After having passed the pointer to the C-struct to Perl space I think to use Convert::Binary::C as suggested by the 2nd comment on my question.
    Once this works my second question: what about performance ?
    Is it faster to fiddle around the C struct in C and use the Perl stack or give just a pointer to Perl and fiddle around the C-struct in Perl ? This needs more investigaton into the Convert::Binary::C. Any advice onto this would be highly appreciated.