I have come across a below function in a delphi code. I am quite new to delphi.There are quite a few places in Delphi where this function is called. However I can't seem to find the definition of this function. Could someone please explain what this means.
property OnProcessEvent: TOnProcessEventProc read FOnProcessEvent write FOnProcessEvent;
That declaration is not a function, it is a property, or more specifically an event. In that same class, you will see a data member named FOnProcessEvent of type TOnProcessEventProc. If you look at the declaration of TOnProcessEventProc, you will see that it is an alias for a method pointer of a specific signature, eg:
type
TOnProcessEventProc = procedure(Sender: TObject; ... other parameters here ...) of object;
That means any non-static class method that matches that signature can be assigned to the OnProcessEvent event. And if the event is declared as published, such a method can even be assigned at design-time instead of in code at run-time.
In the code for the class that declares the event property, all it has to do is call FOnProcessEvent() as if it were a procedure, eg:
if Assigned(FOnProcessEvent) then
FOnProcessEvent(Self, ... parameter values here ...);
Whatever method is actually assigned to FOnProcessEvent, if any, will be called.
Related
Is there some common ancestor for Delphi delegates which are declared with of object clause?
I need to find a common ancestor for TNotifyEvent and my custom delegate:
TMyEvent = procedure(Sender: TObject; msg: stringh); of object;
to make an universal method for firing these events.
Should I use Pointer? or TObject?
You need to get down and dirty with the implementation details for method pointers. These are stored as a so-called double pointer value. One pointer for the subject of the method call (the instance) and one pointer for the method itself (the code).
You can use the type TMethod from the System unit to represent method pointers. Its declaration looks like so (with the comparison operators removed for simplicity):
type
TMethod = record
Code, Data: Pointer;
end;
You need to use a typecast to make assignments between these types:
uses
System.Classes;
var
Event: TNotifyEvent;
Method: TMethod;
begin
Method := TMethod(Event);
TMethod(Event) := Method;
end.
Obviously none of this is type-safe so you need to ensure correctness. The compiler cannot help you. There is nothing like the checked type conversion operator, as, to work with method pointers. That is, it is up to you that when you cast from TMethod to a specific method pointer type, you have to make sure that the TMethod instance really is an instance of the method pointer type to which you cast. Think of this whole process as being analogous to casting from a typed pointer to an untyped pointer, and then back again.
Now, if you are going to store arbitrary method pointers into TMethod instances, that's fine. But what happens when you subsequently need to fire these methods. You need to know which type of method pointer is really behind each TMethod instance. So that you know how to cast it, what arguments it needs, and so how to call it. That's going to mean you have to store extra information about the true type of the method, alongside the raw method itself.
So, I think that I have perhaps answered the question that you asked, but I'm not sure it's going to be of much use to you. To understand that I think we'd really need to know more about what you are trying to achieve, and what information you have, when.
For instance, if you know the arguments that are to be passed to the method at the time you need to store it away, you could use variable capture and wrap it in an anonymous method. That would allow you to retain type-safety and avoid any of the rather dubious casts that I demonstrate above. Perhaps you need partial application, as a means of adapting your non-homogeneous method pointers to have the same interface. In which case again anonymous methods can help.
I want to add a method to an existing Delphi class. I think basic class framework OK but need to access some properties of the object that called my method in my method. I can't seem to get anything to work.
old class TStringGrid
new class OptStringGrid where myNewMethod is referenced
//example of new class method
procedure myNewMethod (const Name: string);
begin
//Here is my question location.
// I would like to access properties of the calling object in this case
// testgrid. Like... i:= testgrid.rowcount;
end
// Unit Calling statements
var
testGrid : OptStringGrid;
i: integer;
begin
i := testgrid.myNewMethod(strName);
end;
New to Delphi, forgive my terminology if wrong please. I know example code not compilable. I'm looking for techniques to access the properties as described.
To access members of the object whose method is executing, you can use the Self variable. It's automatically declared and assigned inside any method body. In fact, its use is usually implicit — any members of the object are automatically in scope inside the method body. You generally only need to qualify member access with Self when there is already some other variable in the method that has the same name as the member you wish to use.
The key thing about implementing methods is that you need to make sure they're actually methods. The code shown in the question does not define myNewMethod as a method. Rather, it's a standalone subroutine. Only methods can be called on objects, and therefore only methods can have access to the objects they're called on.
A method declaration appears inside a class declaration. Yours might look something like this:
type
TOptStringGrid = class(TStringGrid)
public
function myNewMethod(const Name: string): Integer;
end;
A method definition appears in the implementation section of your unit, along with all your other subroutine bodies, just like all the event-handler implementations the IDE creates for you when you double-click events in the Object Inspector. Those are just ordinary methods.
What distinguishes a method implementation from an implementation of some other kind of subroutine is that the method name includes the name of the class it belongs to:
function TOptStringGrid.myNewMethod(const Name: string): Integer;
begin
// ...
end;
Observe the TOptStringGrid. portion in the code above. That's how the compiler knows that the method body belongs to that class and not anything else named myNewMethod.
Within that method body, you can access all the published, public, and protected members of the ancestor class, TStringGrid, including the RowCount property.
I have an ADOStoredProc on my form. It's not visual but in code.Normally it's pretty easy to handle an event if a component is visual.It's just a matter of double clicking the desired event. But how do I do it with code.I've declared a procedure:
procedure SP_SearchAfterScroll(DataSet:TDataSet)
Now how do I assign SP_Search(this is the ADOStoredProc) AfterScroll event handler property to the procedure I wrote above. I'm sure you're going to answer it. So thanks in advance.
When SP_Search is the TAdoStoredProc and has an OnAfterScroll property, all you need to do is:
SP_Search.OnAfterScroll := SP_SearchAfterScroll;
I am assuming that you used the correct signature for SP_SearchAfterScroll. That is to say that the OnAfterScroll property has a type looks like:
TScrollEvent = procedure(DataSet: TDataSet) of object;
If the OnAfterScroll property has a type that differs from this, you will need to make sure that your SP_SearchAfterScroll procedure matches the parameters in that type.
Edit
In the comments Mikayil asked
SP_Search.AfterScroll :=
SP_SearchAfterScroll(SPSearch)' the
compiler complains saying incompatible
types TNotifyEvent and procedure. But
when I write SP_Search.AfterScroll :=
SP_SearchAfterScroll it works. What's
the difference?
I hadn't gotten round to answering that and in the mean time Mikey explained it very well, so for (easier) future reference I am including his explanation up here:
SP_Search.AfterScroll := that code
assigns a function to handle the event
when it fires - you are not making a
call to SP_SearchAfterScroll at
'assign time' just assigning a value
to a variable, so you don't pass
parameter. Parameter is needed when
call is made - when event fires then
caller will assign parameter with the
right value. When you pass the
parameter,compiler assumes you are
calling the function, not assigning
it, so you get incompatible types
error. When you simply assign the
function without the parameter,
compiler understands you're assigning,
not calling the function.
Declare as:
TDataSetNotifyEvent
then it works
I've encountered some code that's new to me...
I've never really seen a type declaration of a procedure of object, and I just don't
see the point.
Why couldn't the developer simply keep a field of type Boolean?
interface
type
TFinishedCaptureEvent = procedure(AFinished: Boolean) of object;
TFrameCard = class(TFrame)
...
private
FOnFinishedCapture: TFinishedCaptureEvent;
procedure DoUpdateMessage(AMessageType: TMessageType);
public
property OnFinishedCapture: TFinishedCaptureEvent read FOnFinishedCapture write FOnFinishedCapture;
end;
implementation
...
procedure TFrameCard.DoUpdateMessage(AMessageType: TMessageType);
begin
if Assigned(FOnFinishedCapture) then
FOnFinishedCapture(False);
...
end;
end.
Let's break this down into two parts to be easier to understand. First, procedure(AFinished: Boolean) isn't a boolean variable, it's a reference to a procedure that takes a boolean as a parameter. It's basically a procedure header, except without the procedure name because this is just a type definition. Any procedure that matches this signature can be assigned to this variable.
The of object part means that this isn't just a procedure reference, but a method reference; it has to belong to an object. The compiler needs to know the difference so that it can store the self pointer for the object together with the procedure pointer so it can be invoked properly, as the other posters have pointed out.
Basically, this is declaring a new event handler, and it's a pretty common pattern in Delphi. It's the same thing that the VCL does all over the place. When you create a button and assign an OnClick handler, it has to be a procedure (Sender: TObject) of object;. Your form gives the button a method reference referring to itself and the event handler procedure, and then the button uses that information to invoke the handler on the form when someone clicks it.
This code is doing the same thing. It's providing a way for some external object to be notified when DoUpdateMessage runs, using the standard Delphi idiom for event notification.
A procedure of object is a procedure reference for procedures contained in class instances. When calling procedures that are members of a class, the implict Self reference must be passed with the other parameters. Using procedure of object tells the compiler to store the Self reference with the procedure address inside the procedure reference, so that when the procedure is called via the procedure reference, the Self reference will be automatically passed.
In the code snippet you provided, TFinishedCaptureEvent is defined as a procedure of object, meaning that any variables created of its type will contain 2 values: the Self value and the procedure address. When this variable is assigned to, in particular when the assignment is inside a class, the compiler will automatically set the Self value inside this variable to the instance of the class that contains the procedure being assigned to the variable. When the variable is called (FOnFinishedCapture(False)), the compiler automatically passes the correct Self value back to the procedure that was assigned to this variable.
I don't understand how you relate this to a field of boolean.
But TFinishedCaptureEvent = procedure(AFinished: Boolean) of object declares a delegate/method pointer type, which is used for events. It's a record which contains a self pointer and a function pointer. When you call the delegate, the function is called with the self passed as a parameter to the function.
I'm effectively trying to deserialize a form.
One of the objects on the serialized form has a method which takes a series of events as parameters.
Now since I don't have the class type of the object when I'm deserializing, I have a method on the object doing the deserialization called AddMethod which is declared like this:
procedure TMyDeserializer.AddMethod(ControlName, EventName: String;
MethodAddr: Pointer);
var
TargetControl : TControl;
Method : TMethod;
begin
if Not Assigned(TempForm) then
Exit;
if TempForm.Name = ControlName then
TargetControl := TempForm
else
TargetControl := TempForm.FindChildControl(ControlName);
if Assigned(TargetControl) then
begin
Method.Code := MethodAddr;
Method.Data := TargetControl;
SetMethodProp(TargetControl, EventName, Method);
end;
end;
So that I can poke subroutines into the various controls as I deserialize them, The problem is I need to add events as a list of parameters (not to a control). e.g.
SetUpEvents(EventHandler1:TNotifyEvent;EventHandler2:TNotifyEvent);
Where EventHandler1 and EventHandler2 are defined somewhere in code as
Procedure EventHandler1(Sender:TNotifyEvent);
begin
// Do something
end;
These are not methods but stand alone subroutines.
When I'm assigning these to objects the subroutine doesn't need to be part of an object as the AddMethod procedure handles it with a call like
MyDeserializerInstance.AddMethod('Button1','OnClick',#EventHandler1);
This works for standard event handlers, such as Button1.OnClick but not if I want to do
Procedure SetUpButton1Click(Method: TNotifyEvent)
begin
TButton(MyDeserializerInstance.TempForm.FindChildControl('Button1')).OnClick = Method;
end;
The problem is I can't pass the subroutine as a method to the example Set Up Procedure.
The form being created isn't declared in an interface and is entirely defined by the file it is read from as well as a few stand alone routines in code.
So I suppose the question is how do turn a subroutine into a method at run time (after creating the object it is supposed to be part of), and if I can't do that how do I pass the subroutines in code as parameters in another method?
So far I've tried casting a TMethod as the correct event type and filling in the .Data as the TempForm. It called the correct method but it scrambled the parameters.
Delphi version is 2007
Non-static class methods have a hidden Self input parameter that is filled in when the method is called. That is what the TMethod.Data field corresponds to. In order to use a standalone procedure as a handler for an event that expects a class method, the procedure must have an extra parameter defined to represent the Self parameter so the value of TMethod.Data has somewhere to go, ie:
procedure Button1ClickHandler(Self: Pointer; Sender: TObject);
begin
// Do something
end;
MyDeserializerInstance.AddMethod('Button1', 'OnClick', #Button1ClickHandler);
Your AddMethod() implementation is assigning the TargetControl as the TMethod.Data value, so the Self and Sender parameters above will end up pointing at the same object at runtime, but that is OK.
Without the explicit Self parameter defined, that explains why your parameters are getting "scrambled" when the procedure called at runtime. The hidden Self value is being assigned to the Sender parameter, and the real Sender value is being ignored.
I'm sure someone will correct me if I'm wrong but I don't believe there is a way to create a type definition at runtime in native Delphi. Delphi's RTTI just doesn't handle this yet.
The two scenarios that come to mind for object serialization are persistence and IPC. (There may be more that I haven't thought of).
Delphi's DFM serialization would be an example of persistence. If you look at a dfm you'll notice it isn't defining methods at all. It's simply assigning event handlers to properties expecting an event handler. Both the handlers and the properties are defined at design time using normal type definitions.
If your intent is IPC(whether on the same machine or a remote one) there are already existing frameworks for accomplishing this. (RemObjects comes to mind)
You don't "make a method" at run time. That would amount to compiling new code. The methods that you assign to various event properties need to already exist.
Furthermore, you can't "add events." The object you're deserializing already has events. You defined them when you wrote the class declaration in your Delphi code. You can't add new event properties to a class after it's been compiled.
It appears that what you're really saying is that you have a standalone procedure that you happen to have named Method1, and you want to pass it as a TNotifyEvent parameter when you call SetUpMethods.
That's the wrong way to go. That Method1 procedure isn't a method, despite its name, so you mustn't use it where a method is required. Change that declaration so it belongs to a class, and then it will be a method.
If you don't want to have to instantiate the class that the method belongs to, that's fine — you can declare it as a class method instead:
class procedure TSomeClass.Method1(Sender: TNotifyEvent);
I encourage you to change the declaration of AddMethod so that the last parameter is of type TMethod. Then you're sure to have both the code and data portions of the method pointer. Right now, you're assigning the data portion based on the object whose event property you're assigning, but as I mentioned in my comment, it's rare for that relationship to exist, especially now that the method belongs to an entirely unrelated class (TSomeClass in my example). The value of the TMethod.Data field becomes the Self value when the method gets called. It's your responsibility to ensure that the value you store in that field is of a compatible type for the class the code belongs to.