所以它在全局范围内宣布,我在初始化部分初始化它,如下所示:
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.
解决方法
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 callFinalizePackage
. 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 callInitializePackage
yourself. Likewise,UnloadPackage
will finalize everything for you.