如何从 Delphi 10.1 Berlin 中的类助手访问私有字段? [英] How to access a private field from a class helper in Delphi 10.1 Berlin?

查看:25
本文介绍了如何从 Delphi 10.1 Berlin 中的类助手访问私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Gabriel Corneanu 的 jpegex, jpeg.TJPEGImage 的类助手.阅读thisthis 我了解到,除了 Delphi Seattle,您无法再像 jpegex 那样访问私有字段确实(以下示例中的 FData).像大卫·赫弗南 (David Heffernan) 提议的那样使用 VMT 四处闲逛,这远远超出了我的范围.有没有更简单的方法来完成这项工作?

I would like to use Gabriel Corneanu's jpegex, a class helper for jpeg.TJPEGImage. Reading this and this I've learned that beyond Delphi Seattle you cannot access private fields anymore like jpegex does (FData in the example below). Poking around with the VMT like David Heffernan proposed is far beyond me. Is there any easier way to get this done?

   type
  // helper to access TJPEGData fields
  TJPEGDataHelper = class helper for TJPEGData
    function  Data: TCustomMemoryStream; inline;
    procedure SetData(D: TCustomMemoryStream);
    procedure SetSize(W,H: integer);
  end;

// TJPEGDataHelper
function TJPEGDataHelper.Data: TCustomMemoryStream;
begin
  Result := self.FData;
end;

推荐答案

当心!这是一个令人讨厌的黑客行为,当被黑客入侵的类的内部字段结构发生变化时,它可能会失败.

Beware! This is a nasty hack and can fail when the internal field structure of the hacked class changes.

type
  TJPEGDataHack = class(TSharedImage)
    FData: TCustomMemoryStream; // must be at the same relative location as in TJPEGData!
  end;

  // TJPEGDataHelper
function TJPEGDataHelper.Data: TCustomMemoryStream;
begin
  Result := TJPEGDataHack(self).FData;
end;

这仅在hack"类的父类与原始类的父类相同时才有效.因此,在这种情况下,TJPEGData 继承自 TSharedImage,hack"类也是如此.位置也需要匹配,所以如果列表中 FData 之前有一个字段,那么等效的字段应该位于hack"类中,即使它没有被使用.

This will only work if the parent class of the "hack" class is the same as the parent class of the original class. So, in this case, TJPEGData inherits from TSharedImage and so does the "hack" class. The positions also need to match up so if there was a field before FData in the list then an equivalent field should sit in the "hack" class, even if it's not used.

可以在此处找到有关其工作原理的完整说明:

A full description of how it works can be found here:

技巧 #5:访问私有字段

这篇关于如何从 Delphi 10.1 Berlin 中的类助手访问私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆