Wimdows.NET

Wim's .NET blog

CharSet enumeration for P/Invoke and StructLayout

Hongmeig blogs about the difference between Marshal.SizeOf(typeof(char)) and sizeof(char).

The reason for this is that a char in unmanaged code (P/Invoke, marshalling) is 1 byte and like Hongmeig says in the .NET framework a char is Unicode, so 2 bytes.

What I'd like to point out though, is that we do have control over the character set when using P/Invoke calls and the physical layout of structs with regards to the character set. This can be very useful for string marshalling.

It can be achieved by using the System.Runtime.InteropServices.CharSet enumeration {Ansi,Auto,None,Unicode}, which can be applied on the DllImportAttribute and the StructLayoutAttribute.

For instance:

using System; 
using System.Runtime.InteropServices;
class Class1
{
static void Main(string[] args)
{
unsafe
{
Console.WriteLine("Marshal.SizeOf(typeof(TestAnsi) shows: " + Marshal.SizeOf(typeof(TestAnsi)));
Console.WriteLine("Marshal.SizeOf(typeof(TestUnicode) shows: " + Marshal.SizeOf(typeof(TestUnicode)));
}
}
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct TestAnsi
{
public char testbyte;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct TestUnicode
{
public char testbyte;
}

This results in the following output:

Marshal.SizeOf(typeof(TestAnsi) shows: 1
Marshal.SizeOf(typeof(TestUnicode) shows: 2

This CharSet enumeration can be applied in a similar fashion on the DllImportAttribute.

Posted: Aug 19 2004, 11:43 AM by Wim | with 7 comment(s)
Filed under:

Comments

TrackBack said:

^_^,Pretty Good!
# April 10, 2005 2:26 AM

kikus said:

тема не раскрыта.. может есть ещё информация по этому поводу?

# June 12, 2010 10:26 PM

Rodseshow said:

Просто хорошая страничка

# February 4, 2011 7:38 PM

Lecegaxew said:

Diky za zajimavy blog

# March 4, 2011 4:02 AM

praca said:

ou did a unselfish nuisance creating a regulations respecting the usefulness photographers like me with no finish feeling with stock. You explained so much that I needed to know. I interpret it with vehement interest. You are a noteworthy writer. I’m on top of the life to get met you and skilled in that you are as productive and clubby as your be employed indicates. Your advancement is appreciated.

# April 13, 2011 1:30 AM

greexereirm said:

nice, very nice<a href="xvncuoi.wordpress.com/.../a>

# July 19, 2011 2:17 PM

ReageasencyuI said:

Это правда... что у людей с невысоким интллектом совсем нет... чувства юмора??    

[url=http://xn--c1aeb8eua.xn--p1ai/]бесплатные полно картинки с еленой белковой[/url]

# January 28, 2012 7:35 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)