Pointer to Object Questions
John Kiro
johnkirollos at yahoo.com
Sat Dec 30 14:41:58 PST 2006
== Quote from Kirk McDonald (kirklin.mcdonald at gmail.com)'s article
> Correct. D has no member indirection operator (->) as C and C++ do. You
> just use . for everything. (The compiler knows if you're talking about a
> pointer or not, and is smart enough to figure it out.)
hmmm.. thanks for clarifying this point.
> Since classes are by reference, anyway, there's no good reason to throw
> around pointers to objects.
> If you /really/ want a pointer to a class instance, you can cast the
> reference to a void*:
> Foo f = new Foo;
> void* ptr = cast(void*)f;
> (This should reinforce the fact that class references are just
> pointers.) However, this is pretty darned hackish, and usually serves
> little purpose. (Once cast to void*, you can't use that void* to access
> members of the class without casting it back.) The only use I can think
> of for this is when keeping references to GC-controlled objects.
Speaking about casting, there is usually a need to cast a reference to an
integer & vice-versa; I'm specifically pointing to the case of using a function
like the Win32 API function SetWindowLong(), in order to link a window with a
corresponding object. Here is how I did it:
//Linking view window to view obj:
SetWindowLong(hwndView,0,cast(uint)(cast(CView*)this));
//retrieve the object given the window handle:
cast(CView)cast(CView*)GetWindowLong(hwndView,0);
Casting to void* instead of CView* also compiled without errors.
So is this the usual way of doing such thing? I mean double casting?
Because casting an object to int or vice-versa is rejected by the compiler.
Regards
John
More information about the Digitalmars-d-learn
mailing list