Brian Hoffman <bhoff...@discover.net> wrote in article
<33F7FAF5.1...@discover.net>...
Quote
> Help! Is there any way to create a Delphi variable that is
> equivalent to the following 'C' union variable declaration?
> Here it is:
> typedef struct _ls_var
> {
> int type;
> union {
> double number;
> const char *string;
> double vector[3];
> } data;
> } LS_VAR;
Brian,
What you need is a "variant record," which you should not
confuse with the "variant types" that were introduced in
Delphi 2 (I think). [I'm not sure why those C++ types think
overloading is so great when overloading of even simple
English words can cause great confusion!]
Just put a button on a Delphi form and try the following:
procedure TForm1.Button1Click(Sender: TObject);
TYPE
LS_VAR =
RECORD
CASE iType: INTEGER OF
0: (n: DOUBLE);
1: (s: pChar);
2: (v: ARRAY[0..2] OF DOUBLE)
END;
begin
Button1.Caption := IntToStr(SizeOf(LS_VAR));
end;
Note: Only one "END" even though RECORD and
CASE would normally have a separate "END".
The "answer" in the button caption is 28 bytes since
the iType is 4 bytes and the longest variant, v, is
3*8 = 24 bytes. Note this form implies that the iType
"tag" variable determines which variant is "active." While this
may be a useful way to look at what's going on, I think
you can directly access any variant at any time.
Since the variant tag is somewhat irrelevant, I usually
code variant records like the following that gives the
same result as above:
TYPE
LS_VAR =
RECORD
iType: INTEGER;
CASE INTEGER OF
0: (n: DOUBLE);
1: (s: pChar);
2: (v: ARRAY[0..2] OF DOUBLE)
END;
Here just use any enumerated type, INTEGER is always useful,
and just enumerate the variants in your RECORD.
Variant records are usually considered "dangerous" since you
can easily cause undesired side effects when memory locations
for variables are shared. (Like the COMMON blocks in old
FORTRAN programs.)
efg
_________________________________________________
Earl F. Glynn EarlGl...@WorldNet.att.net
MedTech Research Corporation
Lenexa, KS 66219 USA