Cast a struct to void*

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 9 11:03:04 PST 2015


On 1/9/15 1:50 PM, John Colvin wrote:
> On Friday, 9 January 2015 at 18:35:56 UTC, anonymous wrote:
>> On Friday, 9 January 2015 at 18:25:42 UTC, John Colvin wrote:
>>> struct S
>>> {
>>>    void* p;
>>> }
>>>
>>> void main()
>>> {
>>>    S s;
>>>    auto a = cast(void*)s; //Error: e2ir: cannot cast s of type S to
>>> type void*

This is actually a compiler bug! I will check to make sure it's not 
already filed, and file if it's not. However, I don't think the code 
should work, it just shouldn't print e2ir.

>>> }
>>>
>>> Is there are a good reason for this being disallowed?
>>
>> You'd expect `cast(void*)s == s.p`? That doesn't work for any type of p.
>
> I was expecting it to work regardless of the type of p. I have an 8 byte
> (on x86_64) struct which I want to reinterpret as a void*
>
>> You can do it with a slightly fancier (and more dangerous) cast:
>> `*cast(void**)&s`.
>
> Yuk. Better than nothing though. Thanks :)

This is what reinterpret_cast from C++ does.

-Steve


More information about the Digitalmars-d-learn mailing list