我正在尝试将 RECT 结构的数组(如下所示)转换为 IntPtr,因此我可以使用 PostMessage 将指针发送到另一个应用程序。
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
// lots of functions snipped here
}
// so we have something to send, in reality I have real data here
// also, the length of the array is not constant
RECT[] foo = new RECT[4];
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(foo[0]) * 4);
Marshal.StructureToPtr(foo, ptr, true); // -- FAILS
这会在最后一行给出 ArgumentException(“指定的结构必须是 blittable 或具有布局信息。”)。我需要以某种方式使用 PostMessage 将这个 RECT 数组传递给另一个应用程序,所以我真的需要一个指向该数据的指针。
我在这里有什么选择?
更新:这似乎有效:
IntPtr result = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.RECT)) * foo.Length);
IntPtr c = new IntPtr(result.ToInt32());
for (i = 0; i < foo.Length; i++)
{
Marshal.StructureToPtr(foo[i], c, true);
c = new IntPtr(c.ToInt32() + Marshal.SizeOf(typeof(Win32.RECT)));
}
再次更新以修复仲裁者评论的内容。