使用本地var进行API调用会导致fn返回后出现访问错误(CheckTokenMembership)

时间:2017-10-08 20:25:04

标签: delphi

在SO的以下示例中使用外部函数CheckTokenMembership,在函数IsUserAdmin返回IsUserAdminStr之后,我得到访问错误

当b为local var to n时,IsUserAdmin之后会立即发生访问冲突。如果b是全局变量,则它可以工作。

删除CheckTokenMembership会停止错误。 FreeSid(AdministratorsGroup)无效。 Changing to Result := true;无效

请指出我显然缺少的东西。

//from https://stackoverflow.com/questions/6261865/looking-for-delphi-7-code-to-detect-if-a-program-is-started-with-administrator-r

//var b:boolean;   // <------ Works if b is here
function IsUserAdminStr(SingleChar:boolean=false):string;
begin
  if IsUserAdmin
      then result:='Admin'
      else result:='User';   //<----------- throws access error here
end;
function CheckTokenMembership(TokenHandle: THandle; SIdToCheck: PSID; var IsMember: Boolean): BOOL; StdCall; External AdvApi32;
function IsUserAdmin: Boolean;
var
  b: boolean;     // <-----------Fails if b is here
  b: BOOL;        // <------- this works 
  AdministratorsGroup: PSID;

const
  SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY =
    (Value: (0,0,0,0,0,5)); // ntifs
  SECURITY_BUILTIN_DOMAIN_RID: DWORD = $00000020;
  DOMAIN_ALIAS_RID_ADMINS: DWORD = $00000220;
begin
  b := AllocateAndInitializeSid(
      SECURITY_NT_AUTHORITY,
      2, //2 sub-authorities
      SECURITY_BUILTIN_DOMAIN_RID,  //sub-authority 0
      DOMAIN_ALIAS_RID_ADMINS,      //sub-authority 1
      0, 0, 0, 0, 0, 0,             //sub-authorities 2-7 not passed
      AdministratorsGroup);
  if (b) then
  begin
    if not CheckTokenMembership(0, AdministratorsGroup, b) then
      b := False;
    FreeSid(AdministratorsGroup);
  end;
  Result := b;
end;

1 个答案:

答案 0 :(得分:0)

如果b是BOOL而不是布尔值,它的作用是``var b:BOOL;`

仍然不明白为什么,或者为什么它显然适用于原创SO海报。 (使用D10.1)