C++ cast to D cast again :)

div0 div0 at users.sourceforge.net
Sun Sep 30 08:46:56 PDT 2007


BLS wrote:
> Hi and sorry about picking on your nerves again  :(
> // C++
> class CWin
> {
> //
> static LRESULT CALLBACK WndProc(HWND hWnd, UINT uID, WPARAM wParam, 
> LPARAM lParam)
> {
>   CWin* pWnd=NULL;  // init pWnd
> }
> 
> // later ...
> CWin* pChild=reinterpret_cast<CWin*>((HWND)
> ::GetWindowLong(pWnd->GetDlgItem( ((( LPDRAWITEMSTRUCT )lParam)->CtlID) 
> ),GWL_USERDATA) );
> 
> 
> }
> 
> //our D class
> class CWin
> {
> static LRESULT WndProc(HWND hWnd, UINT uID, WPARAM wParam, LPARAM lParam)
> {
>   CWin pWnd=null;  // init pWnd as    ---reference !
> }
> /* instead of :
> CWin* pChild=reinterpret_cast<CWin*>
> we use
> CWin pChild = cast(CWin) cast(void*)
> 
> But I am not sure how to translate :
> ((HWND)
> ::GetWindowLong(pWnd->GetDlgItem( ((( LPDRAWITEMSTRUCT )lParam)->CtlID) 
> ),GWL_USERDATA) );
> */
> 
> // Later we have
> if (HIWORD(pWnd))
> 
> /*Since we are working with a ref. instead of a pointer this will not work.
> I guess I can use :
> */
> 
> if (HIWORD(cast(void*)pWnd))
> // can you confirm
> }
> 
> GetWindowLong() is a Windows Api func., sure you know it.
> So what the correct translation ?
> Bjoern
> Beside, I still wonder : Having a class A, Is A* pA a legal construct in D.
> What is pA from a technical view; a pointer to a reference ?

Even if you get this to compile it won't work.
(well it will till one day until it just crashes mysteriously)

At some point the garbage collector might decide move your Cwin object, 
invalidating the pointer you are trying to store with 
SetWindowLong/GetWindowLong.

You'll have to either allocation your cwin objects outside the garbage 
collectors control or pin the objects. (Don't know how you do this, 
depends on whether you are using phobos or tango)

You should probably look at how dfl interfaces with the Win32 API, 
http://www.dprogramming.com/dfl.ph as that library has solved these 
issues and you should be able to work out how it's doing all the 
necessary casting/pinning.


More information about the Digitalmars-d-learn mailing list