Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON'?

What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON' for an x64 target build?

In particular with a normal C-Style cast, I get this warning when compiling with an x64 config:

warning C4312: 'type cast' : conversion from 'OLE_HANDLE' to 'HICON' of greater size

Here is the offending code:

imgList.Add((HICON)ohIcon);

The above code works fine for me, but I want to get rid of the warning when building for x64.

like image 803
Brian R. Bondy Avatar asked Dec 18 '22 09:12

Brian R. Bondy


2 Answers

The H gives it away, in this case the library code has created a distinct type to give you a little more type safety (in the days of old C APIs).

They are actually both HANDLEs, which is a kernel object that doesn't really care what the resource is, just that you have a 'handle' to it. Remember the API is a C one, so use C style casts, and when you come to delete it, use DeleteObject().

edit: 64 bits eh... the problem's because MS updated Handles to be 64 bits, but left the OLE stuff alone. Fortunately, all they did was pad the extra bits with zeros.

Try using the LongToHandle conversion routines and see the MIDL porting guide - scroll about halfway down to the "USER and GDI handles are sign extended 32b values" section.

like image 57
gbjbaanb Avatar answered Mar 07 '23 01:03

gbjbaanb


Assuming you're using Microsoft Visual Studio based on the question...

If you are developing only for 32-bit targets, you may choose to disable this (and some other similar warnings) by turning off the project option "Detect 64-bit Portability Issues" (C++ compiler option /Wp64).

If you are developing for 64-bit targets as well, then @Harper is probably right and you'll need to do some more digging on the right way to handle this. You might want to read this white paper as a starting point; go to the section about USER and GDI handles.

like image 22
Patrick Johnmeyer Avatar answered Mar 07 '23 00:03

Patrick Johnmeyer