Wednesday, June 30, 2004

How false can also be true

Recently, I spent a considerable amount of time tracking down a bug which consisted of a boolean value being passed through a number of methods and constantly evaluating to true irrespective of how it was set.

It turned out that a conversion was made implicitly from short to long during a COM call.

Not a problem I hear you say, as C++ does implicit conversions from short to long which will handle the conversion neatly.

Well, C++ might but COM doesn't.
The cause was confusion over the data type. It was passed in as a short and handled as a long. So the memory after passing 0x0000 as a short was 0xCCCC0000 as a long.

neatly converting false to true!

This both reminds us we should always use VARIANT_BOOL for booleans in com and also tells us a simple class could help.

Well, guess what, someone has written one, it's called COMBOOL and handles lots of nasty conversions for you.

No comments: