[英]How to pass UTF-8 string from Delphi to a DLL C extern function?
I am calling from Delphi a C extern function in a Visual Studio compiled DLL. 我在Delphi中调用Visual Studio编译的DLL中的C extern函数。 The DLL method in turn calls a C++ method that takes as argument a C++ string type.
DLL方法又调用C ++方法,该方法将C ++字符串类型作为参数。 The string at the Delphi end is UTF-8 encoded (without the BOM).
Delphi端的字符串是UTF-8编码的(没有BOM)。 I need to make sure the C++ method that takes the string type gets the UTF-8 encoded string.
我需要确保采用字符串类型的C ++方法获取UTF-8编码的字符串。
I can modify the DLL source code. 我可以修改DLL源代码。 My question:
我的问题:
My UTF-8 string on the Delphi side is of type string. 我在Delphi端的UTF-8字符串是string类型。 What type should the C extern method take?
C extern方法应该采用什么类型? PChar, PWideChar?
PChar,PWideChar? and how do I convert that to a C++ string type?
以及如何将其转换为C ++字符串类型?
Note: I can't convert the UTF-8 string into an AnsiString first because the encoding stores some Greek letters that must be preserved. 注意:我无法首先将UTF-8字符串转换为AnsiString,因为编码存储了一些必须保留的希腊字母。 The C++ end will make a copy of the Delphi string and handle the disposal of any allocated memory.
C ++端将复制Delphi字符串并处理任何已分配的内存。
Delphi end (Using XE6): Delphi结束(使用XE6):
mystr : string;
callCExternMethod (mystr) // cast to what?
C++ End (Using VS 2013): C ++ End(使用VS 2013):
void callCExternMethod (????? mystr) {
// convert mystr to C++ string type
callCPlusPlusMethod (takes C++ string type)
}
On the Delphi side the parameter is PAnsiChar
which you pass like this: PAnsiChar(Utf8String(str))
. 在Delphi端,参数是
PAnsiChar
,你可以这样传递: PAnsiChar(Utf8String(str))
。
On the C++ side you receive the parameter as const char*
. 在C ++端,您将获得参数
const char*
。
Obviously you need to ensure that the calling convention matches. 显然,您需要确保调用约定匹配。
Another option would be to use the UTF8String
type: 另一种选择是使用
UTF8String
类型:
mystr : string;
u8: UTF8String;
u8 := UTF8String(mystr);
callCExternMethod(PAnsiChar(u8));
Note: the UTF8String
type is not available for use on mobile platforms in Delphi XE5 through 10.0 Seattle, unless you use a patch to enable it: 注意:除非您使用补丁启用,否则
UTF8String
类型不能在Delphi XE5到10.0 Seattle的移动平台上使用:
http://andy.jgknet.de/blog/2013/10/the-return-of-the-byte-strings/ http://andy.jgknet.de/blog/2013/10/the-return-of-the-byte-strings/
UTF8String
has been re-enabled for use in mobile starting in Delphi 10.1 Berlin. UTF8String
已重新启用,可在德尔福10.1柏林的移动设备中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.