[fpc-pascal] How do I do this safely?

Marco van de Voort marcov at stack.nl
Fri Oct 15 19:41:15 CEST 2004


> I am trying to write code that will compile cleanly in current and
> future versions of FPC (in mode Delphi) and Delphi on 32- and 64-bit
> platforms.  I need to store strings and their floating point rankings
> in a list and I was advised to use the single type and store them in
> the TStringList.Objects list, using a cast to store and retreive the
> values.  
> 
> SL := TstringList.Create;
> rank := 0.95;
> title := 'This is a string';
> SL.AddObject(title,pointer(rank));
> 
> This feels unsafe.. I'd hate to have to come back later to debug why
> the ranks have become completely garbled on a new platform or
> version.
> 
> Should I convert ranks to an integer (slightly awkward)?  Or just
> create a trivial class to hold ranks as objects (seems like
> overkill)? Or...?

Allocate space for it.

var p : ^real;	// extended/double whatever
  // assuming sl exists.
begin
 new(p);
 p:=0.95
 sl.addobject('this is a string',rank);

However this means you must destroy it when deallocating/destroying the list.

Something like

if sl.count>0 then
  for i:=0 to count-1 do
	dispose(sl.objects[i]);

in your destructor.




More information about the fpc-pascal mailing list