Delegate
From REALbasicWiki
| Overall article skill | ✭ |
A delegate is a type that holds a reference to a method. Delegates were added to the REALbasic language in REALbasic 2007r4.
Contents |
[edit] Adding a Delegate Type To a Project
Delegate types are declared in modules. To create a new delegate type, open the code editor of a module. Then choose the menu item
Project ▶ Add ▶ Delegate . You should see an editor that looks like a method editor. You enter a name, parameter types, and a return type, and set the visibility.
As of REALbasic 2008 r3, delegate declarations can now be added to classes as well as modules.
[edit] Type Checking
Two delegates are considered to have the same type if their signatures (parameter types and return type) match. The name of the delegate type is not considered.
[edit] Calling a Delegate
All delegate types have a method, Invoke. This method has the same signature as the delegate. Call Invoke to execute the method.
[edit] Creating Delegates via AddressOf
You create a delegate from a REALbasic method -- global, shared, or object -- using AddressOf.
dim f as SomeDelegate = AddressOf obj.Method
The signatures of the method and the delegate must match, or a compile-time error will result.
[edit] Creating Delegates via New
A second way to create a delegate object is via the New operator. This allows you to create a delegate from a Ptr, and is used for calling external functions via pointer.
dim fp as Ptr = SomeFunctionThatReturnsAFunctionPointer
dim f as new YourDelegate(fp)
The parameter passed to the constructor cannot be nil; if it is, a NilObjectException will be raised.
if the signature of YourDelegate does not match that of the function, expect the worst.
[edit] Conversion to Ptr
Delegates can be converted to type Ptr by assignment.
dim p as Ptr = someDelegateRef
This gives you the raw function pointer; object method delegates lose the object information upon assignment.
[edit] External Function Callbacks
You can pass a delegate created from a shared method or module method to external functions. You declare the external function parameter as Ptr, and pass the delegate to it. You should not pass delegates created from object methods. The compiler will let you do it, and the result will most probably be a crash upon execution.
[edit] Delegates and Memory Management
An object method delegate keeps a reference to its object. Consider the following example.
dim c as new Class1
dim d as FilterDelegate = AddressOf c.Filter
c = nil
Even after c is set to nil, a reference to the Class1 object exists as long as the delegate reference exists, as the debugger shows. This provides a new means for creating reference cycles.
