Unexpected behavior when using both alias this and object pointer
xiren7 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 12 06:52:03 PST 2017
The problem and the code:
import std.stdio: writeln;
import core.stdc.stdlib: malloc;
struct Impl {
ubyte[8] payload;
}
class Foo {
Impl *impl;
alias impl this;
this()
{
impl = cast(Impl*) malloc(Impl.sizeof);
}
}
class Foo2 {
ubyte[8] payload;
}
void main()
{
// alias T = Foo2;
alias T = Foo;
auto t = new T();
// what I want to do is:
// 1. cast t as pointer
// 2. passe the pointer to a extern(C) callback function
// 3. cast the pointer back to t in extern(C) callback
function
// 4. accesse the payload field
auto payload = (cast(T) cast(void*) t).payload; // -> crashs
// the right way to get the address of the t object
writeln(*cast(void**) &t); // -> 278E3373000
// the unexpected behavior
// the obvious(but wrong) way to get the address of the t
object
writeln(cast(void*) t); // -> 278E164DAB0
// because of alias this
// cast(void*) t == cast(void*) t.payload
writeln(cast(void*) t.payload); // -> 278E164DAB0
}
My question is should let the compiler generate a warning about
this unexpected(maybe) behavior?
More information about the Digitalmars-d-learn
mailing list