Search code examples
arraysdelphidelphi-2009ansi

delphi declaring size of ansi string


Its easy to define a string at the size of 3 (in old delphi code)

st:string[3];

now, we wish to move the code to ansi

st:ansiString[3];

won't work!

and for adcanced oem type

st:oemString[3]; 

same problem, where

type
  OemString = Type AnsiString(CP_OEMCP);

how could be declared a fixed length ansi string and the new oem type?

update: i know it will create a fixed length string. it is part of the design of the software to protect against mistakes, and is essential for the program.


Solution

  • You don't need to define the size of an AnsiString.

    The notation

    string[3] 
    

    is for short strings used by Pascal (and Delphi 1) and it is mostly kept for legacy purposes.

    Short strings can be 1 to 255 bytes long. The first ("hidden") byte contains the length.

    AnsiString is a pointer to a character buffer (0 terminated). It has some internal magic like reference counting. And you can safely add characters to an existing string because the compiler will handle all the nasty details for you.

    UnicodeStrings are like AnsiStrings, but with unicode chars (2 bytes in this case). The default string now (Delphi 2009) maps to UnicodeString.

    the type AnsiString has a construct to add a codepage (used to define the characters above 127) hence the CP_OEMCP:

    OemString = Type AnsiString(CP_OEMCP);