我遵循提供的密碼代碼here,但是由於大小= 1的變長數組的編組而稍微害怕,然後通過計算偏移量而不是索引到數組中來逐步完成。沒有更好的方法嗎?如果不是,我該如何做到這一點,以確保32位和64位的安全?如何從GetTokenInformation()安全地爲32位和64位調用可變長度的結構數組? C#
[StructLayout(LayoutKind.Sequential)]
public struct SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_GROUPS
{
public int GroupCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public SID_AND_ATTRIBUTES[] Groups;
};
public void SomeMethod()
{
IntPtr tokenInformation;
// ...
string retVal = string.Empty;
TOKEN_GROUPS groups = (TOKEN_GROUPS)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_GROUPS));
int sidAndAttrSize = Marshal.SizeOf(new SID_AND_ATTRIBUTES());
for (int i = 0; i < groups.GroupCount; i++)
{
// *** Scary line here:
SID_AND_ATTRIBUTES sidAndAttributes = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(
new IntPtr(tokenInformation.ToInt64() + i * sidAndAttrSize + IntPtr.Size),
typeof(SID_AND_ATTRIBUTES));
// ...
}
我看到here爲遠大於它很可能是在聲明數組的長度的另一種方法,但似乎有其自身的問題。
作爲一個側面的問題:當我在調試器中單步執行上面的代碼時,我無法評估tokenInformation.ToInt64()
或ToInt32()
。我得到一個ArgumentOutOfRangeException。但是這行代碼執行得很好!?這裏發生了什麼?
51%...你在哪看到的!?開玩笑 - 公平點我真的很懶。 – Rory 2011-05-20 11:00:47
因此任何想法ToInt64()在32位和64位機器上都是安全的嗎? – Rory 2011-05-20 11:01:20