使用FastMM4,如何注册泄漏的字符串? [英] Using FastMM4, how to register leaked string?

查看:85
本文介绍了使用FastMM4,如何注册泄漏的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用FastMM4,可以轻松注册泄漏的指针,但不能注册泄漏的字符串。显然,应用于字符串的 @ 运算符并没有真正为我们提供整个字符串, PChar(string)也没有;

With FastMM4 one can easily register a leaked pointer, but not a leaked string. Apparently the @ operator applied to a string is not really giving us the whole string, nor is PChar(string); What can I use to nicely register a leaked string?

现在我可以使用它来很好地注册泄漏的字符串了吗?

For now I found this works:

FastMM4.RegisterExpectedMemoryLeak(Pointer(NativeInt(PChar(StringVariable))-12));

但这取决于幻数 12 ,并且这取决于版本,并且代码实际上并没有表达正在发生的事情。我希望某个地方有一个RTL函数,该函数可以接收字符串并返回指向该字符串基的指针,或者是一些我忽略的 FastMM4 方法。

But it relies on the magic number 12, and that's version-dependent, and the code really doesn't express what's going on. I hope there's a RTL function somewhere that takes a string and gives back a pointer to the "base" of the string, or some FastMM4 method that I overlooked.

我可以在这样的过程中包装那种丑陋的表情野兽,但我仍然发现它很hacky:

I can pack that ugly beast of expression in a procedure like this, but I still find it hacky:

procedure RegisterExpectedStringLeak(const s:string);
begin
  {$IFDEF VER210}
  FastMM4.RegisterExpectedMemoryLeak(Pointer(NativeInt(PChar(s))-12));
  {$ELSE}
  {$MESSAGE Fatal 'This only works on Delphi 2010'}
  {$ENDIF}
end;






这应该与问题无关。这就是我泄漏字符串的原因:

我正在使用缓存机制来存储应用程序生命周期内的某些数据。我不打算释放那些对象,因为在应用程序的整个生命周期中我确实需要它们,并且在应用程序关闭时仅花费很少的时间进行适当的终结。这些对象包含一些字符串字段,因此显然这些字符串是泄漏的。

I'm using a caching mechanism to store certain pieces of data for the life of the application. I do not intend to free those objects, because I do need them for the life of the application and going through proper finalization only waists time at application shutdown. Those objects contain some string fields, so obviously those strings are "leaked".

推荐答案

我能想到的最接近的是:

The closest I can think of would be:

function RegisterExpectedStringLeak(const S: string): Boolean;
  type
    {Have to redeclare StrRec here, because it is not in the interface section of system.pas}
    PStrRec = ^StrRec;
    StrRec = packed record
      {$ifdef CONDITIONALEXPRESSIONS}
      {$if RTLVersion >= 20}
      codePage: Word;
      elemSize: Word;
      {$ifend}
      {$endif}
      refCnt: Longint;
      length: Longint;
    end;
begin
  Result := RegisterExpectedMemoryLeak(Pointer(NativeInt(PChar(S)) - SizeOf(StrRec)));
end;

复制了 StrRec 的重新声明来自Delphi XE的 getmem.inc (FastMM4)-我只添加了 {$ ifdef CONDITIONALEXPRESSIONS} 。我认为它也应该与旧版本的Delphi向后兼容。

The re-declaration of StrRec is copied from Delphi XE's getmem.inc (FastMM4) - I only added the {$ifdef CONDITIONALEXPRESSIONS}. I think it should be backwards-compatible with older versions of Delp too.

这篇关于使用FastMM4,如何注册泄漏的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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