delphi - 从资源 (.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;
解决方案
您正在使用SizeOfResource()
which 返回大小(以字节为单位)。
Size := SizeofResource(hInstance, InfoBlock);
但你使用它就好像它是字符数
SetString(Result, ResData, ResSize);
因为SizeOf(Char)
是 2,所以您正在将实际文本之后发生在内存中的内容读入字符串。
解决办法很明显
SetString(Result, ResData, ResSize div SizeOf(Char));
推荐阅读
- ios - iOS 应用未与动态链接 URL 前缀关联
- css - 如何跨越到隐式网格中的最后一列?
- rust - 如何从 iter() 和 iter().rev() 获得相同类型的迭代器?
- java - JCEF 的 UnsatisfiedLinkError
- three.js - 无法在 Threejs 中的任意轴上旋转对象
- api - 如何使用硒和黄瓜测试航班预订动态定价系统的自动化
- php - PHP 邮件功能在 Plesk ionos 主机上不起作用
- ios - 不同维度的 TableView 部分索引标题大小
- powershell - 在 Powershell 中安装后无法直接运行 chololately
- c# - FCM 令牌在更新应用程序后刷新。为什么?