gpt4 book ai didi

c# - 如何从 GetTokenInformation() 安全地为 32 位和 64 位调用可变长度的结构数组? C#

转载 作者:行者123 更新时间:2023-11-30 12:16:03 25 4
gpt4 key购买 nike

我遵循提供的 pinvoke 代码 here但是我有点害怕将可变长度数组编码为 size=1,然后通过计算偏移量而不是索引到数组来单步执行它。难道没有更好的办法吗?如果不是,我应该怎么做才能使 32 位和 64 位安全?

    [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。但是代码行执行得很好!?这是怎么回事?

最佳答案

与其猜测偏移量是多少,不如使用 Marshal.OffsetOf(typeof(TOKEN_GROUPS), "Groups") 通常更好获得数组开头的正确偏移量。

关于c# - 如何从 GetTokenInformation() 安全地为 32 位和 64 位调用可变长度的结构数组? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com