2

I'm really sorry to have to ask this, but I clearly don't understand something fundamental to Delphi.

When you declare a variable of a class like TIdSSLIOHandlerSocketOpenSSL, what do you have to initiate it to? Clearly if it was a string or an integer then the requisite value would be a string on an integer, but in this case it is less obvious(to people as incapable as me). Not initiating it results in an access violation, and I understand why having found an article on it here at about.com, but that article doesn't explain what to initiate to.

Below is the code that gives the access violation because I haven't initiated the variable client (it's an application without a gui)

program New;

uses
  Windows, Messages, SysUtils, Variants, Classes,
  Sockets, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack,
  IdServerIOHandler, IdSSL, IdSSLOpenSSL;


function Handshake(target: string; port: integer) : string;
var client: TIdSSLIOHandlerSocketOpenSSL;
begin
client.Create();
client.Port := port;
client.Destination := target;
client.Destroy;
end;


begin

  Handshake('127.0.0.1',15);

end.

Apologies for my ignorance,

N

N. McA.
  • 4,796
  • 4
  • 35
  • 60

1 Answers1

6

You need to use the syntax TIdSSLIOHandlerSocketOpenSSL.Create to invoke a constructor and save the result to the instance variable:

function Handshake(target: string; port: integer) : string;
var
  client: TIdSSLIOHandlerSocketOpenSSL;
begin
  client := TIdSSLIOHandlerSocketOpenSSL.Create;
  try
    client.Port := port;
    client.Destination := target;
    Result := ...;//don't forget to assign the return value to something
  finally
    client.Free;
  end;
end;

Also use try/finally to protect the lifetime of the object in the face of exceptions. The finally block will always execute, providing that execution passes try.

And to destroy an object you should call Free rather than Destroy. This doesn't matter here, but is very important when you destroy objects inside another object's destructor. To learn more on the topic of Free I refer you (immodest I know) to another answer of mine.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490