Initializing a class pointer

Bekenn leaveme at alone.com
Sat Feb 26 19:43:52 PST 2011


On 2/26/2011 5:33 PM, Tyro[a.c.edwards] wrote:
>> Ok, that's essentially what I have, except that I used Controller pCtrl
>> vice auto. WinGetLong however, is a template that calls
>> GetWindowLongPtrA() and casts it's result (in this case) to Controller.
>> GetWindowLongPtrA() returns LONG_PTR (aka int) and therefore fails
>> miserably on the cast attempt. On the reverse, there is a WinSetLong
>> that attempts to cast Controller to int for use with
>> SetWindowLongPtrA(). Neither of these functions complain when I use
>> Controller* but I end up with the problem of trying to initialize a
>> pointer with a reference to Controller.
>
> By the way, in original C++ code WinGetLong and WinSetLong are both
> using a reinterpret_cast to achieve this monkey magic. To the best of my
> knowledge, there is no reinterpret_cast facility in D. So the question
> would be, why would it have been necessary to use reinterpret_cast in
> the first place and how can similar effect be obtained in D? What was
> being reinterpreted? Was it the address of the class or the value some
> private value contained therein?

What you need here is a double cast; class references can be cast to 
void*, and from there to LONG_PTR.  The reverse also works:

auto WinGetLong(T)(HWND hwnd)
{
	return cast(T)cast(void*)GetWindowLongPtrA(hwnd, GWLP_USERDATA);
}

void WinSetLong(T)(HWND hwnd, T o)
{
	SetWindowLongPtrA(hwnd, GWLP_USERDATA, cast(LONG_PTR)cast(void*)o;
}


More information about the Digitalmars-d-learn mailing list