【发布时间】:2015-02-02 00:41:37
【问题描述】:
private struct TOKEN_USER
{
internal SID_AND_ATTRIBUTES User; //Compiler warning comes from here.
}
[StructLayout(LayoutKind.Sequential)]
private struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
private int Attributes;
}
将结构初始化为默认值:
TOKEN_USER tokenUser = default(TOKEN_USER);
然后进行两次必需的调用以检索指向结构的指针: (与问题无关)使用这个:
GetTokenInformation(tokenhandle, TokenInformationClass.TokenUser, sid, sidlength, ref sidlength);
然后编组回一个结构。
tokenUser = (TOKEN_USER)Marshal.PtrToStructure(sid, tokenUser.GetType());
这可行,但编译器警告我 TOKEN_USER 中的“用户”字段未分配。
R# 建议我从构造函数初始化它:
public TOKEN_USER(SID_AND_ATTRIBUTES user) : this(user)
{
}
但是,这不会编译,并出现错误“构造函数无法调用自身”。 我的问题是,我应该将它分配给 SID_AND_ATTRIBUTES (默认)以满足编译器的要求,还是忽略它?
测试程序:
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(
int dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
int dwProcessId);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(
IntPtr processHandle,
int desiredAccess,
ref IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool GetTokenInformation(
IntPtr tokenHandle,
TokenInformationClass tokenInformationClass,
IntPtr tokenInformation,
int TokenInformationLength,
ref int ReturnLength);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool IsValidSid(
IntPtr SID);
private enum TokenInformationClass
{
TokenUser = 1,
}
private const int QueryInformation = 0x400;
private const int TokenRead = 0x20008;
private struct TOKEN_USER
{
internal SID_AND_ATTRIBUTES User; //Compiler warning comes from here.
}
[StructLayout(LayoutKind.Sequential)]
private struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
private int Attributes;
}
internal static IntPtr GetProcessHandle()
{
foreach (Process p in Process.GetProcesses())
{
using (p)
{
if (p.ProcessName == "explorer")
{
return OpenProcess(QueryInformation, false, p.Id);
}
}
}
return IntPtr.Zero;
}
public void Test()
{
IntPtr pHandle = GetProcessHandle();
IntPtr tokenHandle = IntPtr.Zero;
OpenProcessToken(pHandle, TokenRead, ref tokenHandle);
int sidlength = 0;
GetTokenInformation(tokenHandle, TokenInformationClass.TokenUser, IntPtr.Zero,
0, ref sidlength);
TOKEN_USER tokenUser = default(TOKEN_USER);
IntPtr sid = Marshal.AllocHGlobal(sidlength);
GetTokenInformation(tokenHandle, TokenInformationClass.TokenUser,sid,
sidlength, ref sidlength);
tokenUser = (TOKEN_USER)Marshal.PtrToStructure(sid, tokenUser.GetType());
if (IsValidSid(tokenUser.User.Sid))
{
Debug.WriteLine("Valid!");
}
}
【问题讨论】:
-
能否展示一个完整的程序
-
@DavidHeffernan 完整的程序太大而无法缩减,所以我创建了一个测试程序来演示这个问题,我使用的是进程令牌,所以我创建了一个帮助函数来返回“explorer” " 用于演示的过程令牌。
-
tokenUser = default(TOKEN_USER)的意义何在?您稍后分配给tokenUser。编译器反对哪一行代码? -
是初始化为默认获取Type in tokenUser = (TOKEN_USER)Marshal.PtrToStructure(sid, tokenUser.GetType());编译器反对结构字段本身。内部 SID_AND_ATTRIBUTES 用户;
-
不要那样做。做
typeof(TOKEN_USER).