I have a C DLL that returns a pointer to a PAnsiChar string managed by the C DLL. I would like to make a copy of the string so that it can be managed on the Delphi side.
If I cast the returned PAnsiChar to an AnsiString, as in "str := AnsiString (myPAnsiChar)" what does the cast actually do? Does the cast allocate new memory for the string pointed to by PAnsiChar or should I make a copy of the string coming from the DLL first?
Yes. The compiler translates that cast into a RTL routine call that copies the string into a new AnsiString. If you build with Debug DCUs enabled you can trace into it in the debugger and see how it works. E.g:
var
fromTheDll: PAnsiChar;
localCopy: string;
localCopy := fromTheDll; //Delphi copies the string to fromTheDll variable
In fact the cast is superfluous. You can just as easily write str := myPAnsiChar.
Delphi string types use memory that is managed by the RTL. This means that they will never reuse the contents of a PChar. The only time you ever need to take steps to make sure an assignment creates a new copy is when the assignment is between two matching Delphi string types. That is AnsiString to AnsiString or UnicodeString to UnicodeString.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With