Winapi.ShlObj.SHGetFolderPath的可重现错误

时间:2018-09-16 11:53:13

标签: delphi winapi delphi-10.1-berlin delphi-10.2-tokyo

通过此代码,我得到了一个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

1 个答案:

答案 0 :(得分:6)

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

  

指向长度为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;