| 
                ■No59866 (asuka さん) に返信
>>fixed ではなく、MarshalAs で UnmanagedType.ByValArray および SizeConst を使えばどうです?
> 当初そのようにしておりましたが、例外が発生するので
> unsafe fixedで定義しなおしました。
unsafe fixed 無しだとこんな感じ。
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TEST_STRUCT
{
    public int a;
    public int b;
    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I2, SizeConst = 3)]
    public short[] s;
}
public class Program
{
    public static void Main()
    {
        string filePath = @"C:\data.dat";
        using (BinaryWriter wrt = new BinaryWriter(new FileStream(filePath, FileMode.Create)))
        {
            unchecked
            {
                wrt.Write((int)0x11223344); // int a;
                wrt.Write((int)0xaabbccdd); // int b;
                wrt.Write((short)0xfedc);   // short s[0];
                wrt.Write((short)0xba98);   // short s[1];
                wrt.Write((short)0x7654);   // short s[2];
            }
            wrt.Close();
        }
        // ファイルの中身:
        //   44 33 22 11 DD CC BB AA  DC FE 98 BA 54 76
        byte[] bin = File.ReadAllBytes(filePath);
        Console.WriteLine("file = {0}", BitConverter.ToString(bin));
        TEST_STRUCT test_struct;
        using (Stream s = new FileStream(filePath, FileMode.Open))
        {
            byte[] buf = new byte[Marshal.SizeOf(typeof(TEST_STRUCT))];
            s.Read(buf, 0, buf.Length);
            IntPtr ptr = Marshal.AllocHGlobal(buf.Length);
            Marshal.Copy(buf, 0, ptr, buf.Length);
            s.Close();
            test_struct = (TEST_STRUCT)Marshal.PtrToStructure(ptr, typeof(TEST_STRUCT));
            Marshal.FreeHGlobal(ptr);
        }
        Console.WriteLine("  a  = 0x{0:x8}", test_struct.a);
        Console.WriteLine("  b  = 0x{0:x8}", test_struct.b);
        Console.WriteLine("s[0] = 0x{0:x4}", test_struct.s[0]);
        Console.WriteLine("s[1] = 0x{0:x4}", test_struct.s[1]);
        Console.WriteLine("s[2] = 0x{0:x4}", test_struct.s[2]);
        Console.ReadLine();
    }
}
  |