String[] pointer to void* and back

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Sep 19 12:08:10 PDT 2014


On Friday, 19 September 2014 at 12:14:19 UTC, seany wrote:
> On Thursday, 18 September 2014 at 22:16:48 UTC, Ali Çehreli 
> wrote:
>
>> If you are holding an address in a void*, you must make sure 
>> that the original object is still at that location when you 
>> attempt to access the object.
>
> Does that mean, that there is no way to make a global stack 
> accessible accross modules, of runtime generated stack 
> variables, unless i define such variable species beforehand?

I don't understand your usage of the word "stack". There may
confusion about the meaning of (the) stack.

As far as I understand, you want to store values (or references
to values) of arbitrary types. You tried to use `void*` for that.
That works, as long as the value stays where the pointer points.
Which is not the case when the value is on the call stack [1]
(i.e. "the stack"). If you put the value on "the heap" [2] (not
to be confused with the data structure), it works fine:

---
import std.stdio;

class C
{
    void* v;

    void dothings()
    {
       string[] ss = ["1", "2", "4"];
       string[][] onTheHeap = new string[][1]; /* Allocate space on
the heap. Can't `new` a single string[] directly, so make it an
array of length 1. */
       onTheHeap[0] = ss; /* Copy ss from the stack to the heap. */
       v = onTheHeap.ptr; /* Could also be `&onTheHeap[0]`, but not
`&onTheheap`. */
    }
}


void main()
{
     C c = new C;
     c.dothings();

     string[]* sh;
     sh = cast(string[]*)c.v;

     string[] si = *sh;
     writeln(si); /* ["1", "2", "4"] */
}
---

By the way, the struct S isn't really buying you anything over
using void* directly.

[1] http://en.wikipedia.org/wiki/Call_stack
[2] http://en.wikipedia.org/wiki/Heap_(programming)


More information about the Digitalmars-d-learn mailing list