使用此代码我得到一个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;
在Delphi 10.2 Tokyo中,如果我两次调用此函数,第二次获得AV。
是什么导致这个错误?
您没有遵循文档中规定的协议。最后一个论点的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;