1

Can I call a method which is placed in main application from dll code?

Jacek Kwiecień
  • 12,397
  • 20
  • 85
  • 157
  • See this example: [How to implement a callback method within DLL (Delphi / TJVPluginManager + TJvPlugin)](http://stackoverflow.com/a/1839294/576719). – LU RD Mar 16 '12 at 11:49

1 Answers1

5

seems there is only one way to do it - create a callback object. in your application you have to declare interface, wich describes your method, for example:

IMyMethodInterface = interface(IInterface)
    procedure MyMethod(); stdcall;
end;

next you have to create class, wich implements this interface (and your method):

TMyMethodObject = class(TInterfacedObject, IMyMethodInterface)
  public
    procedure MyMethod(); stdcall;
end;

when you load DLL, you have to create TMyMethodObject instance and pass its IMyMethodInterface to dll; of course dll has to have corresponding method and export it (wich takes interface as parameter) SetMethodCallback wich stores interface reference:

vars:

var mmo : IMyMethodInterface;
    dllHandle : THandle;
    smc : procedure (mmi : IMyMethodInterface); stdcall;

code:

    mmo := TMyMethodObject.Create();

    dllHandle := LoadLibrary('mydll.dll');
    smc := GetProcAddress(dllHandle, 'SetMethodCallback');
    if assigned(smc) then
        smc(mmo);

now, you can use IMyMethodInterface reference in your dll to call method.

of course you can statically link dll and use it directly:

procedure SetMethodInteface(mmi : IMyMethodInterface); stdcall; external 'mydll.dll';

here is an DLL sample code:

library Project3;
// uses YourMethodIntf.pas
{$R *.res}

var AppMethod : IMyMethodInterface;

    procedure SetAppMethodCallback(mmi : IMyMethodInterface); stdcall;
    begin
        AppMethod := mmi;
    end;

    procedure AnotherDllMethod();
    begin
        //here you can use AppMethod.MyMethod();
    end;

exports
    SetAppMethodCallback name 'SetMethodcallback';

begin
end.

take into account that your mmo object (TMyMethodInterface) will not be destroyed until you set AppMethod in dll to nil (or FreeLibrary dll ), so be careful

teran
  • 3,214
  • 1
  • 21
  • 30