ReinhardE has asked for the wisdom of the Perl Monks concerning the following question:

I am writing a Perl backend for OpenLDAP. I need to pass C structures to Perl into Perl objects. One way to achieve this is via the Perl Stack. call first new to create the object, put every variable from the struct onto the stack, and call the init method wich imports the data into Perl Space. Would it not be more performent to put a pointer to the structure onto the stack and let then Perl fiddle around with the structure ? Maybe that not the whole structure is needed, so the further methods use also what's needed ? Thx for any advice

Replies are listed 'Best First'.
Re: Embedding Perl in C - C structs
by Joost (Canon) on Feb 04, 2005 at 12:40 UTC
    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.

      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.
Re: Embedding Perl in C - C structs
by Corion (Patriarch) on Feb 04, 2005 at 12:59 UTC

    If all you need are C structures, and ways to inspect and change them via Perl, the Convert::Binary::C module can do that - but I believe I told you that already on the Frankfurt.pm mailing list :-)

      Thx for the advice, yes I got it already from Frankfurt. I need to understand the module a little bit better. I think this resolves the 2nd problem, dealing with the C structures migrated into Perl space in some magic way, via the Perl stack using XS.
      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.