[StructLayout(LayoutKind.Explicit)] public struct Repository { /// <summary> /// 仓库名称 /// </summary> [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)] public string Name; /// <summary> /// 指针 /// </summary> [FieldOffset(128)] public ushort location; }
我用sendmessage测试了下没问题 [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr ip, int a, int b, ref Repository c);重写的wndproc Repository r = (Repository)Marshal.PtrToStructure(m.LParam, typeof(Repository)); MessageBox.Show(r.Name);//name是前128个字符
结构体=》指针可以试试这个方法 Marshal.StructureToPtr
这里说明一下原因。
Structure得到的大小是不固定的。
当我用这个方法写入N个结构体之后
就是说我没法精确得到在这个结构体写入文件后的准确位置。
而且,我读取的时候很可能是类似与这样读取。
CopyMemory(文件指针,offset,sizeof(Repository)*65536);
我直接就Copy内存了就。这样的话Marshal.StructureToPtr这个方法没有用啊
public struct Repository
{
/// <summary>
/// 仓库名称
/// </summary>
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
public string Name; /// <summary>
/// 指针
/// </summary>
[FieldOffset(128)]
public ushort location;
}
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr ip, int a, int b, ref Repository c);重写的wndproc
Repository r = (Repository)Marshal.PtrToStructure(m.LParam, typeof(Repository));
MessageBox.Show(r.Name);//name是前128个字符
:[StructLayout(LayoutKind.Explicit,Pack=1,CharSet=CharSet.Unicode,Size=64+2)]
public unsafe struct Repository
{
/// <summary>
/// 仓库名称
/// </summary>
[FieldOffset(0)]
[MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]
public fixed char Name[32]; /// <summary>
/// 指针
/// </summary>
[FieldOffset(64)]
public ushort location; }//因为这样,我可以用
uint size =(uint)sizeof(Repository);
//直接获取结构体大小
//可以用
CopyMemory(文件指针,offset,sizeof(Repository)*65536);
//直接从文件一次性读取上万个结构并且把数据都填充进去。
不过还是谢谢你,这么用心,感谢。