Reputation: 751
I'm writing a tool, which use a C-DLL. The functions of the C-DLL expect a char*
, which is in UTF-8 Format.
My question: Can I pass a PChar
or do I have to use UTF8Encode(string)
?
Upvotes: 1
Views: 3288
Reputation: 16065
Please edit the question and add the tag with your target Delphi version.
Pass it as PAnsiChar
; PChar is a joker and may mean different data types. When you work with DLL-like API, you ignore compiler safety net and that means you should make your own. And that means you should use real types, not jokers, the types that would not change no matter which compiler settings and version would be active.
But before getting passing the pointer you should ensure that the source data is encoded in UTF8 actually.
.
Var data: string; buffer: UTF8String; buffer_ptr: PAnsiChar;
Begin
buffer := data + #0;
// transcoding to UTF8 from whatever charset it was, transparently done by Delphi RTL
// last zero to ensure that even for empty string you would have valid pointer below
buffer_ptr := Pointer(@buffer[1]); // making sure there can be no codepage bound to the datatype
C_DLL_CALL(buffeR_ptr);
End;
Upvotes: 1
Reputation: 613382
Consider a string variable named s
. On an ANSI Delphi PChar(s)
is ANSI encoded. On a Unicode Delphi it is UTF-16 encoded.
Therefore, either way, you need to convert s
to UTF-8 encoding. And then you can use PAnsiChar(...)
to get a pointer to a null terminated C string.
So, the code you need looks like this:
PAnsiChar(UTF8Encode(s))
Upvotes: 5