Search code examples
delphiembedded-resourcedelphi-10.3-rio

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


Based on this question I want to know how to solve the problem of strange characters appearing, even having text file saved as Unicode.

enter image description here

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;

Solution

  • You are using SizeOfResource() which returns the size in bytes.

    Size := SizeofResource(hInstance, InfoBlock);
    

    but you are using it as if it were number of characters

    SetString(Result, ResData, ResSize);
    

    Because SizeOf(Char) is 2, you are reading into the string what happens to be in the memory after the actual text.

    Solution is obviously

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