views:

82

answers:

2

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.

+3  A: 

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.

Mason Wheeler
Mason is correct, you don't have to nil the reference as it will be handled for you, but there is nothing wrong with doing it yourself. You also didn't nil the references to BindCtx or Moniker, but not to worry they should be released as soon as they fall out of scope.
skamradt
thanks very much Mason.
Salvador
A: 

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)); 
Remy Lebeau - TeamB