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

Loading text from resource (.res) file gives strange characters

基于this问题我想知道如何解决出现奇怪字符的问题,即使将文本文件保存为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;

您正在使用 SizeOfResource(),其中 returns 大小 字节

Size := SizeofResource(hInstance, InfoBlock);

但您使用它时就好像它是 个字符

SetString(Result, ResData, ResSize);

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

解决办法很明显

SetString(Result, ResData, ResSize div SizeOf(Char));