Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the proper way to work with LateBinding in Delphi?

actually i am using late-binding in delphi, and i need to know wich is the proper way to work with it.

My principal concern is about how I handle the memory used by these objects, I must free the memory?

check this sample code

var
  chEaten: Integer;
  BindCtx: IBindCtx;
  Moniker: IMoniker;
 MyObject:: IDispatch;
begin
try  
  OleCheck(CreateBindCtx(0, bindCtx));
  OleCheck(MkParseDisplayName(BindCtx, StringToOleStr('oleobject.class'), chEaten, Moniker));
  OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, MyObject));

  MyObject.Metod1();
  MyObject.Metod2();
 finally
 MyObject:=nil,// is  this necesary?
 end;

end;

would be helpful if someone explain briefly how is handled the memory in this type of objects.

thanks in advance.

like image 477
Salvador Avatar asked Aug 31 '25 17:08

Salvador


2 Answers

COM Interface objects in Delphi are automatically managed by the compiler. It inserts hidden calls to AddRef and Release at the appropriate places, and your interfaces will automatically have their Release methods called when they go out of scope. So no, you don't have to nil out the reference.

like image 189
Mason Wheeler Avatar answered Sep 02 '25 12:09

Mason Wheeler


Like Mason said, the memory for the interfaces is managed by the compiler for you. However, StringToOleStr() returns an allocated BSTR that needs to be freed manually with SysFreeString(). You should use the WideString type instead, which manages the memory for you, eg:

OleCheck(MkParseDisplayName(BindCtx, PWideChar(WideString('oleobject.class')), chEaten, Moniker)); 

Or:

var
  w: WideString;

w := 'oleobject.class';
OleCheck(MkParseDisplayName(BindCtx, PWideChar(w), chEaten, Moniker)); 
like image 35
Remy Lebeau Avatar answered Sep 02 '25 11:09

Remy Lebeau