I have a class of type TObject called CModelItem
I want to have a list of these objects and be able to modify the values of each one
So, I created a class
CQueueList = class(TList)
private
public
end;
and I make
QueueList : CQueueList;
in var
Now, I can add the CModelItem to this list, like so:
QueueList := CQueueList.Create;
for idx := 0 to ndx - 1 do
begin
MyItem := CModelItem.Create;
MyItem.CopyHead(CModelItem(RunList.Objects[idx]));
MyItem.ReadData;
MyItem.NumOfIterations := NumRepEdit.Value;
MyItem.IsInQueue := True;
MyItem.LogEvents := EventsCheckBox.Checked;
MyItem.LogMatch := MatchCheckBox.Checked;
MyItem.LogUpdates := UpdatesCheckBox.Checked;
QueueList.Add(MyItem);
end;
I can also use it, so I can do:
DefForm := TRunDefForm.Create(Self, QueueList.Items[idx]);
with DefForm taking in a component and a CModelItem
But I'm running into problems trying to modify the values of an object in QueueL
First, I can't access something like MyItem.IsInQueue by doing
QueueList.Items[idx].IsInQueue := blah;
because it tells me IsInQueue is 'an undeclared identifier'
I've also tried making a new CModelItem and copying the information over, like this:
idx := QueueListBox.ItemIndex;
MyItem := QueueList.Items[idx];
and this compiles fine, but throws up an 'access violation error' when it goes into that function
I noticed that QueueList.Items[idx] is a pointer, but I'm really not sure how I should be accessing it
The compiler complains because TList.Items returns an untyped pointer.
You can use a typecast:
CModelItem(QueueL.Items[idx]).IsInQueue := blah;
You can also reimplement the Items property in your CQueueList class:
private
function GetItems(Index: Integer): CModelItem;
public
property Items[Index: Integer]: CModelItem read GetItems; default;
end;
function CQueueList.GetItems(Index: Integer): CModelItem;
begin
Result := inherited Items[Index];
end;
As you've seen, using a local variable works; although the access violation is a bug probably somewhere else in your code.
Related
I'm refactoring a component code, and I found the follow code:
procedure TMenuToolbarButton.ClearActivation;
var
i: Integer;
begin
for i := 0 to Self.Parent.ComponentCount -1 do
begin
if (Self.Parent.Components[i] is TMenuToolbarButton) then
begin
(Self.Parent.Components[i] as TMenuToolbarButton).FActivatedImage.Visible := False;
(Self.Parent.Components[i] as TMenuToolbarButton).FActivatedImageGrowLeft.Visible := False;
end;
end;
end;
I'ts working perfectly today, but i want to use for/in in this method, something like this:
procedure TMenuToolbarButton.ClearActivation;
var
MyMenuToolbarButton: TMenuToolbarButton;
begin
for MyMenuToolbarButton in Self.Parent do
begin
MyMenuToolbarButton.FActivatedImage.Visible := False;
MyMenuToolbarButton.FActivatedImageGrowLeft.Visible := False;
end;
end;
I already tried with Generics.Collections casting the Self.Parent like this: TObjectList<TMenuToolbarButton>(Self.Parent)
So, I want to know if is there a better way to make the working code more "elegant"
The Parent is a TWinControl, not a TObjectList, so your attempted typecast is invalid.
You can't use a for.. in loop with the Components property directly, as it is not an iterable container that meets any of the documented requirements:
Delphi supports for-element-in-collection style iteration over containers. The following container iteration patterns are recognized by the compiler:
for Element in ArrayExpr do Stmt;
for Element in StringExpr do Stmt;
for Element in SetExpr do Stmt;
for Element in CollectionExpr do Stmt;
for Element in Record do Stmt;
The Components property is not an Array, a String, a Set, a Collection, or a Record, so it can't be iterated by a for..in loop.
However, TComponent itself satisfies the documented requirements of an iterable Collection:
To use the for-in loop construct on a class or interface, the class or interface must implement a prescribed collection pattern. A type that implements the collection pattern must have the following attributes:
The class or interface must contain a public instance method called GetEnumerator(). The GetEnumerator() method must return a class, interface, or record type.
The class, interface, or record returned by GetEnumerator() must contain a public instance method called MoveNext(). The MoveNext() method must return a Boolean. The for-in loop calls this method first to ensure that the container is not empty.
The class, interface, or record returned by GetEnumerator() must contain a public instance, read-only property called Current. The type of the Current property must be the type contained in the collection.
TComponent has a public GetEnumerator() method which returns a TComponentEnumerator object that internally iterates the Components property. But, since the property deals with TComponent objects, you will still have to manually typecast them inside the loop.
Try this:
procedure TMenuToolbarButton.ClearActivation;
var
//i: Integer;
Comp: TComponent;
Btn: TMenuToolbarButton;
begin
//for i := 0 to Self.Parent.ComponentCount -1 do
for Comp in Self.Parent do
begin
//Comp := Self.Parent.Components[i];
if Comp is TMenuToolbarButton then
begin
Btn := TMenuToolbarButton(Comp);
Btn.FActivatedImage.Visible := False;
Btn.FActivatedImageGrowLeft.Visible := False;
end;
end;
end;
So, using a for..in loop does not really gain you anything useful over a traditional for..to loop in this situation.
TComponent implements method GetEnumerator by returning instance of TComponentEnumerator, which enumerates all components owned by this component. In order to use this enumerator you could change your local variable declaration to var MyMenuToolbarButton: TComponent;, but you would still need to type-cast inside the loop.
If you really, really want to use for..in loop for enumerating components of specified type, you can write your own generic enumerator:
type
TComponentEnumerator<T: TComponent> = record
private
FIndex: Integer;
FComponent: TComponent;
public
constructor Create(AComponent: TComponent);
function GetCurrent: T; inline;
function GetEnumerator: TComponentEnumerator<T>;
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
constructor TComponentEnumerator<T>.Create(AComponent: TComponent);
begin
FIndex := -1;
FComponent := AComponent;
end;
function TComponentEnumerator<T>.GetCurrent: T;
begin
Result := T(FComponent.Components[FIndex]);
end;
function TComponentEnumerator<T>.GetEnumerator: TComponentEnumerator<T>;
begin
Result := Self;
end;
function TComponentEnumerator<T>.MoveNext: Boolean;
begin
Inc(FIndex);
while (FIndex < FComponent.ComponentCount) and (not (FComponent.Components[FIndex] is T)) do
Inc(FIndex);
Result := FIndex < FComponent.ComponentCount;
end;
Usage:
procedure TMenuToolbarButton.ClearActivation;
var
MyMenuToolbarButton: TMenuToolbarButton;
begin
for MyMenuToolbarButton in TComponentEnumerator<TMenuToolbarButton>.Create(Self.Parent) do
begin
MyMenuToolbarButton.FActivatedImage.Visible := False;
MyMenuToolbarButton.FActivatedImageGrowLeft.Visible := False;
end;
end;
Few notes:
This is pretty naïve implementation which is not protected against some edge cases like changing the components collection while iterating, cross-thread access, ... Of course your original code does none of that, but when you write general purpose class, you should consider making it more foolproof or document its limitations.
This implementation enumerates components of type T or its descendants.
Using enumerators adds small overhead when compared to simple for..to loop.
I've looked at many questions and resources which deal with the "Self" variable in an Object, but everyone says something different.
For example, in this question: Delphi Self-Pointer usage
the highest rated answer to the question appears to be wrong. Pointer(Self) does not point to the object which contains it, and cannot be used to pass references from inside the object.
I've tried doing this:
Type
myobject = class
PSelf: Pointer;
End;
Var
Obj: myobject;
Procedure RunProgram;
Begin
Obj := myobject.create;
Obj.PSelf := #Obj;
//Run the rest of the program
.
.
.
and for the most part, this has worked just fine.
My question is: is this a good coding practice? Can the "PSelf" variable be expected to point to the object for the duration of the program's execution?
I recently came across a bug where "PSelf" had stopped pointing to it's containing object, and I'm wondering if objects ever get shuffled around in the heap, or whether the memory had been corrupted.
Edit:
There is some instance in which using the "Self" variable didn't work for me, and now I cannot duplicate it. So this whole question is pointless, as is my technique of using a 'PSelf' variable. Sorry about that.
And as Ken pointed out, the link above has a correct answer :)
I think you're misunderstanding what Self is, and how object references work in Delphi.
A variable containing an instance of a class is already a pointer to that object instance. The Delphi compiler just allows you to leave out the dereference operator (^) as a convenience.
var
MyObject: TMyObject;
begin
MyObject := TMyObject.Create; // MyObject is now a pointer to an instance of TMyObject
...
Delphi also allows the shorthand of not using the dereference operator when accessing members or properties of the object instance. Again, the following code is actually equivalent:
MyObj.SomeProperty := SomeValue;
MyObj^.SomeProperty := SomeValue;
From the Delphi documentation:
A variable of a class type is actually a pointer that references an object. Hence more than one variable can refer to the same object. Like other pointers, class-type variables can hold the value nil. But you don't have to explicitly dereference a class-type variable to access the object it points to. For example, SomeObject.Size := 100 assigns the value 100 to the Size property of the object referenced by SomeObject; you would not write this as SomeObject^.Size := 100.
Self is an automatically declared property that points to the current instance of the object. In other words, it's automatically available inside the code that implements that class to reference the current instance of the object. This allows you to have multiple instances of the same object:
type
TMyObject=class(TObject)
private
FMyInteger: Integer;
function GetMyInteger: Integer;
procedure SetMyInteger(Value: Integer);
published
property MyInteger: Integer read GetMyInteger write SetMyInteger;
end;
...
function TMyObject.GetMyInteger: Integer;
begin
Result := Self.FMyInteger;
// Self is implied, so the above line can more simply be written as
// Result := FMyInteger;
end;
procedure TMyObject.SetMyInteger(Value: Integer);
begin
if (Value <> Self.FMyInteger) then // Self is again implied here
Self.FMyInteger := Value;
end;
var
MyObjOne, MyObjTwo: TMyObject;
i, j: Integer;
begin
MyObjOne := TMyObject;
// Here, the code inside TMyObject.SetInteger that
// uses `Self` would refer to `MyObjOne`
MyObjOne.MyInteger := 1;
MyObjTwo := TMyObject;
// Here, the code in TMyObject.SetInteger would be
// using the memory in `MyObjTwo` when using `Self`
MyObjTwo.MyInteger := 2;
end;
Note that Self is only valid in the code that implements the class. It's available and valid in TMyObject.GetMyInteger and TMyObject.SetMyInteger above (the only implemented code in my example), and always refers to the current instance.
There's no need to keep track of the addresses of Self, as the variable referencing that object instance is Self inside methods of that object instance. It's only valid inside that instance of the object, and always refers to that object instance. So in your code example, PSelf is just wasted space - myobject already contains a pointer to itself, and that pointer is automatically available in methods of myobject:
type
myobject = class; // Now automatically contains a `Self` pointer
// available in methods of the class once an
// instance is created
var
myobj: myobject;
begin
myobj := myobject.Create; // myobj.Self now is valid in methods of
// `myobject`
Here's my resolution to the problem. I'm still wondering why the second example doesn't work.
This works (but is the wrong way to do it):
Type
myobject1 = class(TObject)
PSelf: Pointer;
Number: Integer;
Function GiveReference: Pointer;
End;
pmyobject1: ^myobject1;
myobject2 = class(TObject)
p: pmyobject1;
End;
Var
Obj1: myobject1;
Obj2: myobject2;
Function myobject1.GiveReference: Pointer;
Begin
Result := PSelf;
End;
Procedure RunProgram;
Var
i: Integer;
Begin
Obj1 := myobject1.create;
Obj1.PSelf := #Obj1;
Obj2 := myobject2.create;
Obj2.P := Obj.GiveReference;
//to access 'number', this works
i := Obj2.P^.Number;
//Run the rest of the program
.
.
.
This does not work, but in my mind is exactly the same. This is what caused me to distrust the 'self' variable (even though yes, I was making a pointer to a pointer).
Type
myobject1 = class(TObject)
Number: Integer;
Function GiveReference: Pointer;
End;
pmyobject1: ^myobject1;
myobject2 = class(TObject)
p: pmyobject1;
End;
Var
Obj1: myobject1;
Obj2: myobject2;
Function myobject1.GiveReference: Pointer;
Begin
Result := #Self;
End;
Procedure RunProgram;
Var
i: Integer;
Begin
Obj1 := myobject1.create;
Obj2 := myobject2.create;
Obj2.P := Obj.GiveReference;
//This will fail, some of the time, but not all of the time.
//The pointer was valid while 'GiveReference' was being called, but
//afterwards, it is not valid.
i := Obj2.P^.Number;
//Run the rest of the program
.
.
.
And finally, this is what I should have been doing all along:
Type
myobject1 = class(TObject)
Number: Integer;
Function GiveReference: Pointer;
End;
myobject2 = class(TObject)
p: myobject1;
End;
Var
Obj1: myobject1;
Obj2: myobject2;
Function myobject1.GiveReference: Pointer;
Begin
Result := Self;
End;
Procedure RunProgram;
Var
i: Integer;
Begin
Obj1 := myobject1.create;
Obj2 := myobject2.create;
Obj2.P := Obj.GiveReference;
//No problems with this, although I would generally check if P was assigned prior to
//reading from it.
i := Obj2.P.Number;
//Run the rest of the program
Obj1.Free;
Obj2.P := nil;
I hadn't done this in the first place, because I was concerned that by not using a pointer, that I might actually be duplicating the entire object.
I am not sure if I am doing this right. I have a list of objects in the listbox and need to use IndexOf to get an object's index in the list.
if AlarmListBox.items.indexOf(alrm.Tagname) = -1 then
alrm is an object of TAlarm class.
Based on a StackOverflow C# question (How Can I Get the Index of An Item in a ListBox?), I try to override GetHashCode and Equals method, but still it doesn't work right.
Overriden Method:
TAlarm = class(System.Object)
TagName:string;
private
protected
public
method Equals(obj:System.Object):Boolean; override;
method GetHashCode:Int32; Override;
end;
method TAlarm.Equals(obj: system.Object):Boolean;
begin
result := TAlarm(obj).Tagname.Equals(self.Tagname);
end;
method TAlarm.GetHashCode:Int32;
begin
result := self.GetHashCode;
end;
This is how I populate AlarmListBox:
AlmGrp:= new TAlarmGroup;
AlarmListBox.items.Add(AlmGrp);
Compiler compiles without any errors, but when I debug the program line by line it always returns -1 and these overridden methods are never called or fired.
Am I implementing these overrides correctly? If not, how should I override them?
Sample code or hints or clues will be appreciated. Thanks,
UPDATE: To David Heffernan and others who have commented or answered, I think the problem might be that I am passing in two different object as Rob's last comment states. I do populate Listbox (UI) with TAlarmGroup but pass in TAlarm into IndexOf, although they both are identical classes. This is probably my problem. What I am really trying to do is populate Listbox with TAlarmGroup objects and through listbox.indexof by passing in the string (Tagname) I search for the object location. That's how it is done on Delphi XE it works great. The code above is not the actual code. Once I clean up the confusion in my code, it will probably work without overriding the GetHashcode and Equals method.
UPDATE: I think, I have stumbled onto something here. On Delphi XE or below, ListBox (UI) provides a method called AddObject. It's parameters are a string and an object respectively. So, when I populated objects into listbox I also provided the string to go along with it. When I searched I passed in a string or the alarm group name. IndexOf searched on this string against the string it had for each object I provided and not against the object's field (TagName). In Delphi Prism, listbox doesn't have a similar method as AddObject method but only Add that only accepts object as a parameter.
Here's an example of doing what you want with the base TAlarm class you provided. I've also provided implementations of the overloaded Equals and GetHashCode that seem to work. (Again, I'm not a Prism/.NET developer; just trying to help out here.)
// In AlarmClass.pas
type
TAlarm = class(System.Object)
TagName:string;
private
protected
public
constructor;
method Equals(obj:System.Object): Boolean; override;
method GetHashCode:Int32; Override;
method ToString(): String; override;
end;
implementation
method TAlarm.GetHashCode: Int32;
begin
if Self = nil then
Result := inherited
else
Result := Self.TagName.GetHashCode;
end;
constructor TAlarm;
begin
inherited;
end;
method TAlarm.Equals(obj: System.Object): Boolean;
begin
if (obj = nil) or (GetType() <> obj.GetType()) then
Exit(False);
Result := TAlarm(obj).TagName.Equals(Self.TagName);
end;
method TAlarm.ToString(): String;
begin
Result := Self.TagName;
end;
// In MainForm.pas
method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
var
Idx: Integer;
begin
Idx := ComboBox1.SelectedIndex;
if Idx <> -1 then
ListBox1.SelectedIndex := ListBox1.Items.IndexOf(ComboBox1.Items[Idx]);
end;
method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
var
i, j: Integer;
Alarm: TAlarm;
aList: Array[0..4] of Object;
aFind: Array[0..1] of Object;
begin
j := 0;
for i := 0 to 4 do
begin
Alarm := new TAlarm;
Alarm.TagName := String.Format('Alarm{0}', i);
aList[i] := Alarm;
// Place items 1 & 3 in another array of searchable items -
// just for fun. Not suggesting implementing your app this way
// by any means.
if (i mod 2) > 0 then
begin
aFind[j] := Alarm;
Inc(j);
end;
end;
ListBox1.Items.AddRange(aList);
ComboBox1.Items.AddRange(aFind);
end;
Here's how it looks with an item selected in the ComboBox after clicking the Button:
I passed ref of interface from Visio Add-ins to MyCOMServer (Interface Marshalling in Delphi have to pass interface as pointer in internals method of MyCOMServer. I try to pass interface to internal method as pointer of interface, but after back cast when i try call method of interface I get exception. Simple example(Fisrt block execute without error, but At Second block I get Exception after addressed to property of IVApplication interface):
procedure TMyCOMServer.test(const Interface_:IDispatch); stdcall;
var
IMy:_IMyInterface;
V: Variant;
Str: String;
I: integer;
Vis: IVApplication;
begin
......
{First code Block}
Self.QuaryInterface(_IMyInterface,IMy);
str := IMy.ApplicationName;
V := Integer(IMy);
i := V;
Pointer(IMy) := Pointer(i);
str := IMy.SomeProperty; // normal completion
{Second code Block}
str := (Interface_ as IVApplication).Path;
V := Interface_;
I := V;
Pointer(Vis) := Pointer(i);
str := Vis.Path; // 'access violation at 0x76358e29: read of address 0xfeeefeee'
end;
Why I can't do like this?
When you have an object that implements multiple interfaces and you cast between them you will get different addresses. It has to do something with how to find the methods of those interfaces.
Let's say that you have two interfaces and a class that implements them, the methods show just a message with the methodname:
type
IMyIntfA = interface
['{21ADE2EF-55BB-4B78-A23F-9BB92BE55683}']
procedure A;
procedure X;
end;
IMyIntfB = interface
['{7E1B90CF-569B-4DD1-8E46-7E7255D2373A}']
procedure B;
end;
TMyObject = class(TInterfacedObject, IMyIntfA, IMyIntfB, IUnknown)
public
procedure A;
procedure X;
procedure B;
end;
When you tell the compiler to call A from IMyIntfA, it knows that A is located at the address of IMyIntfA plus an offset. The same applies to calling method B from IMyIntfB.
But what you are doing is putting the reference to IMyIntfB in a var of IMyIntfA and then call method A. The result is that the address of the method the compiler calculates is totally wrong.
var
lIntfA: IMyInterfaceA;
lIntfB: IMyInterfaceB;
begin
lIntfA := TMyObject.Create; //TMyObject implements IMyInterfA, IMyInterfB
lInfB := lIntfA as IMyInterfaceB;
if Integer(lIntfA) <> Integer(lIntfB) then
ShowMessage('I told you so');
Pointer(lIntfA) := Pointer(lIntfB);
lIntfA.A; //procedure B is called, because B is at "Offset 1", like A
lIntfA.X; //total mayhem, X is at "Offset 2", but there is nothing at IMyIntfB + offset 2
end;
PS: I'am not a guru and I don't know the technical details about how everything is implemented. This is only a rough explanation which should give you an idea of why your code goes wrong. If you want your code to succeed do this:
Vis := Interface_ as IVApplication;
Str := (Vis.Path);
I'm only guessing since I don't know much about COM, but casting an interface to an integer or pointer does mess up the internal reference counting. Your interface is likely to be released, which would explain the access violation.
EDIT: I wonder that Pointer(Vis) := Pointer(i) works anyway. Shouldn't the cast create a temporary object. Maybe that's why Vis does not get assigned?
Hey all, first sorry for my bad english.
Consider the following (not actual code):
IMyInterface = Interface(IInterfce)
procedure Go();
end;
MyClass = class(IMyInterface)
procedure Go();
end;
MyOtherClass = class
published
property name: string;
property data: MyClass;
end;
I'm setting "MyOtherClass" properties using RTTI. For the string property it's easy, but my question is:
How can I get a reference to the "data" (MyClass) property so I can call the Go() method?
I want to do something like this (pseudo-code):
for i:= 0 to class.Properties.Count
if (propertyType is IMyInterface) then
IMyInterface(class.properties[i]).Go()
(if only this was C# :( )
PS.: this is in delphi 7 (i know, even worse)
If the string property is easy, as you say, then I assume you're calling GetStrProp and SetStrProp from the TypInfo unit. Class-type properties can be equally easy with GetObjectProp and SetObjectProp.
if Supports(GetObjectProp(Obj, 'data'), IMyInterface, Intf) then
Intf.Go;
If you don't really need the interface, and you know that the data property has type TMyClass, then you can go a little more directly:
(GetObjectProp(Obj, 'data') as TMyClass).Go;
That requires the property to have a non-null value.
If you don't know the name of the property you want, then you can use some other things in TypInfo to search for it. For example, here is a function that will find all the published properties of an object that have values that implement IMyInterface; it calls Go on each of them in no particular order.
procedure GoAllProperties(Other: TObject);
var
Properties: PPropList;
nProperties: Integer;
Info: PPropInfo;
Obj: TObject;
Intf: IMyInterface;
Unk: IUnknown;
begin
// Get a list of all the object's published properties
nProperties := GetPropList(Other.ClassInfo, Properties);
if nProperties > 0 then try
// Optional: sort the list
SortPropList(Properties, nProperties);
for i := 0 to Pred(nProperties) do begin
Info := Properties^[i];
// Skip write-only properties
if not Assigned(Info.GetProc) then
continue;
// Check what type the property holds
case Info.PropType^^.Kind of
tkClass: begin
// Get the object reference from the property
Obj := GetObjectProp(Other, Info);
// Check whether it implements IMyInterface
if Supports(Obj, IMyInterface, Intf) then
Intf.Go;
end;
tkInterface: begin
// Get the interface reference from the property
Unk := GetInterfaceProp(Obj, Info);
// Check whether it implements IMyInterface
if Supports(Unk, IMyInterface, Intf) then
Intf.Go;
end;
end;
end;
finally
FreeMem(Properties);
end;
end;
You can get an array of all published propertied by calling GetPropInfos(MyClass.ClassInfo). This is an array of PPropInfo pointers. And you can get at type-specific data from a PPropInfo by calling GetTypeData on it, which returns a PTypeData. The record it points to will have the information you're looking for about the class reference.