Lo1234
Lo1234

Reputation: 45

Safeway to cast Windows CreateFile handle to 'long' and vice versa in C++

Is it safe or correct way to cast windows CreateFile return type ("HANDLE") to long datatype and vice versa ie long value to HANDLE type? If the approach is correct then how it can be done in Windows 7 Environment? 32 bit handling will be fine but any portable code to handle 64 bit version it can be a best shot.

Upvotes: 0

Views: 396

Answers (2)

lodo
lodo

Reputation: 2383

HANDLE is probably implemented as an opaque pointer, so casting it to/from uintptr_t shouldn't give you problems. But it is not really safe. No conversion from implementation-defined datatype to integer is safe, and no conversion from pointer to integer is safe.

Pointers should remain pointers.

Implementation-defined types should not be converted.

Integer should stay integers.

Upvotes: 1

There is no way to correctly cast a HANDLE to a long and back.

Consider that on 64-bit Windows, long is 32 bits long and HANDLE is 64 bits long.

Upvotes: 0

Related Questions