I have a bad behavior using GetProcAddress()
to calling a simple method inside a Delphi package.
I have a singleton object that has some methods, and when I call any singleton method inside a Delphi package using GetProcAddress()
, another instance of the singleton is being created. It is a big problem because there are a lot of methods that initialize services when the application is started.
Below is the simple example to share the problem:
Singleton Object
unit Unit2;
interface
uses System.Classes;
type
TMyClass = class(TPersistent)
strict private
class var FInstance : TMyClass;
private
class procedure ReleaseInstance();
public
constructor Create;
class function GetInstance(): TMyClass;
procedure TheMethod; -->>> Any method
end;
implementation
uses
Vcl.Dialogs;
{ TMyClass }
constructor TMyClass.Create;
begin
inherited Create;
end;
class function TMyClass.GetInstance: TMyClass;
begin
if not Assigned(Self.FInstance) then
Self.FInstance := TMyClass.Create;
Result := Self.FInstance;
end;
class procedure TMyClass.ReleaseInstance;
begin
if Assigned(Self.FInstance) then
Self.FInstance.Free;
end;
procedure TMyClass.TheMethod;
begin
ShowMessage('This is a method!');
end;
initialization
finalization
TMyClass.ReleaseInstance();
end.
Package Source Code
unit Unit3;
interface
uses Unit2;
procedure CustomMethod;
implementation
procedure CustomMethod;
begin
TMyClass.GetInstance.TheMethod; // ----->> callimg this method, another instance is initialized and lost the first settings
end;
exports
CustomMethod;
begin
end.
Main program code
procedure TForm1.Button1Click(Sender: TObject);
var
Hdl: HModule;
P: procedure;
begin
TMyClass.GetInstance.TheMethod; // -------->>> Initialize the singleton class normally
Hdl := LoadPackage('CustomPgk.bpl');
if Hdl <> 0 then
begin
@P := GetProcAddress(Hdl, 'CustomMethod'); //// ---->>> Call the custom method
if Assigned(P) then
P;
UnloadPackage(Hdl);
end;
end;
Can somebody help me, please?