Why are void[] contents marked as having pointers?
Vladimir Panteleev
thecybershadow at gmail.com
Sun May 31 14:14:26 PDT 2009
On Sun, 31 May 2009 23:11:57 +0300, grauzone <none at example.net> wrote:
>> 3) It's very rare in practice that the only pointer to your object
>> (which you still plan to access later) to be stored in a
>> void[]-allocated array! Remember, the properties of memory regions are
>> determined when the memory is allocated, so casting an array of
>> structures to a void[] will not lose you that reference. You'd need to
>> move your pointer to a void[]-array (which you need to allocate
>> explicitly or, for example, concatenating your reference to the
>> void[]), then drop the reference to your original structure, for this
>> to happen.
>
> void[] = can contain pointers
> ubyte[] = can not contain pointers
>
> void[] just wraps void*, which is a low level type and can contain
> anything. Because of that, the conservative GC needs to scan it for
> pointers. ubyte[], on the other hand, contains sequences of 8 bit
> integers. For untyped binary data, ubyte[] is the most correct type.
>
> You want to send it over network or write it into a file? Use ubyte[].
> The data will never contain any pointers. You want to play low level
> tricks, that involve copying around arbitrary memory contents (like
> boxing, see std.boxer)? Use void[].
std.boxer is actually a valid counter-example for my post.
The specific fix is simple: replace the void[] with void*[].
The generic "fix" is just to add a line to http://www.digitalmars.com/d/garbage.html adding that hiding your only reference in a void[] results in undefined behavior. I don't think this should be an inconvenience to any projects?
> You shouldn't cast structs or any other types to ubyte[], because the
> memory representation of those type is highly platform specific. Structs
> can contain padding, integers are endian dependend... If you want to
> convert these to binary data, write a marshaller. You _never_ want to do
> direct casts, because they're simply unportable. If you do the cast, you
> have to know what you're doing.
Thanks for the advice, but I actually know what I'm doing. Unlike C, D's structure alignment rules are actually part of the specification. If I wanted my programs to be safe/cross-platform/etc. regardless of execution speed, I'd use a scripting or VM-ed language.
--
Best regards,
Vladimir mailto:thecybershadow at gmail.com
More information about the Digitalmars-d
mailing list