stringdelphidelphi-2010code-migration

string problems migrating Delphi 3 to Delphi 2010


I got the source of an older project and have to change little things but I got in big trouble because of having only delphi 2010 to do that.

There is an record defined :

bbil = record
  path : string;
  pos: byte;
  nr: Word;
end;

later this definition is used to read from file :

b_bil: file of bbil;
pbbil: ^bbil;
l_bil : tlist;

while not(eof(b_bil)) do
  begin
    new(pbbil);
    read(b_bil, pbbil^);
    l_bil.add(pbbil);
  end

The primary problem is, the compiler does not accept the type "string" in the record because he wants a "finalization". So I tried to change "string" to "string[255]" or "shortstring". Doing this the app is reading the file but with wrong content.

My question is how to convert the old "string" type with which the files were written to the "new" types in Delphi 2010.

I already tried a lot e.g. "{$H-}". Adding only one char more in the record shows, the file is correct, because file is read nearly correct but truncated one char more each dataset - the length of lengthbyte+255chars seems to be correct fpr the definition but shortstring is not matching.


Solution

  • Eek! It looks like your code either pre-dates or does not use long strings. If you want to get the same behaviour as in your old Delphi then you need to replace string with ShortString.

    I see that you've tried that already and report that it fails. It's really the only explanation that makes any sense to me because all other string types are essentially pointers and so the only way the read could ever have worked is with a ShortString. The migration you are attempting is immense and you probably have huge numbers of confounding problems.

    @LU RD makes a good point in the comments that the record layout may differ between Delphi versions since you are not using a packed array. You can investigate the record layout using the two Delphi versions that you have at hand. You will need to arrange that the size of the records match between versions, and that the offsets to the fields also match.

    Based on the comments below, adding a padding byte between pos and nr will resolve your problems.

    bbil = record
      path : string;
      pos: byte;
      _pad: byte;
      nr: Word;
    end;
    

    You could also achieve the same effect by setting the $ALIGN compiler option to {$ALIGN ON} which would be how I think I would go about things.

    In the long run you really ought to get away from short strings, ANSI encoding, direct mapping between your internal records and your data files and so on. In the short run you may be better off getting hold of the same version of Delphi as was used to build this code and using that. I'd expect this issue to be just the tip of the iceberg.