Archived Forum Post

Index of archived forum posts

Question:

How to Free an IChilkatEmail2 Object in Delphi?

Apr 04 '13 at 10:03

I copied the code from the Send Simple email and I get a AV after the send, to wit:

var
mailman: TChilkatMailMan2;
success: Integer;
email: CHILKATMAILLib2_TLB.IChilkatEmail2;

...

// Create a new email object email := CoChilkatEmail2.Create;

// fills in the fields, etc.

rc := mailman.SendEmail(email As CHILKATMAILLib2_TLB.IChilkatEmail2);
if (rc <> 1) then
begin
  SiMain.LogError('Email send failed >> '+ mailman.LastErrorText);
end;

// works fine up to this point, email gets sent

try CoChilkatEmail2(email).Free; // Takes Exception except on E: Exception do begin ... end; end;

What's the proper method to free the object ? Does CloseSMTPConnection tidy everything up ? I used the cast because the IChilkatEmail2 doesn't have a free method.


Answer

(from http://docwiki.embarcadero.com/RADStudio/XE3/en/Interface_References)
"On the Win32 platform, interface references are typically managed through reference-counting, which depends on the _AddRef and _Release methods inherited from System/IInterface. Using the default implementation of reference counting, when an object is referenced only through interfaces, there is no need to destroy it manually; the object is automatically destroyed when the last reference to it goes out of scope."

A Chilkat interface reference would be a type that begins with an uppercase "I", such as IChilkatEmail2. You don't explicitly call _AddRef or _Release -- this is handled automatically be Delphi. In other words, you don't actually need to do anything in your application code to cleanup.

Additional Information:

When a Chilkat object is declared using “TChilkat*” such as TChilkatSFtp, and it is instantiated dynamically, then it must be explicitly freed (destroyed). See Cleaning up ActiveX Objects in Delphi — calling Free

Also see: Understanding Delphi COM (OLE) Interface References, AddRef and All That