我在从另一个中构建一个struct
s数组时遇到问题。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
s 引用的数组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
s 仅具有一个存储空间,但在尝试编组数组中的第二项时失败。
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 个存储需要通过。也许我的想法有缺陷,但我不知道如何纠正这一点。