This works for dynamically allocating memory (an array of char):

SV * create_image(int size) {
    char * image;
    New(0,image,size,char);
    memset(image,CLEAR,size);
    return sv_setref_pv(newSViv(0),"image", (void *)image);
 }

void destroy_image(SV * p) {
    char * image = (char *) SvIV(SvRV(p));
    Safefree(image);
 }

And to access the memory as an array of char:

void clear_image(SV * p,int size) {
    char * image = (char *) SvIV(SvRV(p));
    memset(image,CLEAR,size);
 }


I would assume something similar would work for a struct, something along
the lines of:

typedef struct {
    SV * suit;
    int value;
 } CARD;

SV * create_card(int size) {
    CARD * my_card;
    New(0,my_card,size,CARD);
    memset(my_card,CLEAR,size*sizeof(CARD));
    return sv_setref_pv(newSViv(0),"card", (void *)my_card);
 }

which would allocate memory for an array of cards (a 'deck' so to speak),
and return the pointer to the array.  I would have done a function to create
one card, but it would not have been any simpler.  And for whatever reason,
I have trouble getting Inline to properly recognize and bind functions that
pass no params (int myfunc(void)).

And to hand out cards from Perl:

void deal_card(SV * p,SV * suit,int value) {
    CARD * my_card = (CARD *) SvIV(SvRV(p));
    my_card->suit = suit;
    my_card->value = value;
    return;
 }

I'm not 100% sure on the "SvIV(SvRV(p))" part -- It's what works for an
array of char.

Hope this was helpful.

--
Dave

Reply via email to