Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the cast AnsiString (myPAnsiChar) actually do?

Tags:

delphi

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?

like image 418
rhody Avatar asked Dec 22 '22 06:12

rhody


2 Answers

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
like image 60
Mason Wheeler Avatar answered Dec 24 '22 01:12

Mason Wheeler


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.

like image 25
David Heffernan Avatar answered Dec 24 '22 01:12

David Heffernan