[Gambas-devel] Store GB_VARIANT in memory

Benoît Minisini gambas at ...1...
Mon Aug 13 21:58:10 CEST 2012


Le 11/08/2012 19:13, Tobias Boege a écrit :
> Hi,
>
> I want to save a GB_VARIANT into a buffer, Ref() the object inside, if any,
> and return in later properly. My code looks something like this:
>
> static void *val;
>
> BEGIN_METHOD(Store, GB_VARIANT value)
>
> 	/* Tried also GB_VARIANT here, but the error differs only, maybe
> 	 * because of the application... */
> 	GB.Alloc(&val, sizeof(GB_VARIANT_VALUE));
> 	GB.StoreVariant(ARG(value), val);
>
> END_METHOD
>
> BEGIN_METHOD_VOID(Restore)
>
> 	GB.ReturnVariant(val);
> 	GB.Free(&val);
>
> END_METHOD
>
> Suppose each Store() matches a Restore(), I get Segfaults in VALUE_write()
> and since I don't quite look through Gambas datatype and storage (yesterday
> crusaded against object reference counting successfully, though) I thought
> it's simpler to ask directly - the array types were not really helpful to
> me as I could not get to the exact point where memory allocation takes
> place. Or, if I were there (ARRAY_add_data()?), I didn't get it.
>
> BTW, the above is clearly simplified, I need allocating val dynamically.
>
> Regards,
> Tobi
>

Oops, I forgot you... :-)

A Gambas Variant is store inside a GB_VARIANT_VALUE structure. You don't 
need to allocate it on the heap.

// A Variant must be initialized to NULL

static GB_VARIANT_VALUE val = { T_NULL };

BEGIN_METHOD(Store, GB_VARIANT value)

   GB.StoreVariant(ARG(value), &val);

END_METHOD

BEGIN_METHOD_VOID(Restore)

   // The variant is copied in a temporary place.
   GB.ReturnVariant(&val);

   // Free the stored variant.
   // But you can't do it now, because the Variant will
   // be referenced after the function has returned only.
   // GB.StoreVariant(NULL, &val);

END_METHOD

As you can't release the Variant inside the Restore method, you must 
free the contents of 'val' in the '_exit' special method of your class.

Regards,

-- 
Benoît Minisini




More information about the Devel mailing list