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.
Use int. Reason being, if I change "AutoRestartShell" with a uint variable:
the data type in the Registry Editor changes to "REG_SZ". If I ask for that value to be returned with:
a string gets returned.
If, however, I change "AutoRestartShell" with an int variable:
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.
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
.It's unsigned so map it to
uint
.According to official Platform invoke data types mapping table
DWORD
corresponds toSystem.UInt32
in C#.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:
Sadly,read Registry must use int otherwise throw exception.this microsoft code:
although release is REG_DWORD