Nick Ing-Simmons wrote:

>Steve Hay <[EMAIL PROTECTED]> writes:
>  
>
>>Is it safe to store a pointer to a C struct in an SV?
>>    
>>
>
>Yes, provided the lifetime of the data pointed to is suitable.
>
>  
>
>>   MY_STRUCT my_struct;
>>   sv = newSVuv((unsigned long) &my_struct);
>>   SvIOK_only_UV(sv);
>>    
>>
>
>Your my_struct is on the stack in the XS function - memory gets 
>reused when XS returns.
>
>What I tend to do is put the struct in the string part of a SvPV
>
>     SV *sv = newSV(sizeof(MY_STRUCT));
>     MY_STRUCT *my_struct = (MY_STRUCT *) SvPVX(sv);
>
Thanks, Nick.  I was beginning to think that it might be something like 
that because of the random nature of the failures.

I've found that the following scheme (a variation on my original 
attempt) also seems to work:

    MY_STRUCT *my_struct;
    SV *sv;
    Newz(1, my_struct, 1, MY_STRUCT);
    sv = newSVuv(PTR2UV(my_struct));

(with a "Safefree(my_struct)" later on).

I believe this is OK because *Perl* has now allocated the struct's 
memory so it doesn't get reused until I ask Perl to free it.  Is that 
correct, or have I just struck lucky with it working so far?

Are they are pros/cons of the two schemes that work?

- Steve



------------------------------------------------
Radan Computational Ltd.

The information contained in this message and any files transmitted with it are 
confidential and intended for the addressee(s) only.  If you have received this 
message in error or there are any problems, please notify the sender immediately.  The 
unauthorized use, disclosure, copying or alteration of this message is strictly 
forbidden.  Note that any views or opinions presented in this email are solely those 
of the author and do not necessarily represent those of Radan Computational Ltd.  The 
recipient(s) of this message should check it and any attached files for viruses: Radan 
Computational will accept no liability for any damage caused by any virus transmitted 
by this email.

Reply via email to