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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch. That was way faster than I expected too!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.