« MBS Xojo Plugins, ver… | Home | Xojo like properties … »

Inside Delegates

You may have used a delegate in Xojo before. Technically a delegate is an object encapsulating a function pointer and if needed a reference to the object reference for a non-global method. As delegates are objects, you can store delegates in a dictionary or array and reference them later by name or index.

Although delegates are objects and they point to a class definition for a "Delegate" class, there is no such class known to the Xojo compiler. You can't use isA with Delegate or extend Delegate via extends or a plugin class extension. The only way to detect if an object or variant is a delegate object is to use introspection and check the full name there:

Dim aDelegate As ADelegate = AddressOf someFunction
Dim i As Introspection.TypeInfo = Introspection.GetType(aDelegate)

When you create a delegate, Xojo allocates an object for you. If you pass in a global method, it just reference the function pointer. But for a method from an object, the object is also referenced. Such a reference may be weak if you use weakAddressOf operator in Xojo. There is no built-in way to get the weak status or the target object, but there are feedback cases and we may be able to do something via plugin.

If you assign the delegate to the Ptr, you get the internal function pointer. This pointer doesn't point to the object, but to the actual Xojo function to be called through the Invoke method. If you assign one delegate to another delegate, that will work as long as the parameters are the same for both types.

We'd love to see Xojo Inc. add some properties to the Delegate class like "Target as Object", where you can see the target object. For weak delegates, a weak property may be great to see the status. And of course the target should become nil if the weak reference got invalid. Currently we can only handle that with catching NilObjectException when invoking them and then set delegate to nil to clear it. More great properties may be the parameters as string as well as a the delegate name itself.

To mitigate the issue for us, we add three functions GetDelegateParametersMBS, GetDelegateTargetMBS and GetDelegateWeakMBS. All take a variant with a delegate. They check whether this may be a delegate and if those, return you the parameter string, the target object or the weak flag. They do work in current and older Xojo version on macOS, Windows and Linux as we see, but may break with a future Xojo update. For weak references, the target is nil when the reference is broken.

See also a few feedback cases worth to support:
20844: Show more delegate information in the debugger
23305: Let Delegates to have properties to retrieve its content
26060: Detect weak status of a weak delegate The biggest plugin in space...
29 06 20 - 10:39