Initializing a class pointer

Tyro[a.c.edwards] nospam at home.com
Sat Feb 26 17:33:26 PST 2011


On 2/27/2011 9:46 AM, Tyro[a.c.edwards] wrote:
> On 2/27/2011 8:52 AM, Simen kjaeraas wrote:
>> Tyro[a.c.edwards] <nospam at home.com> wrote:
>>
>>> I'm trying to convert some c++ code that defines
>>>
>>> T func(par...)
>>> {
>>> Controller * pCtrl = WinGetLong<Controller *> (hwnd);
>>> .
>>> .
>>> .
>>> switch(msg)
>>> {
>>> case FirstMatch:
>>> pCtrl = new Controller (hwnd, reinterpret_cast<CREATESTRUCT *>
>>> (lParam));
>>> break;
>>> }
>>> }
>>>
>>> I'm not sure why I need a pointer to the class, just trying to figure
>>> it out.
>>
>> Ah. You would not need a pointer to the class in D. Instead, your
>> function
>> would look something like this:
>>
>> T funct(par...)
>> {
>> auto pCtrl = WinGetLong!Controller(hwnd);
>> ...
>> switch(msg)
>> {
>> case FirstMatch:
>> pCtrl = new Controller(hWnd, cast(CREATESTRUCT*)lParam);
>> break;
>> }
>> }
>>
>> C++ classes are in some ways more akin to D structs, in that:
>>
>> class A {};
>>
>> void foo(){
>> A bar;
>> }
>>
>> bar would be allocated on the stack in C++, while in D bar would be a
>> pointer to a class instance on the heap. (well, it would be null, but
>> when you set it to something, that something would reside on the heap)
>>
>
> 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?


More information about the Digitalmars-d-learn mailing list