Delphi单元初始化不总是调用

前端之家收集整理的这篇文章主要介绍了Delphi单元初始化不总是调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在.bpl中有一个单位,我需要一个我写的新函数的stringlist.我想要使​​用stringlist来持久保存应用程序的生命周期,这样每个调用都可以建立在先前的调用发现之上.

所以它在全局范围内宣布,我在初始化部分初始化它,如下所示:

var
  ProductLookup : TStrings;  
...

function foo : boolean;
begin
  result := (ProductLookup.IndexOfName('bar') >=0); //blow up here. It's nil. Why?
end;
....

initialization
  ProductLookup := TStringList.Create;  // This should get run,but doesn't.

finalization
  FreeAndNil(ProductLookup);

end.

当我单元测试它,一切都很好.但是当它从主应用程序运行时,由于stringlist为零,所以我正在冒充访问冲突.所以现在我正在使用foo函数中的nil,并在必要时创建.但是我为什么初始化对我来说是不行的.我在初始化中放置了一个调试消息,当它作为BPL加载时,它不会运行,但如果我直接编译到dUnit exe中,则可以运行它.有任何想法吗? Delphi2005.

解决方法

达里安让我想起了 I’ve answered this before

If the operating system loads the BPL as part of loading the associated EXE,then not all the initialization sections will get called. Instead,only the sections from the units that are explicitly used by something else in the program get called.

If the code in the initialization section registers a class,and then you only refer to that class indirectly,say by looking for it by name in a list,then the unit’s initialization section might not get called. Adding that unit to any “uses” clause in your program should solve that problem.

To work around this problem,you can initialize the package’s units yourself by calling the 07001 function,in the SysUtils unit. It requires a module handle,which you can get by calling the 07002 API function. That function will only call the initialization sections of the units that haven’t already been initialized. That’s my observation,anyway.

If you call InitializePackage,then you should also call FinalizePackage. When your package gets unloaded,the finalization sections will get called for all the units that were automatically initialized.

If the OS does not automatically load your package,then you are loading it with the LoadPackage function. It initializes all the package’s units for you,so you don’t need to call InitializePackage yourself. Likewise,UnloadPackage will finalize everything for you.

原文链接:https://www.f2er.com/delphi/101570.html

猜你在找的Delphi相关文章