1

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;
Olivier
  • 13,283
  • 1
  • 8
  • 24
  • 1
    How do you create the resource? Using an RC file or using resourcestring keyword? Are the strange characters extra characters or transformed characters? Showing what create the resource string could help. – fpiette Sep 12 '20 at 07:33
  • Any particular reason why you are using a raw resource and not using `resourcestring`? – Remy Lebeau Sep 12 '20 at 16:30

1 Answers1

7

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));
Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54