开发者

Working with HResult, interop and related things in C#

开发者 https://www.devze.com 2022-12-09 19:59 出处:网络
I am working on a project in C# to create a forms application. I would like to use IFileDialog and other functionality that is part of the native Windows API (or however ti should be called).

I am working on a project in C# to create a forms application. I would like to use IFileDialog and other functionality that is part of the native Windows API (or however ti should be called).

Starting out I knew absolutely nothing about interop or the Windows API. I am starting to learn but at times it can be hard to find very ba开发者_JAVA百科sic info on certain aspects. Therefore I have a (probably trivial/stupid) questions:

HResults are used often. As I understand, HResults are nothing more than a 32 bit entity where the different bits supply info on the result of certain operations. In some code I found online I often see things like int hres = -2147467259;. Being a total noob I went to check what this means. -2147467259 is 0xFFFFFFFF80004005 and in the online documentation at MSDN I can see that 0x80004005 signifies E_FAIL aka unspecified error. My question is, what is up with the FFFFFFFF part? Couldn't they just have used int hres = 0x80004005? Maybe this is very obvious and I'm a total noob, but still :)


The FFFFFFFF part is because your HResult is negative.

That's how computers store negative numbers using Two's complement.

Check out this calculation (my emphasis):
-2147467259 = 0xFFFFFFFF80004005
-2147467259 + 2^32 (rollover) = 2147500037 = 0x80004005


On 32 bit platforms an int is 32 bits long which is 4 bytes of 8 hexadecimal digits. So E_FAIL would be 0x80004005, (which is what the code you pasted shows. If you dump this value on a 64 bit machine then it'll take up twice as much storage and since numbers are sign extended and the leading 8 (binary 100) means the sign bit is 1 then it's ones all the way. 1111 in binary is F in hex which brings all the Fs you see.

0

精彩评论

暂无评论...
验证码 换一张
取 消