Marshal.Sizeof(typeof(char)) is not equal to sizeof(char)
Yes, believe your eyes. Marshal.SizeOf(typeof(char)) = 1, however sizeof(char) = 2. Reason? Not sure about the first one, i guess it is traditional C style while char used to be defined as one byte. However, in C#, char type is defined as unicode encoded, which means it will use 2 bytes. So when you make those native methods call, be sure to read the documentation and find out which char it is using. For example, LSA_STRING struct is definately different from LSA_UNICODE_STRING.
Note, in order to get to the sizeof() to compile, you have to include inside an unsafe block. For example,
class
Class1
{
[STAThread]
static void Main(string[] args)
{
unsafe
{
Console.WriteLine("Marshal.SizeOf(typeof(char) shows " + Marshal.SizeOf(typeof(char)));
Console.WriteLine("sizeof(char) shows " + sizeof(char));
}
}
}
And make sure you tell the compiler you are compiling this code using the unsafe mode. You can easily do this if you are compiling using VS.net. Just right click on the project, choose Properties, in the left pane, choose Configuration Properties->Build, and on your right pane, you will see "Allow unsafe code blocks" combo box, just choose true there.
Compile and run! you will see
Marshal.SizeOf(typeof(char) shows 1
sizeof(char) shows 2
Press any key to continue