本文介绍了Delphi 2010:如何将UTF8编码的PAnsiChar转换为UnicodeString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我有一个使用UTF-8作为其内部字符串格式的外部DLL.接口函数都使用PAnsiChar传递字符串.

The situation: I’ve an external DLL that uses UTF-8 as its internal string format. The interface functions all use PAnsiChar to pass strings along.

我的其余应用程序使用Delphi的本机string类型;因为我使用的是Delphi 2010,所以它将映射为UnicodeString.

The rest of my application uses Delphi’s native string type; since I’m working with Delphi 2010, that will map to a UnicodeString.

如何可靠地将那些PAnsiChar参数(指向UTF-8编码的字符串)强制转换为UnicodeString?

How can I reliably cast those PAnsiChar arguments (which are pointing to UTF-8 encoded strings) to a UnicodeString?

我有这个功能,我认为效果很好:

I had this function, which I thought worked fine:

function PUTF8CharToString(Text: PAnsiChar): string;
var
  UText: UTF8String;
begin
  UText := UTF8String(Text);
  Result := string(UText);
end;

...但是现在我遇到了结果字符串损坏的情况;当我将PAnsiChar保存到文件中时,就可以了;但是当我使用上述函数保存转换后的结果字符串时,它已损坏.

...but now I’ve run into a case where the result string is corrupted; when I save the PAnsiChar to file, it’s fine; but when I save the resulting string after conversion using the above function, it’s corrupted.

还是应该正常工作,这是否表明存在其他一些内存分配问题?

Or should this work correctly, and is this indicative of some other memory (de)allocation problem?

我终于设法通过将转换后的字符串分配给局部变量字符串,而不是直接将其传递给另一个函数来摆脱内存损坏./p>

I finally managed to get rid of the memory corruption by assigning the converted string to a local variable string, instead of directly passing it to another function.

推荐答案

来自系统:

函数UTF8ToUnicodeString(const S:PAnsiChar):UnicodeString;超载;

function UTF8ToUnicodeString(const S: PAnsiChar): UnicodeString; overload;

UnicodeStr:= System.Utf8ToUnicodeString(Text);

UnicodeStr := System.Utf8ToUnicodeString(Text);

这篇关于Delphi 2010:如何将UTF8编码的PAnsiChar转换为UnicodeString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 15:47