1

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

此结构由我正在使用的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_1s 引用的数组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_9s 仅具有一个存储空间,但在尝试编组数组中的第二项时失败。

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 个存储需要通过。也许我的想法有缺陷,但我不知道如何纠正这一点。

4

1 回答 1

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 是一个结构,在这里定义:

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)”错误。

于 2013-04-08T14:24:19.660 回答