Hi all,
I need to be able to get variable names and values at runtime and even
declare new ones by reading a definition file.
My first tryings are to store the variables that I need in a record
structure like:
PMyVarStruc = ^TMyVarStruc;
TMyVarStruc = record
VarName : string;
VarData: array of pointer;
end;
so that I am able to assign the variable AVar of type:
type
PAVar = ^TAvar;
TAvar = record
Name:string;
data:byte;
end;
to the Pdata field in the TMyVarStruc.
{ As far as I know , I have to define all types of pointers that I will
ever need for my function in advance -
I don't like that, cause I want to be free to declare any type of
variable structure}
{pointer type definition}
type
Pinteger: ^integer;
Pstring : ^string;
{global example-variable that I want to access at runtime}
Var Avar:Tavar;
{procedure to store the global variable to a TMyVarSTruc}
procedure TForm1.Button3Click(Sender: TObject);
Var
Pint:Pinteger;
Pstr:Pstring;
Size:integer;
Parr:array of pointer;
begin
Avar.name:='Test'; // Test data stored to the global variable
Avar.data:=100; // Test data stored to the global variable
size:=2; // I have to set the pointer array size
Setlength(Parr,size);
Pstr:=...@Avar.name;
Pint:=...@Avar.data;
PArr[0]:=addr(Avar.name);
PArr[1]:=addr(Avar.data);
{Now I call the function that expects a name, a size , and the Vardata
(array of pointer) to store all to a
PMyVarstruc variable}
SetMyVariable('ATest',1,PArr);
end;
Then I can get back my variable value and name
by calling a function like:
procedure TForm1.Button4Click(Sender: TObject);
Var AResult:PMyvarstruc;
Pint:PInteger;
Pstr:Pstring;
TheVar:Tavar;
begin
ARESULt:=GetmyVariable('ATest');
Pstr:=Aresult^.PData[0];
Thevar.name:=Pstr^;
Pint:=Aresult^.PData[1];
Thevar.data:=Pint^;
memo1.text:=Aresult^.name+thevar.name+inttostr(thevar.data);
end;
One bad thing is: I have to declare all types of pointers (like
Pinteger, Pstring and so on)
in advance to be able to get the right value back from the pointer.
Delphi Help says:
"Standard pointer types exist for many purposes. The most versatile is
Pointer, which can point to data of any kind.
But a Pointer variable cannot be dereferenced; placing the ^ symbol
after a Pointer variable causes a compilation error.
To access the data referenced by a Pointer variable, first cast it to
another pointer type and then dereference it."
Is there a better way todo it than my way ? Any suggestions very
appreciated!!
Thanks to all replies!
--
===========================================================================
Klaus Heerlein phone: ++49 (0)5556 979-387
Max Planck Institut fr Aeronomie fax: ++49 (0)5556 979-240
Max Planck Str. 2
D-37191 Katlenburg-Lindau
===========================================================================