[fpc-pascal] Get TMethod from function reference

Sven Barth pascaldragon at googlemail.com
Thu Sep 15 20:50:56 CEST 2022


Am 15.09.2022 um 15:30 schrieb Hairy Pixels:
>
>> On Sep 15, 2022, at 12:28 PM, Sven Barth <pascaldragon at googlemail.com> wrote:
>>
>> As mentioned elsewhere function references are in fact interfaces. And you can't retrieve a method pointer to a interface function, cause relying on that would result in either memory leaks or premature release of the interface, because TMethod only contains a Pointer for the Data field that does not support managed types.
>>
>> You can get a reference to the raw interface by doing this however:
>>
>> === code begin ===
>>
>> var
>>    proc: reference to procedure;
>>    i: IUnknown;
>> begin
>>     i := IUnknown(PPointer(@proc)^);
>> end.
>>
>> === code end ===
>>
>> Though I don't know what you hope to achieve with this...
> Ok so what’s happening is I had a deferred dispatch library that used many different callback types and now I want to unify it using references. Problem is, with the old design I used “of object” types so I was able to get the target class and use it do to things like cancel all actions that were associated with a particular class.

Unless you inherit from a function reference as mentioned by Ondrej then 
all you would get is object instance the compiler constructs implicitely 
so it wouldn't be much use to you anyway.

> I don’t understand how memory loss could be in play. If the function reference is stored and not freed it should have the information needed to invoke a method and in theory you should be able to retrieve it anytime, providing the interface had a public method for this (which would be a nice extension to add). How is that not correct?

And that's the thing: you need to keep the function reference itself 
around. Or increase the reference count of the interface. In both cases 
you need to make sure that you clear it up correctly. Otherwise you'll 
have a memory leak. And if you don't do all that then the function 
reference will go out of scope and be released.

Regards,
Sven


More information about the fpc-pascal mailing list