Delphi Unicode String Type Stored Directly at its Address (or "Unicode ShortString")

Posted by Andreas Rejbrand on Stack Overflow See other posts from Stack Overflow or by Andreas Rejbrand
Published on 2010-05-10T21:19:18Z Indexed on 2010/05/11 13:04 UTC
Read the original article Hit count: 333

Filed under:
|
|
|
|

I want a string type that is Unicode and that stores the string directly at the adress of the variable, as is the case of the (Ansi-only) ShortString type.

I mean, if I declare a S: ShortString and let S := 'My String', then, at @S, I will find the length of the string (as one byte, so the string cannot contain more than 255 characters) followed by the ANSI-encoded string itself.

What I would like is a Unicode variant of this. That is, I want a string type such that, at @S, I will find a unsigned 32-bit integer (or a single byte would be enough, actually) containing the length of the string in bytes (or in characters, which is half the number of bytes) followed by the Unicode representation of the string. I have tried WideString, UnicodeString, and RawByteString, but they all appear only to store an adress at @S, and the actual string somewhere else (I guess this has do do with reference counting and such). Update: The most important reason for this is probably that it would be very problematic if sizeof(string) were variable.

I suspect that there is no built-in type to use, and that I have to come up with my own way of storing text the way I want (which actually is fun). Am I right?

Update I will, among other things, need to use these strings in packed records. I also need manually to read/write these strings to files/the heap. I could live with fixed-size strings, such as <= 128 characters, and I could redesign the problem so it will work with null-terminated strings. But PChar will not work, for sizeof(PChar) = 1 - it's merely an address.

The approach I eventually settled for was to use a static array of bytes. I will post my implementation as a solution later today.

© Stack Overflow or respective owner

Related posts about delphi

Related posts about string