Should DWORD map to int or uint?

45,650

Solution 1

Well according to the MSDN DWORD is an unsigned integer with a range of 0 to 4294967295.

So ideally you should replace it with uint rather than int.

However, as you have spotted uint is non-CLS compliant so if your method is publicly visible you should use int and do the conversion. The corollary to that is that if your method isn't used outside your assembly you should mark it as internal rather than public. Then you'll be able use a uint.

Solution 2

It's unsigned so map it to uint.

Solution 3

A DWORD is, by (Microsoft's) definition, an unsigned 32-bit integer. It should map to whichever type your compiler uses to represent that.

These days it's most likely an unsigned int, but that's not a portable implementation. I know you're using C#, but to give you an example in a language I'm more familiar with, a typical implementation in C might be:

#if defined(SOME_HARDWARE_IMPLEMENTATION)
#define DWORD unsigned int
#elif #defined(SOME_OTHER_IMPLEMENTATION)
#define DWORD unsigned long
#elif #defined(YET_ANOTHER_IMPLEMENTATION)
#define DWORD something_else
#else
#error Unsupported hardware; cannot map DWORD
#endif

Solution 4

The CLS compliance warning applies only if the P/Invoke method is visible outside the assembly, which generally means the call is public. If the method is not externally visible, then it is acceptable to use uint.

Solution 5

Use int. Reason being, if I change "AutoRestartShell" with a uint variable:

regKey.SetValue("AutoRestartShell", uintVariable);

the data type in the Registry Editor changes to "REG_SZ". If I ask for that value to be returned with:

regKey.GetValue("AutoRestartShell");

a string gets returned.

If, however, I change "AutoRestartShell" with an int variable:

regKey.SetValue("AutoRestartShell", intVariable);

The data type stays as "REG_DWORD".

Why does this happen? No idea. All I know is that it does. Logic certainly would tell us that uint should be used but that changes the data type which we don't want.

Share:
45,650
user541686
Author by

user541686

Updated on March 30, 2020

Comments

  • user541686
    user541686 about 4 years

    When translating the Windows API (including data types) into P/Invoke, should I replace DWORD with int or uint?

    It's normally unsigned, but I see people using int everywhere instead (is it just because of the CLS warning? even the .NET Framework itself does this), and so I'm never really sure which one is the correct one to use.