Bugzilla – Bug 320710
Marshalling of fixed size char arrays in structs is unicode only
Last modified: 2007-09-15 21:24:46 UTC
---- Reported by r.gerosa@gmail.com 2006-03-30 05:57:08 MST ---- Description of Problem: When specifying the [StructLayout(CharSet=CharSet.Ansi)] in a struct and using Marshal.PtrToStructure to get the structure from a buffer, if there is a fixed size char array in the struct, it is marshaled as unicode chars (2 bytes), it should instead read ansi chars (1 byte) Steps to reproduce the problem: 1. Define a struct decorated with [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] and containing a fixed sixe char array: [MarshalAs (UnmanagedType.ByValArray, SizeConst=4)] public char[] test; 2. Unmarshal the struct from a buffer, using Marshal.PtrToStructure 3. The result is wrong here is an example of c# code reproducing the problem: using System; using System.Runtime.InteropServices; namespace test { [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)] public struct TestStruct1 { [MarshalAs (UnmanagedType.ByValArray, SizeConst=4)] public char[] test; } class MainClass { public static void Main(string[] args) { GCHandle handle; byte[] buffer = new byte[4] {(byte)'t',(byte)'e',(byte)'s',(byte)'t'}; int structSize = Marshal.SizeOf(typeof(TestStruct1)); Console.WriteLine("struct size: " + structSize); handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); TestStruct1 testStruct1 = (TestStruct1) Marshal.PtrToStructure( handle.AddrOfPinnedObject(),typeof(TestStruct1)); handle.Free(); Console.WriteLine("value: " + new String(testStruct1.test)); } } } Actual Results: struct size: 8 value: ?? Expected Results: struct size: 4 value: test How often does this happen? always Additional Information: the expected result is the one returned using .NET ---- Additional Comments From vargaz@gmail.com 2006-04-07 11:22:46 MST ---- Fixed in SVN. Unknown bug field "cf_op_sys_details" encountered while moving bug <cf_op_sys_details>Arch Linux 7.1</cf_op_sys_details> Unknown operating system unknown. Setting to default OS "Other".