循环遍历IntPtr以构建struct数组时出错

时间:2013-04-05 19:29:17

标签: c# marshalling intptr

我在另一个struct中从IntPtr构建struct数组时遇到问题。

此结构由Windows API我使用:

返回
public struct DFS_INFO_9 {
    [MarshalAs(UnmanagedType.LPWStr)]
    public string EntryPath;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string Comment;
    public DFS_VOLUME_STATE State;
    public UInt32 Timeout;
    public Guid Guid;
    public UInt32 PropertyFlags;
    public UInt32 MetadataSize;
    public UInt32 SdLengthReserved;
    public IntPtr pSecurityDescriptor;
    public UInt32 NumberOfStorages;
    public IntPtr Storage;
}

[DllImport("netapi32", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int NetDfsEnum([MarshalAs(UnmanagedType.LPWStr)]string DfsName, int Level, int PrefMaxLen, out IntPtr Buffer, [MarshalAs(UnmanagedType.I4)]out int EntriesRead, [MarshalAs(UnmanagedType.I4)]ref int ResumeHandle);

我正在尝试获取DFS_STORAGE_INFO_1引用的IntPtr Storage数组。

这是结构(如果重要的话):

public struct DFS_STORAGE_INFO_1 {
    public DFS_STORAGE_STATE State;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string ServerName;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string ShareName;
    public IntPtr TargetPriority;
}

到目前为止,这段代码一直在努力使DFS_INFO_9只有一个存储空间,但在尝试编组数组中的第二个项目时失败了。

DFS_INFO_9 info = GetInfoFromWinApi();
List<DFS_STORAGE_INFO_1> Storages = new List<DFS_STORAGE_INFO_1>();
for (int i = 0; i < info.NumberOfStorages; i++) {
    IntPtr pStorage = new IntPtr(info.Storage.ToInt64() + i * Marshal.SizeOf(typeof(DFS_STORAGE_INFO_1)));
    DFS_STORAGE_INFO_1 storage = (DFS_STORAGE_INFO_1)Marshal.PtrToStructure(pStorage, typeof(DFS_STORAGE_INFO_1));
    Storages.Add(storage);
}

我收到一个FatalExecutionEngineError,它会吐出错误代码0x0000005(拒绝访问)。我假设DFS_STORAGE_INFO_1的大小被误算,导致编组尝试访问分配给阵列的内存。但这可能发生在i = 1上,当时可能有7个存储空间可以通过。也许我的想法有缺陷,但我不知道如何纠正这个问题。

1 个答案:

答案 0 :(得分:1)

DFS_STORAGE_INFO_1的实际定义是:

public struct DFS_STORAGE_INFO_1 {
    public DFS_STORAGE_STATE State;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string ServerName;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string ShareName;
    DFS_TARGET_PRIORITY TargetPriority;
}

TargetPriority是一个结构,定义为here

public struct DFS_TARGET_PRIORITY {
    public DFS_TARGET_PRIORITY_CLASS TargetPriorityClass;
    public UInt16 TargetPriorityRank;
    public UInt16 Reserved;
}

public enum DFS_TARGET_PRIORITY_CLASS {
    DfsInvalidPriorityClass = -1,
    DfsSiteCostNormalPriorityClass = 0,
    DfsGlobalHighPriorityClass = 1,
    DfsSiteCostHighPriorityClass = 2,
    DfsSiteCostLowPriorityClass = 3,
    DfsGlobalLowPriorityClass = 4
}

对于FatalExecutionEngineError,我认为结构DFS_STORAGE_INFO_1的大小被错误估算,因为它的定义不正确。当尝试将指针转换为它们引用的结构时,下一个索引是错误的,因为大小已关闭。转换内存块时,可能会引用一个本来不应该访问的块,抛出“拒绝访问(0x0000005)”错误。