Delphi unit initialization not always called

泄露秘密 提交于 2019-11-29 06:37:16

Darian reminds me that 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.

Only found one reference in Quality Central, but there may be more. Includes LoadPackage referenced workaround.

http://qc.embarcadero.com/wc/qcmain.aspx?d=61968

Not every unit in a BPL will necessarily be initialized, under certain circumstances. If I had to guess, I'd say that this BPL is linked to your program at load time and not dynamically loaded later? Try putting the name of the unit you're using into the program's uses list in the DPR. That should fix it.

How are you loading the bpl? Are you leaving it to Delphi to do the loading or are you manually loading the bpl? If you are manually loading the bpl, are you loading it as a "straight" dll or are you using LoadPackage to load it as a delphi package? I would think that either letting the vcl load it (through the requires processing) or using LoadPackage is required for the initialization sections to be run by the vcl...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!