Winapi.ShlObj.SHGetFolderPath可重现的错误

问题描述 投票:-1回答:1

使用此代码我得到一个AV:

uses
  Winapi.ShlObj;

function GetUserAppDataPath: string;
var
  ThisPath: PWideChar;
begin
  if Winapi.ShlObj.SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, ThisPath) = S_OK then
    Result := string(ThisPath)
  else
    Result := '';
end;

enter image description here

在Delphi 10.2 Tokyo中,如果我两次调用此函数,第二次获得AV。

是什么导致这个错误?

我使用PWideChar,因为Delphi IDE告诉我:enter image description here

delphi winapi delphi-10.1-berlin delphi-10.2-tokyo
1个回答
6
投票

您没有遵循文档中规定的协议。最后一个论点的documentation

指向以null结尾的长度为MAX_PATH的字符串的指针,该字符串将接收路径。

您需要分配该缓冲区并传递其地址。

function GetUserAppDataPath: string;
var
  ThisPath: array[0..MAX_PATH-1] of Char;
begin
  if Winapi.ShlObj.SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, ThisPath) = S_OK then
    Result := ThisPath
  else
    Result := '';
end;
© www.soinside.com 2019 - 2024. All rights reserved.