开发者

How do I access late bound nested properties and methods?

I want to know what is the proper way to access a late bound property or method from Delphi when the property to access is nested inside another property. Let me explain.

Check this sample application to check if the firewall is active, the 3 functions declared uses the HNetCfg.FwMgr COM object and return the same value.

{$APPTYPE CONSOLE}

uses
  Variants,
  ActiveX,
  Comobj,
  SysUtils;

//in this function i don't use any "helper" property to hold the temp value of the properties.
function FirewallIsActive1 : Boolean;
var
  Firewall : OleVariant;
begin
  Firewall := CreateOleObject('HNetCfg.FwMgr'); 
  Result   := Firewall.LocalPolicy.CurrentProfile.FirewallEnabled;
end;


//here i hold the value of the LocalPolicy property 
function FirewallIsActive2 : Boolean;
var
  Firewall : OleVariant;
  Policy   : OleVariant;
begin
  Firewall := CreateOleObject('HNetCfg.FwMgr');
  Policy   := Firewall.LocalPolicy;
  Result   := Policy.CurrentProfile.FirewallEnabled;
end;


//Here i use  a  "helper" variable for each property
function FirewallIsActive3 : Boolean;
var
  Firewall : OleVariant;
  Policy   : OleVa开发者_运维知识库riant;
  Profile  : OleVariant;
begin
  Firewall := CreateOleObject('HNetCfg.FwMgr');
  Policy   := Firewall.LocalPolicy;
  Profile  := Policy.CurrentProfile;
  Result   := Profile.FirewallEnabled;
end;


var
  i : Integer;
begin
 try
    CoInitialize(nil);
    try
      Writeln(BoolToStr(FirewallIsActive1,True));
      Writeln(BoolToStr(FirewallIsActive2,True));
      Writeln(BoolToStr(FirewallIsActive3,True));
      Readln;
    finally
      CoUninitialize;
    end;
 except
    on E:Exception do
    begin
        Writeln(E.Classname, ':', E.Message);
        Readln;
    end;
  end;
end.

I ask this question because I want to know if the Delphi compiler is capable of generating the code to dispose the olevariants in any case of the 3 functions?


Delphi will not generate any additional variants and therfore will not have any problem to free them. Delphi will just traverse the IDispatch route to get the valuses in FirewallIsActive1.

If you only need one value I would prefer this. If you need several infos of a nested interface I would store this in a helper variant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜