首页 > 解决方案 > 从资源 (.res) 文件加载文本会产生奇怪的字符

问题描述

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

标签: delphiembedded-resourcedelphi-10.3-rio

解决方案


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

Size := SizeofResource(hInstance, InfoBlock);

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

SetString(Result, ResData, ResSize);

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

解决办法很明显

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

推荐阅读