Context
(Actual question below)
Easy in Delphi
I regularly convert API headers to Delphi. Sometimes there are problems with struct alignment, or I miss a packing option like #pragma pack(push, 1). To check if I have the proper alignment and size, I display the offsets in my translated records with this simple function using extended RTTI:
procedure WriteOffsets(Info: Pointer);
var
LContext: TRttiContext;
LType: TRttiType;
LField: TRttiField;
begin
LType := LContext.GetType(Info);
if Assigned(LType) then
if LType.TypeKind = tkRecord then
begin
Writeln((' ' + LType.QualifiedName + ' = record ').PadRight(48),
' // size ', LType.TypeSize);
for LField in LType.GetFields do
Writeln((' ' + LField.Name + ': ' + LField.FieldType.Name + ';').PadRight(48),
' // offset ', LField.Offset);
Writeln(' end;');
Writeln;
end
else
begin
Writeln(LType.QualifiedName, ' is not a record');
end
else
Writeln('Invalid type');
end;
and then call it with:
WriteOffsets(TypeInfo(TSecurityDescriptor));
That nicely writes the size and offsets for each member field, so I can check this with a similar output generated by C++Builder. The function generates something like this:
Winapi.Windows._SECURITY_DESCRIPTOR = record // size 20
Revision: Byte; // offset 0
Sbz1: Byte; // offset 1
Control: Word; // offset 2
Owner: Pointer; // offset 4
Group: Pointer; // offset 8
Sacl: PACL; // offset 12
Dacl: PACL; // offset 16
end;
Not so easy in C++Builder
But in C++Builder this is not so easy. I currently use a number of macros and simple RTTI (typeid(x).name()) like this:
members.h
#ifndef MEMBERS_H
#define MEMBERS_H
void print_member(const char *type, const char *name, int offset)
{
char buffer[256];
sprintf(buffer, " %s %s;", type, name);
printf("%-48s // offset %d\n", buffer, offset);
}
#define print(member) \
print_member(typeid(((type *)0)->member).name(), #member, offsetof(type, member))
#define start \
printf("struct %-42s/\/ size %d\n{\n", typeid(type).name(), sizeof(type))
#define end \
printf("};\n\n");
#endif
I know that that is ugly and makes C++ purists cringe, but it works. I use it in simple test programs like this:
#include "windows.h" // for the struct type I want to inspect
#include "members.h"
int main()
{
#define type SECURITY_DESCRIPTOR
start;
print(Revision);
print(Sbz1);
print(Control);
print(Owner);
print(Group);
print(Sacl);
print(Dacl);
end;
#undef type
}
And I get this kind of output:
struct _SECURITY_DESCRIPTOR // size 20
{
unsigned char Revision; // offset 0
unsigned char Sbz1; // offset 1
unsigned short Control; // offset 2
void * Owner; // offset 4
void * Group; // offset 8
_ACL * Sacl; // offset 12
_ACL * Dacl; // offset 16
};
Question
Is there a way to make the C++Builder part more elegant and performant? Ideally, I only provide the type (e.g. SECURITY_DESCRIPTOR) and the code generates the output for all its data members.
Currently, unlike in the Delphi example, I must query each member field explicitly. I do get the output I need, but it is much more work than in Delphi.
I couldn't find a way to make C++Builder generate RTTI similar to the extended RTTI in Delphi. Is there a way, using the more extended capabilities of C++ (or actually C++Builder), e.g. templates and/or the new features of C++11 (or C++14?) to automate this better, i.e. I just supply the name of the struct and the code does the same as Delphi? Does C++Builder provide better RTTI than the very basic little bit of RTTI that normal C++ provides?
Note
I am only interested in the data members of simple (Windows 32 or 64 bit) POD API structs, not in classes or structs with (possibly virtual) member functions as used in general C++.
Related
I have a C DLL with a number of functions I'm calling from Delphi. One of the functions (say Func1) returns a pointer to a struct - this all works fine. The structs created by calling Func1 are stored in a global pool within the DLL. Using a second function (Func2) I get a pointer to a block of memory containing an array of pointers, and I can access the array elements using an offset.
I need to be able copy the address in the returned pointer for a struct (from Func1) to any of the memory locations in the array (from Func2). The idea is that I can build arrays of pointers to pre-defined structs and access the elements directly from Delphi using pointer offsets.
I tried using:
CopyMemory(Pointer(NativeUInt(DataPointer) + offset), PStruct, DataSize);
where DataPointer is the start of my array and PStruct is returned from Func1, but that doesn't copy the address I need.
In .NET it works using Marshal.WriteIntPtr and looking at the underlying code for this using Reflector I think I need something trickier than CopyMemory. Anyone got any ideas for doing this in Delphi?
Edit: This is part of a wrapper around vector structures returned from the R language DLL. I have a base vector class from which I derive specific vector types. I've got the wrapper for the numeric vector working, so my base class looks fine and this is where I get DataPointer:
function TRVector<T>.GetDataPointer: PSEXPREC;
var
offset: integer;
h: PSEXPREC;
begin
// TVECTOR_SEXPREC is the vector header, with the actual data behind it.
offset := SizeOf(TVECTOR_SEXPREC);
h := Handle;
result := PSEXPREC(NativeUInt(h) + offset);
end;
Setting a value in a numeric vector is easy (ignoring error handling):
procedure TNumericVector.SetValue(ix: integer; value: double);
var
PData: PDouble;
offset: integer;
begin
offset := GetOffset(ix); // -- Offset from DataPointer
PData := PDouble(NativeUInt(DataPointer) + offset);
PData^ := value;
end;
For a string vector I need to (i) create a base vector of pointers with a pre-specified length as for the numeric vector (ii) convert each string in my input array to an R internal character string (CHARSXP) using the R mkChar function (iii) assign the address of the character string struct to the appropriate element in the base vector. The string array gets passed into the constructor of my vector class (TCharacterVector) and I then call SetValue (see below) for each string in the array.
I should have thought of PPointer as suggested by Remy but neither that or the array approach seem to work either. Below is the code using the array approach from Remy and with some pointer vars for checking addresses. I'm just using old-fashioned pointer arithmetic and have shown addresses displayed for a run when debugging:
procedure TCharacterVector.SetValue(ix: integer; value: string);
var
PData: PSEXPREC;
offset: integer;
offset2: integer;
PTest: PSEXPREC;
PPtr: Pointer;
PPtr2: Pointer;
begin
offset := GetOffset(ix);
PPtr := PPointer(NativeUInt(DataPointer) + offset); // $89483D8
PData := mkChar(value); // $8850258
// -- Use the following code to check that mkChar is working.
offset2 := SizeOf(TVECTOR_SEXPREC);
PTest := PSEXPREC(NativeUInt(PData) + offset);
FTestString := FTestString + AnsiString(PAnsiChar(PTest));
//PPointerList(DataPointer)^[ix] := PData;
//PPtr2 := PPointer(NativeUInt(DataPointer) + offset); // Wrong!
PPointerArray(DataPointer)^[ix] := PData;
PPtr2 := PPointerArray(DataPointer)^[ix]; // $8850258 - correct
end;
I'd have thought the address in PData ($8850258) would now be in PPtr2 but I've been staring at this so long I'm sure I'm missing something obvious.
Edit2: The code for SetValue used in R.NET is as follows (ignoring test for null string):
private void SetValue(int index, string value)
{
int offset = GetOffset(index);
IntPtr stringPointer = mkChar(value);
Marshal.WriteIntPtr(DataPointer, offset, stringPointer);
}
From reflector, Marshal.WriteIntPtr uses the following C:
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
{
byte* numPtr = (byte*) (((void*) ptr) + ofs);
if ((((int) numPtr) & 3) == 0)
{
*((int*) numPtr) = val;
}
else
{
byte* numPtr2 = (byte*) &val;
numPtr[0] = numPtr2[0];
numPtr[1] = numPtr2[1];
numPtr[2] = numPtr2[2];
numPtr[3] = numPtr2[3];
}
}
catch (NullReferenceException)
{
throw new AccessViolationException();
}
}
You say you want to copy the struct pointer itself into the array, but the code you have shown is trying to copy the struct data that the pointer is pointing at. If you really want to copy just the pointer itself, don't use CopyMemory() at all. Just assign the pointer as-is:
const
MaxPointerList = 255; // whatever max array count that Func2() allocates
type
TPointerList = array[0..MaxPointerList-1] of Pointer;
PPointerList = ^TPointerList;
PPointerList(DataPointer)^[index] := PStruct;
Your use of NativeUInt reveals that you are using a version of Delphi that likely supports the {$POINTERMATH} directive, so you can take advantage of that instead, eg:
{$POINTERMATH ON}
PPointer(DataPointer)[index] := PStruct;
Or, use the pre-existing PPointerArray type in the System unit:
{$POINTERMATH ON}
PPointerArray(DataPointer)[index] := PStruct;
I would like to translate some type definitions from winnt.h which contain some unions with bitfields. However, is this the correct way of doing it? I am particularly not sure about the union in _TP_CALLBACK_ENVIRON_V3.
typedef struct _UMS_SYSTEM_THREAD_INFORMATION {
ULONG UmsVersion;
union {
struct {
ULONG IsUmsSchedulerThread : 1;
ULONG IsUmsWorkerThread : 1;
} DUMMYSTRUCTNAME;
ULONG ThreadUmsFlags;
} DUMMYUNIONNAME;
} UMS_SYSTEM_THREAD_INFORMATION, *PUMS_SYSTEM_THREAD_INFORMATION;
typedef struct _TP_CALLBACK_ENVIRON_V3 {
TP_VERSION Version;
PTP_POOL Pool;
PTP_CLEANUP_GROUP CleanupGroup;
PTP_CLEANUP_GROUP_CANCEL_CALLBACK CleanupGroupCancelCallback;
PVOID RaceDll;
struct _ACTIVATION_CONTEXT *ActivationContext;
PTP_SIMPLE_CALLBACK FinalizationCallback;
union {
DWORD Flags;
struct {
DWORD LongFunction : 1;
DWORD Persistent : 1;
DWORD Private : 30;
} s;
} u;
TP_CALLBACK_PRIORITY CallbackPriority;
DWORD Size;
} TP_CALLBACK_ENVIRON_V3;
type
UMS_SYSTEM_THREAD_INFORMATION = record
UmsVersion: ULONG;
ThreadUmsFlags: ULONG;
case Integer of
0:(IsUmsSchedulerThread : ULONG);
1:(IsUmsWorkerThread : ULONG);
end;
PUMS_SYSTEM_THREAD_INFORMATION = ^UMS_SYSTEM_THREAD_INFORMATION;
TP_CALLBACK_ENVIRON_V3 = record
Version: TP_VERSION;
Pool: PTP_POOL;
CleanupGroup: PTP_CLEANUP_GROUP;
CleanupGroupCancelCallback: PTP_CLEANUP_GROUP_CANCEL_CALLBACK;
RaceDll: PVOID;
ActivationContext: PACTIVATION_CONTEXT; // Pointer
FinalizationCallback: PTP_SIMPLE_CALLBACK;
case Flags: DWORD of
1: (LongFunction: DWORD)
1: (Persistent: DWORD)
30: (Private: DWORD)
end;
CallbackPriority: TP_CALLBACK_PRIORITY;
Size: DWORD;
end;
PTP_CALLBACK_ENVIRON = ^TP_CALLBACK_ENVIRON_V3;
Those : something notations are bit fields. There is no direct Pascal equivalent.
However, since the three bitfields combined are a complete dword, a general outline for the equivalent becomes something like this:
type
_TP_CALLBACK_ENVIRON_V3 = record
...
FinalizationCallback: PTP_SIMPLE_CALLBACK;
case Integer of
1: (Flags: DWord);
2: (LongFunctionPersistentPrivate: DWord)
end;
As noted, the ':' notations are bit fields. There is no direct solution, but there is a simple way to translate them that makes them useful again. See my article that describes this. It uses a simple set of functions to get or set a number of bits and to shift them into place, and a clever way (I did not invent it, BTW) to declare them, using the rather unknown property index.
Take a look here: Pitfalls of converting
The idea came from a Stack Overflow answer.
FWIW, the article also describes how to handle unions in such translations.
I'm trying to read returned arrays from the TeamSpeak3 SDK, some of the methods returns arrays that are null terminated and multi dimensional with a mix of data types.
What "delhpi" structure should I pass as parameter and how can I read the returned values back in the a matching structure? a la.
type
TDeviceInfo = record
DeviceId : string; // maybe an integer
DeviceName : string;
end;
TDeviceInfoArr = array of TDeviceInfo
// or maybe
TDeviceInfoArr = array of array[0..1] of string;
var
DeviceArr : array of TDeviceInfoArr;
This is what the SDK Documentation says.
To get a list of all available playback and capture devices for the specified mode, call
unsigned int ts3client_getPlaybackDeviceList(modeID, result);
const char* modeID;
char**** result;
unsigned int ts3client_getCaptureDeviceList(modeID, result);
const char* modeID;
char**** result;
Parameters
• modeID
Defines the playback/capture mode to use. For different modes there might be different device lists. Valid modes are returned by
ts3client_getDefaultPlayBackMode / s3client_getDefaultCaptureMode and ts3client_getPlaybackModeList / ts3client_getCaptureModeList.
• result
Address of a variable that receives a NULL-terminated array { { char* deviceName, char* deviceID }, { char* deviceName, char* deviceID }, ... , NULL }.
Unless the function returns an error, the elements of the array and the array itself need to be freed using ts3client_freeMemory.
Returns ERROR_ok on success, otherwise an error code as defined in public_errors.h. In case of an error, the result array is uninitialized and must not be released.
Example to query all available playback devices:
char * defaultMode;
if (ts3client_getDefaultPlayBackMode( & defaultMode) == ERROR_ok) {
char * * * array;
if (ts3client_getPlaybackDeviceList(defaultMode, & array) == ERROR_ok) {
for (int i = 0; array[i] != NULL; ++i) {
printf("Playback device name: %s\n", array[i][0]); /* First element: Device name */
printf("Playback device ID: %s\n", array[i][1]); /* Second element: Device ID */
/* Free element */
ts3client_freeMemory(array[i][0]);
ts3client_freeMemory(array[i][1]);
ts3client_freeMemory(array[i]);
}
ts3client_freeMemory(array); /* Free complete array */
} else {
printf("Error getting playback device list\n");
}
} else {
printf("Error getting default playback mode\n");
}
First of all, I'm going to ignore error handling because I think we handled that in your last question. And I'm going to assume that ts3client_getDefaultPlayBackMode presents no problems.
So that leaves ts3client_getPlaybackDeviceList. Import it like this:
function ts3client_getPlaybackDeviceList(modeID: PAnsiChar;
out result: PPPAnsiChar): Cardinal; cdecl; external '...';
You will likely need to define PPPAnsiChar.
type
PPPAnsiChar = ^PPAnsiChar;
PPAnsiChar = ^PAnsiChar;
You might find that the RTL already defines PPAnsiChar.
So, next to calling the function. First of all declare a variable to hold the array, and so others to help iterate:
var
arr, myarr: PPPAnsiChar;
p: PPAnsiChar;
Then call the function:
ts3client_getPlaybackDeviceList(modeID, arr);
myarr := arr;
while myarr^ <> nil do
begin
p := myarr^;
Writeln('Playback device name: ', p^);
ts3client_freeMemory(p^);
inc(p);
Writeln('Playback device ID: ', p^);
ts3client_freeMemory(p^);
ts3client_freeMemory(myarr^);
inc(myarr);
end;
ts3client_freeMemory(arr);
This code is really quite vile I'm sure that you will agree. If you have a modern version of Delphi then you can enable pointer math to make it read better.
{$POINTERMATH ON}
ts3client_getPlaybackDeviceList(modeID, arr);
i := 0;
while arr[i] <> nil do
begin
Writeln('Playback device name: ', arr[i][0]);
Writeln('Playback device ID: ', arr[i][1]);
ts3client_freeMemory(arr[i][0]);
ts3client_freeMemory(arr[i][1]);
ts3client_freeMemory(arr[i]);
inc(i);
end;
ts3client_freeMemory(arr);
Although this code is better, it will never win a beauty contest.
Remember that I've neglected all error checking. You'll need to add that.
Based on David's suggesstions I found the following code working, thanks David!
{$POINTERMATH ON}
procedure TfrmMain.RequestPlaybackDevices;
var
arr, myarr: PPPAnsiChar;
p: PPAnsiChar;
defaultmode : PAnsiChar;
i : Integer;
begin
try
ts3check(ts3client_getDefaultPlayBackMode(#defaultmode));
ts3check(ts3client_getPlaybackDeviceList(defaultMode, #arr));
try
i := 0;
while arr[i] <> nil do
begin
LogMsg(format('Playback device name: %s',[UTF8ToUnicodeString(arr[i][0])]));
LogMsg(format('Playback device ID: %s',[UTF8ToUnicodeString(arr[i][1])]));
ts3client_freeMemory(arr[i][0]);
ts3client_freeMemory(arr[i][1]);
ts3client_freeMemory(arr[i]);
inc(i);
end;
finally
ts3client_freeMemory(arr);
end;
except
on e: exception do LogMsg(Format('Error RequestPlaybackDevices: %s', [e.Message]));
end;
end;
{$POINTERMATH OFF}
I have two strings, which I need to compare for equality.
String 1 is created in this way:
var
inBuf: array[0..IN_BUF_SIZE] of WideChar;
stringBuilder : TStringBuilder;
mystring1:string;
...
begin
stringBuilder := TStringBuilder.Create;
for i := startOfInterestingPart to endOfInterestingPart do
begin
stringBuilder.Append(inBuf[i]);
end;
mystring1 := stringBuilder.ToString();
stringBuilder.Free;
String 2 is a constant string 'ABC'.
When string 1 is displayed in a debug console, it is equal to 'ABC'. But the comparisons
AnsiCompareText(mystring1, 'ABC')
mystring1 = 'ABC'
CompareStr(mystring1, 'ABC')
all report inequality.
I suppose that I need to convert string 2 ('ABC') to the same type as the string 1.
How can I do that?
Update 26.09.2012:
aMessage is displayed in the log output as {FDI-MSG-START-Init-FDI-MSG-END}
Here's the code for printing the length of strings:
StringToWideChar('{FDI-MSG-START-Init-FDI-MSG-END}', convString, iNewSize);
...
OutputDebugString(PChar('Len (aMessage): ' + IntToStr(Length(aMessage))));
OutputDebugString(PChar('Len (original constant): ' + IntToStr(Length('{FDI-MSG-START-Init-FDI-MSG-END}'))));
OutputDebugString(PChar('Len (convString): ' + IntToStr(Length(convString))));
And here's the log output:
[3580] Len (aMessage): 40
[3580] Len (original constant): 32
[3580] Len (convString): 0
It looks like you're keeping garbage data in your wide string after the meaningful part, in your update, Length(aMessage) returns 40, while your source string's length is 32.
In Delphi a wide string is COM BSTR compatible, meaning it can hold null characters, a null does not terminate it, it keeps its length at a negative offset of the character data. A possible null character in it helps it to be converted to other string types, but it doesn't alter its own termination.
Consider the below,
const
Source = '{FDI-MSG-START-Init-FDI-MSG-END}';
var
ws: WideString;
size: Integer;
begin
size := 40;
SetLength(ws, size);
StringToWideChar(Source, PWideChar(ws), size);
// the below assertion fails when uncommented
// Assert(CompareStr(Source, ws) = 0);
ws := PWideChar(ws); // or SetLength(ws, Length(Source));
// this assertion does not fail
Assert(CompareStr(Source, ws) = 0);
end;
I have an integer field in a ClientDataSet and I need to compare to some values, something like this:
I can use const
const
mvValue1 = 1;
mvValue2 = 2;
if ClientDataSet_Field.AsInteger = mvValue1 then
or enums
TMyValues = (mvValue1 = 1, mvValue2 = 2);
if ClientDataSet_Field.AsInteger = Integer(mvValue1) then
or class const
TMyValue = class
const
Value1 = 1;
Value2 = 2;
end;
if ClientDataSet_Field.AsInteger = TMyValues.Value1 then
I like the class const approach but it seems that is not the delphi way, So I want to know what do you think
Declaration:
type
TMyValues = class
type TMyEnum = (myValue1, myValue2, myValue3, myValue4);
const MyStrVals: array [TMyEnum] of string =
('One', 'Two', 'Three', 'Four');
const MyIntVals: array [TMyEnum] of integer =
(1, 2, 3, 4);
end;
Usage:
if ClientDataSet_Field.AsInteger = TMyValues.MyIntVals[myValue1] then
A cast would generally be my last choice.
I wouldn't say that class consts are not the Delphi way. It's just they have been introduced to Delphi quite recently, and a lot of books and articles you'll find on the internet were written before their introduction, and thus you won't see them widely used. Many Delphi developers (I'd say the majority) will have started using Delphi before they were made available, and thus they're not the first thing that one thinks about.
One thing to consider is backwards compatibility - class constants are relatively new to Delphi so if your code has to be sharable with previous versions than they are out.
I typically use enumerated types, with the difference from yours is that my first enumeration is usually an 'undefined' item to represent NULL or 0 in an int field.
TmyValues = (myvUndefined, myvDescription1, myvDescription2)
if ClientDataSet_Field.AsInteger = Ord(myvDescription1) then...
To use a little bit of Jim McKeeth's answer - if you need to display to the user a text viewable version, or if you need to convert their selected text into the enumerated type, then an array comes in handy in conjuction with the type:
const MYVALS: array [TmyValues ] of string = ('', 'Description1', 'Description2');
You can then have utility functions to set/get the enumerated type to/from a string:
Function MyValString(const pMyVal:TmyValues):string;
begin
result := MYVALS[Ord(pMyVal)];
end;
Function StringToMyVal(const pMyVal:String):TMyValues;
var i:Integer;
begin
result := myvUndefined;
for i := Low(MYVALS) to High(MYVALS) do
begin
if SameText(pMyVal, MYVALS[i]) then
begin
result := TMyValues(i);
break;
end;
end;
end;
Continuing on... you can have scatter routine to set a combo/list box:
Procedure SetList(const DestList:TStrings);
begin
DestList.Clear;
for i := Low(MYVALS) to High(MYVALS) do
begin
DestList.Insert(MYVALS[i]);
end;
end;
In code: SetList(Combo1.Items) or SetList(ListBox1.Items)..
Then if you are seeing the pattern here... useful utility functions surrounding your enumeration, then you add everything to it's own class and put this class into it's own unit named MyValueEnumeration or whaterver. You end up with all the code surrounding this enumeration in one place and keep adding the utility functions as you need them. If you keep the unit clean - don't mix in other unrelated functionality then it will stay very handy for all projects related to that enumeration.
You'll see more patterns as time goes and you use the same functionality over and over again and you'll build a better mousetrap again.
When using constants I recommend assigning the type when the data type is a numeric float.
Delphi and other languages will not always evaluate values correctly if the types do not match...
TMyValue = class
const
// will not compare correctly to float values.
Value1 = 1; // true constant can be used to supply any data type value
Value2 = 2; // but should only be compared to similar data type
// will not compare correctly to a single or double.
Value3 = 3.3; // default is extended in debugger
// will not compare correctly to a single or extended.
Value1d : double = Value1; // 1.0
Value2d : double = Value2; // 2.0
end;
Compared float values in if () and while () statements should be compared to values of the same data type, so it is best to define a temporary or global variable of the float type used for any comparison statements (=<>).
When compared to the same float data type this format is more reliable for comparison operators in any programming language, not just in Delphi, but in any programming language where the defined float types vary from variable to constant.
Once you assign a type, Delphi will not allow you to use the variable to feed another constant, so true constants are good to feed any related data type, but not for comparison in loops and if statements, unless they are assigned and compared to integer values.
***Note: Casting a value from one float type to another may alter the stored value from what you entered for comparison purposes, so verify with a unit test that loops when doing this.
It is unfortunate that Delphi doesn't allow an enumeration format like...
TController : Integer = (NoController = 0, ncpod = 1, nextwave = 2);
or enforce the type name for access to the enumeration values.
or allow a class constant to be used as a parameter default in a call like...
function getControllerName( Controller : TController = TController.NoController) : string;
However, a more guarded approach that provides both types of access would be to place the enumeration inside a class.
TController = class
//const
//NoController : Integer = 1;
//ncpod : Integer = 2;
//nextwave : Integer = 3;
type
Option = (NoController = 0, ncpod = 1, nextwave = 2);
public
Class function Name( Controller : Option = NoController) : string; static;
end;
implementation
class function TController.Name( Controller : Option = NoController) : string;
begin
Result := 'CNC';
if (Controller = Option.nextwave) then
Result := Result + ' Piranha'
else if (Controller = Option.ncpod) then
Result := Result + ' Shark';
Result := Result + ' Control Panel';
end;
This approach will effectively isolate the values, provide the static approach and allow access to the values using a for () loop.
The access to the values from a floating function would be like this...
using TControllerUnit;
function getName( Controller : TController.Option = TController.Option.NoController) : string;
implementation
function getName( Controller : TController.Option = TController.Option.NoController) : string;
begin
Result := 'CNC';
if (Controller = TController.Option.nextwave) then
Result := Result + ' Piranha'
else if (Controller = TController.Option.ncpod) then
Result := Result + ' Shark';
Result := Result + ' Control Panel';
end;
so many options! :-) i prefer enums and routinely use them as you describe. one of the parts i like is that i can use them with a "for" loop. i do use class constants as well but prefer enums (even private enums) depending on what i'm trying to achieve.
TMyType=class
private const // d2007 & later i think
iMaxItems=1; // d2007 & later i think
private type // d2007 & later i think
TMyValues = (mvValue1 = 1, mvValue2 = 2); // d2007 & later i think
private
public
end;
An option you haven't thought of is to use a lookup table in the database and then you can check against the string in the database.
eg.
Select value, Description from tbl_values inner join tbl_lookup_values where tbl_values.Value = tbl_lookup_values.value
if ClientDataSet_Field.AsString = 'ValueIwant' then