c++ - Cast DWORD_PTR to class and vice versa without c-style cast -
according herb sutter's c++ coding standards: 101 rules, guidelines, , best practices programmer should avoid c-style casting:
c-style casts have different (and dangerous) semantics depending on context, disguised behind single syntax. replacing c-style casts c++-style casts helps guard against unexpected errors
i trying pass pointer p_ctrl
winapi callback function, want use dword_ptr parameter of callback function (below example working, contains c-style casts commented):
wndctrls* wndctrls::button ( wndctrls* const p_ctrl, hwnd hwnd, rect const &rc ) { p_ctrl->ctrl = createwindowex ( 0, l"button", p_ctrl->w_classnamebutton.c_str (), ws_visible | ws_child | bs_ownerdraw, rc.left, rc.top, rc.right, rc.bottom, hwnd, 0, (hinstance)getwindowlongptr ( hwnd, gwl_hinstance ), // problematic c-style cast know workaround p_ctrl ); setwindowsubclass ( p_ctrl->ctrl, wndctrls::ctrlproc, 0, (dword_ptr)p_ctrl ) ) // c-style cast return p_ctrl; } lresult callback wndctrls::ctrlproc ( hwnd hwnd, uint message, wparam wparam, lparam lparam, uint_ptr uidsubclass, dword_ptr dwrefdata ) { wndctrls* const p_ctrl = (wndctrls*)dwrefdata; // problematic c-style cast switch ( message ) { ... } return defsubclassproc ( hwnd, message, wparam, lparam ); }
i tried dynamic cast, gives me errors. reinterpret_cast
should not used @ (according sutter).
please there way casts using c++ provided functions?
sutter's advice that: advice. aren't hard , fast rules; they're suggestions encourage write safer, more robust code.
this 1 of cases advice doesn't work.
in many places, windows api needs able pass data may or may not pointer. such, uses pointer-sized integer, using c-style cast (remember windows api c-based) turn integer pointer. is safe because documentation requires be: if give windows garbage pointer value, you're breaking function's rules!
the standard c/c++ names pointer-sized integers intptr_t
(signed) , uintptr_t
(unsigned). however, windows predates c99 , c++11 (when these introduced), uses own names: long_ptr
(signed) , dword_ptr
, ulong_ptr
(unsigned). in addition, wparam
, lparam
, , lresult
pointer-sized, since window messages need deal pointers.
so go ahead , use c-style cast or reinterpret_cast<>
, whichever 1 prefer. other casts won't work because need interpret integer pointer, other casts won't let do.
you may need these anyway because there other places that, because windows api needs not in c usable other languages, subclassing replaced having object of struct derive first element of dervied struct. apparent in wm_notify
message, possible notification structs nmhdr
. keep in mind.
Comments
Post a Comment