@jamie, it has nothing to do with the variable scope of the form instance. Global variable will not help in any way, it can possibly (in some usage scenarios) even make things worse. Imagine you have called that function twice - the second call would overwrite the global reference set by the first call.
And by the way, as far as I know declaring the reference type locally in the method does not mean that the variable (object instance) will be on stack. The reference (the address of the object instance) will be, indeed, but not the object instance itself. Objects are always allocated on the heap. Someone will correct me if I am wrong, but I am pretty sure it is that way.
But, to the point. @vejrous, forms in DLLs are not so easy. The main problem here is that the form is not created by the Application.CreateForm method, but instantiated directly. Your application has no main form. So the form lifecycle is not as you could expect.
You can try to solve it by trying to instantiate the form with the Appication.CreateForm, but, to be honest, I have never tried this approach. Instead, you can try to use a bit different way that I have successfully used in the past for forms in DLLs.
It is using the
ShowModal method call instead of calling
Show. Try this approach. But I am not sure if it will work with Lazarus' implementation of application and forms lifecycle, for me it worked long time ago with Delphi. But at least give it a try, I believe that Lazarus is not so much different from Delphi.
procedure ShowForm; stdcall;
begin
with TForm1.Create(nil) do
try
ShowModal();
finally
Free();
end;
end;
Using
ShowModal instead would also resolve some other issues with your old original approach. Because there is an extra issue with using the method
Show that you have probably missed. If you expect that your function exported by DLL will not return until the form is alive, then you are wrong. In reality, the function will return immediately after calling the Show method. I mean that the execution will be outside of the exported function, but the form will be still alive. ShowModal uses its own message loop, so the function will need to wait until ShowModal call is finished and will only return after you have closed the modal form.