Search code examples
delphidllindy-9

How to use IdFTP inside a DLL Delphi


When i inject the DLL, the ShowMessage work fine, but when i use IdFtp the remote Process crash.

library FTP_DLL;

uses
SysUtils,Classes,IdFTP,Dialogs;

{$R *.res}

var
IdFTP1: TIdFtp = nil;


begin
  IdFTP1.Host := 'My ftp server';
  IdFTP1.UserName := 'user';
  IdFTP1.Password := 'password';
  IdFTP1.Connect;
  IdFTP1.Put('C:\test.txt','test.txt',False);
  ShowMessage('ok') ;
end.

Thank you.


Solution

  • The most egregious problem here is that the code runs inside DllMain. There are severe restrictions over what you are allowed to do in DllMain. I'm quite sure that you are breaking the rules in multiple ways.

    You should move this code so that it is outside of DllMain. Either spawn a new thread to run the code, something that is allowed from DllMain, or execute the code in an exported function.

    After you sort that out, you will need to actually instantiate the object that you use. At the moment your initialize it like this:

    var
      IdFTP1: TIdFtp = nil;
    

    Trying to do anything with IdFTP1 is clearly going to fail. You are going to need to instantiate an object. I guess you are used to dropping components onto a design surface and having the framework instantiate everything for you. Well, that's not an option here and you will need to explicitly create the objects you use.

    Perhaps you might try this:

    library FTP_DLL;
    
    uses
      IdFTP;
    
    procedure Test; stdcall;
    var
      IdFTP: TIdFtp;
    begin
      IdFTP := TIdFtp.Create(nil); // pass nil as the owner, we take charge of lifetime
      try
        IdFTP.Host := 'My ftp server';
        IdFTP.UserName := 'user';
        IdFTP.Password := 'password';
        IdFTP.Connect;
        IdFTP.Put('C:\test.txt','test.txt',False);
      finally
        IdFTP.Free;
      end;
    end;
    
    exports
      Test;
    
    begin
    end.