Search code examples
c#clrmarshallingunmanagedlanguage-interoperability

What do HRESULT, DWORD, and HANDLE mean in unmanaged code?


I was reading about Marshaling. and im confused because what does mean this in unmanaged code. HRESULT, DWORD, and HANDLE. The original text is:

You already know that there is no such compatibility between managed and unmanaged environments. In other words, .NET does not contain such the types HRESULT, DWORD, and HANDLE that exist in the realm of unmanaged code. Therefore, you need to find a .NET substitute or create your own if needed. That is what called marshaling.


Solution

  • short answer:

    it is just telling you that you must "map" one data type used in one programming language to another data type used in a different programming language, and the data types must match.

    quick answer:

    For this one, the details may not be correct, but the concept is.

    These are a few of the data types defined in the Windows header files for C/C++. They are "macros" which "abstract" the primitive data types of C/C++ into more meaningful data types used in Windows programming. For instance, DWORD is really an 32-bit unsigned integer in C/C++, but on 64-bit processors, it is defined in the header files as a 64-bit unsigned integer. The idea is to provide an abstraction layer between the data type needed by the processor and the data types used by the language.

    During marshalling, this "dword" will be converted to the CLR data type you specify in the DllImport declaration. This is an important point.

    Let's say you want to call a Windows API method that takes a DWORD parameter. When declaring this call in C# using DllImport, you must specify the parameter data type as System.UInt32. If you don't, "bad things will happen".

    For example, if you mistakenly specify the parameter data type as System.UInt64. When the actual call is made, the stack will become corrupt because more bytes are being placed on the stack then the API call expects. Which can lead to completely unexpected behavior, such as crashing the application, crashing Windows, invalid return values, or whatever.

    That is why it is important to specific the correct data type.

    data types in question:

    • DWORD is defined as 32-bit unsigned integer or the CLR type System.UInt32.
    • HANDLE is the CLR types IntPtr, UintPtr, or HandleRef
    • HRESULT is System.Int32 or System.UInt32

    References: