Address of data that is static, be it shared or tls or __gshared or immutable on o/s <x>

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 6 08:55:35 PDT 2017


On 09/06/2017 08:27 AM, Cecil Ward wrote:
 > If someone has some static data somewhere, be it in tls or marked shared
 > __gshared or immutable or combinations (whatever), and someone takes the
 > address of it and pass that address to some other routine of mine that
 > does not have access to the source code of the original definition of
 > the object in question, then is it possible to just use 'the address'
 > passed without knowing anything about that data? I'm assuming that the
 > answer might also depend on compilers, machine architectures and
 > operating systems?
 >
 > If this kind of assumption is very ill-advised, is there anything
 > written up about implementation details in different operating systems /
 > compilers ?

Yes, they are all valid operations. Further, the object need not be a 
static one; you can do the same with any object even it's on the stack. 
However,

- The object must remain alive whenever the other routine uses it. This 
precludes the case of the object being on the stack and the other 
routine saving it for later use. When that later use happens, there is 
no object any more. (An exception: The object may be kept alive by a 
closure; so even that case is valid.)

- Remember that in D data is thread-local by default; e.g. a module 
variable will appear to be on the same address to all threads but each 
thread will have its own copy. So, if the data is going to be used in 
another thread, it must be defined as 'shared'. Otherwise, although the 
code will look like it's working, different threads will be accessing 
different data. (Sometimes this is exactly what is desired but not what 
you're looking for.) (Fortunately, many high-level thread operations 
like the ones in std.concurrency will not let you share data unless it's 
'shared'.)

Ali



More information about the Digitalmars-d-learn mailing list