[fpc-pascal] Assigning Interface method to event handler

Sven Barth pascaldragon at googlemail.com
Wed May 25 14:28:00 CEST 2016


Am 25.05.2016 13:18 schrieb "Michael Van Canneyt" <michael at freepascal.org>:
>
>
>
> On Wed, 25 May 2016, Graeme Geldenhuys wrote:
>
>> Hi,
>>
>> Can I safely assign a method from an Interface reference to an event
>> handler. The code below works, but I'm not sure if it is safe to do so,
>> and allowed.
>>
>> ==================================
>>  TTestApp = class(TObject)
>>  private
>>    rpt: TFPReportReport;
>>    FReportFilter: IFPReportFilter; // can hold any export filter
>>  ...
>>
>> constructor TTestApp.Create;
>> begin
>>  rpt := TFPReportReport.Create(nil);
>>  rpt.Author := 'Graeme Geldenhuys';
>>  rpt.Title := 'FPReport Demo 4 - Frames and Fonts';
>>
>>  FReportFilter := TFPReportExportPDF.Create;  // PDF output
>>  //FReportFilter := TFPReportExportAggPas.Create;  // PNG output
>>  rpt.OnRenderReport := @FReportFilter.RenderReport;
>>  ...
>> end;
>
>
> I am not sure this is safe to do, since an event handler exists of 2
> pointers: data and method. As far as I know, an interface does not have a
> data pointer.

An method pointer is always automatically constructed by the compiler
consisting of the address of the method (here IFPReportFilter.RenderReport)
and the instance that method belongs to (in this case the FReportFilter),
so this will indeed work without problems.
The question however is whether it is guaranteed to keep working and isn't
merely the use of an implementation detail...

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20160525/f057bf94/attachment.html>


More information about the fpc-pascal mailing list