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

Esteemed Monks,
I have been playing with Inline::C and the Perl API recently. What a fun way to program!!

Here is my question:

Simply put, I'm accessing an external C-Library with Inline::C, and I want the C constructor wrapper to bless a hashref, not a scalar. The object, then, could call other wrappers as well as storing some other data in its slots. Let me illustrate this with some code:

package Foo; ## Inline part skipped. __C__ SV* new() { HV* hv = newHV(); Foo* foo = newFoo(); //C constructor. // Now, do something with hv and foo, then return blessed_hashref; } void setName(SV* obj, char* name) { Foo* foo = get_foo_from(obj); // and call the Foo-C method: Foo_set_name(foo); } package main; my $foo = Foo->new(); $foo->setName("Lorelai"); $foo->{shortname} = "Rory";

Does this make sense? Or should I not bother the blessed scalar and simply create a hash based Perl class to wrap it?

Thanks!

Replies are listed 'Best First'.
Re: Perl API,external C library and blessing a hashref
by mpeppler (Vicar) on May 19, 2004 at 16:10 UTC
    Either technique works. I've blessed my objects at the C level (though I use XS, not Inline::C). In addition, I've used the '~' magic to store an SV that holds the pointer to the data for the C struct that describes the object.

    Something like

    thv = (HV*)sv_2mortal((SV*)newHV()); sv = newSViv((IV)info); sv_magic((SV*)thv, sv, '~', "CTlib", 5); SvRMAGICAL_on((SV*)thv); rv = newRV((SV*)thv); stash = gv_stashpv("Sybase::CTlib::_attribs", TRUE); (void)sv_bless(rv, stash);
    Then you can get the "info" structure from the hashref via mg_find().

    Note that this code is pretty old, and there might be better ways to do this sort of things in more recent versions of perl.

    Michael

      Thanks Michael!! It's working like a charm. My gawd! It's beautiful...

      I need to look into the MAGIC* now. :)

      Ogla
        Go read the perlguts and perlapi docs for some information about this...

        Michael