title: Where to call FreeLibrary for DLLs used by dynamic packages?
body: <p>I have a <a href="https://edn.embarcadero.com/article/27178" rel="nofollow noreferrer">dynamically loaded BPL package</a> which uses a third part library who loads a DLL.</p>
  
  <p>After calling <code>UnloadPackage</code> for my BPL package, the application still locks the DLL file.</p>
  
  <pre><code>var
    MyPackageHandle : THandle;
    MyPackageClass : TPersistentClass;
    MyPackageForm : TCustomForm;
  begin
    MyPackageHandle := LoadPackage('.\MyPackage.bpl');
    if(MyPackageHandle &lt;&gt; 0) then 
    begin
      try
        MyPackageClass := GetClass('TMyPackageForm');
        if(Assigned(MyPackageClass) then
        begin
          MyPackageForm := TComponentClass(MyPackageClass).Create(nil) as TCustomForm;
          MyPackageForm.ShowModal();
          MyPackageForm.Free();
        end;
      finally
        UnloadPackage(MyPackageHandle);
      end;
    end;
  end;
  </code></pre>
  
  <p>For testing, I'm using the <code>Windows.GetModuleHandle</code> function.</p>
  
  <p>I've tried calling <a href="https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-freelibrary" rel="nofollow noreferrer"><code>FreeLibrary</code></a> passing the handle of the DLL and then I'm able to delete the DLL file. I suspect that a <code>FreeLibrary</code> call is missing somewhere in my BPL package or in the third part BPL.</p>
  
  <p>In a condition like the one described above (A dynamically loaded BPL which statically links a third part BPL which uses a DLL), where should the <code>FreeLibrary</code> be executed?</p>