What does personal AnsiString (myPAnsiChar) actually do?

I have a C DLL that returns a pointer to a PAnsiChar string managed by a C DLL. I would like to make a copy of the string so that it can be controlled on the Delphi side.

If I returned the returned PAnsiChar to AnsiString, as in "str: = AnsiString (myPAnsiChar)", what does the actor do? Does the allocation include new memory for the line pointed to by PAnsiChar, or do I first need to make a copy of the line coming from the DLL?

+4
source share
2 answers

Yes. The compiler translates this method into an RTL call that copies the string to the new AnsiString. If you build with DCU Debug enabled, you can trace it in the debugger and see how it works. For instance:

var fromTheDll: PAnsiChar; localCopy: string; localCopy := fromTheDll; //Delphi copies the string to fromTheDll variable 
+9
source

In fact, casting is redundant. You can write str: = myPAnsiChar just as easily.

Delphi string types use RTL-controlled memory. This means that they will never reuse the contents of PChar. The only time you need to take steps to make sure the assignment creates a new copy is when the job is between two matching Delphi string types. This is AnsiString for AnsiString or UnicodeString for UnicodeString.

+2
source

Source: https://habr.com/ru/post/1379917/


All Articles