String[] pointer to void* and back

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 18 14:49:27 PDT 2014


On 09/18/2014 02:35 PM, seany wrote:

 > struct S
 >    {
 >      void *v;
 >    }
 >
 > class C
 > {
 >
 >
 >    S* sx = new S;
 >
 >    void dothings()
 >    {
 >       string[] ss = ["1", "2", "4"];

Note that ss is a local variable of a druntime type equivalent of the 
following:

struct D_Slice_of_strings_
{
     size_t length;
     string * ptr;
}

Although the elements that are accessed through .ptr are in dynamic 
memory and owned by the GC, the local struct object (i.e. ss) itself is 
on the program stack. It will be gone upon leaving dothings().

 >       string[] *s;
 >       void *vv;
 >
 >       s = &ss;
 >       vv = s;
 >
 >       sx.v = vv;
 >
 >    }

As a demonstration, one solution is to make ss a member variable. Then, 
it would live as long as v lived. However, ss can be in some other 
long-lived container as well.

Ali



More information about the Digitalmars-d-learn mailing list