从资源 (.res) 文件加载文本会产生奇怪的字符

1 delphi embedded-resource delphi-10.3-rio

基于这个问题,我想知道如何解决出现奇怪字符的问题,即使将文本文件保存为Unicode。

在此处输入图片说明

function GetResourceAsPointer(ResName: PChar; ResType: PChar; out Size: LongWord): Pointer;
var
  InfoBlock: HRSRC;
  GlobalMemoryBlock: HGLOBAL;
begin
  Result := nil;
  InfoBlock := FindResource(hInstance, ResName, ResType);
  if InfoBlock = 0 then
    Exit;
  Size := SizeofResource(hInstance, InfoBlock);
  if Size = 0 then
    Exit;
  GlobalMemoryBlock := LoadResource(hInstance, InfoBlock);
  if GlobalMemoryBlock = 0 then
    Exit;
  Result := LockResource(GlobalMemoryBlock);
end;

function GetResourceAsString(ResName: pchar; ResType: pchar): string;
var
  ResData: PChar;
  ResSize: Longword;
begin
  ResData := GetResourceAsPointer(ResName, ResType, ResSize);
  SetString(Result, ResData, ResSize);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
   ShowMessage(GetResourceAsString('TESTANDO', 'TXT'));
end;
Run Code Online (Sandbox Code Playgroud)

Tom*_*erg 7

您正在使用SizeOfResource()which 返回大小(以字节为单位)

Size := SizeofResource(hInstance, InfoBlock);
Run Code Online (Sandbox Code Playgroud)

但你使用它就好像它是字符数

SetString(Result, ResData, ResSize);
Run Code Online (Sandbox Code Playgroud)

因为SizeOf(Char)是 2,所以您正在读入字符串中实际文本之后发生在内存中的内容。

解决方案很明显

SetString(Result, ResData, ResSize div SizeOf(Char));
Run Code Online (Sandbox Code Playgroud)

  • @戴维森除以2。 (2认同)