Mixing Delphi Strings and Null Terminated Strings

You can mix long strings (AnsiString values) and null-terminated strings (PChar values) in expressions and assignments, and you can pass PChar values to functions or procedures that take long-string parameters. The assignment s := p, where s is a string variable and p is a PChar expression, copies a null-terminated string into a long string.

In a binary operation, if one operand is a long string and the other a PChar, the PChar operand is converted to a long string.

You can cast a PChar value as a long string. This is useful when you want to perform a string operation on two PChar values. For example, s := string(P1) + string(P2);

You can also cast a long string as a null-terminated string. The following rules apply.

• If s is a long-string expression, PChar(s) casts s as a null-terminated string; it returns a pointer to the first character in s. For example, if str1 and str2 are long strings, you could call the Win32

API MessageBox function like this: MessageBox(0, PChar(str1), PChar(str2), MB_OK);

  • You can also use Pointer(s) to cast a long string to an untyped pointer. But if s is empty, the typecast returns nil.
  • PChar(S) always returns a pointer to a memory block; if s is empty, a pointer to #0 is returned.
  • When you cast a long-string variable to a pointer, the pointer remains valid until the variable is assigned a new value or goes out of scope. If you cast any other long-string expression to a pointer, the pointer is valid only within the statement where the typecast is performed.
  • When you cast a long-string expression to a pointer, the pointer should usually be considered readonly. You can safely use the pointer to modify the long string only when all of the following conditions are satisfied.
  • The expression cast is a long-string variable.
  • The string is not empty.
  • The string is unique - that is, has a reference count of one. To guarantee that the string is unique, call the SetLength, setstring, or UniqueString procedure.
  • The string has not been modified since the typecast was made.
  • The characters modified are all within the string. Be careful not to use an out-of-range index on the pointer.

The same rules apply when mixing WideString values with PWideChar values.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment