加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi单元初始化不总是调用

发布时间:2020-12-15 04:24:49 所属栏目:大数据 来源:网络整理
导读:我在.bpl中有一个单位,我需要一个我写的新函数的stringlist.我想要使??用stringlist来持久保存应用程序的生命周期,这样每个调用都可以建立在先前的调用发现之上. 所以它在全局范围内宣布,我在初始化部分初始化它,如下所示: var ProductLookup : TStrings; .
我在.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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读