gpt4 book ai didi

Delphi 单元初始化并不总是被调用

转载 作者:行者123 更新时间:2023-12-03 14:40:48 28 4
gpt4 key购买 nike

我在 .bpl 中有一个单元,我需要一个用于我编写的新函数的字符串列表。我希望字符串列表在应用程序的整个生命周期中持续存在,以便每次调用都可以基于先前调用发现的内容进行构建。

因此它是在单元内全局声明的,我在初始化部分对其进行初始化,如下所示:

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.

当我对其进行单元测试时,一切都很好。但是当它从主应用程序运行时,我因访问冲突而崩溃,因为字符串列表为零。所以现在我求助于检查 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 InitializePackage function, in the SysUtils unit. It requires a module handle, which you can get by calling the GetModuleHandle 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.

关于Delphi 单元初始化并不总是被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618650/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com