Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

delphi - Coinitialize has not been called error message

I am in the process of coding a console application that will create a firewall exception for my main app called Client.exe which uploads a few documents to our servers via FTP. I borrowed RRUZ code from Delphi 7 Windows Vista/7 Firewall Exception Network Locations my code looks like this:

program ChangeFW;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  ComObj;

var
  ExecName: string;

procedure AddExceptionToFirewall(Const Caption, Executable: String);
const
NET_FW_PROFILE2_DOMAIN  = 1;
NET_FW_PROFILE2_PRIVATE = 2;
NET_FW_PROFILE2_PUBLIC  = 4;

NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_ACTION_ALLOW    = 1;
var
  fwPolicy2      : OleVariant;
  RulesObject    : OleVariant;
  Profile        : Integer;
  NewRule        : OleVariant;
begin
  Profile             := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
  fwPolicy2           := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject         := fwPolicy2.Rules;
  NewRule             := CreateOleObject('HNetCfg.FWRule');
  NewRule.Name        := Caption;
  NewRule.Description := Caption;
  NewRule.Applicationname := Executable;
  NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
  NewRule.Enabled := TRUE;
  NewRule.Profiles := Profile;
  NewRule.Action := NET_FW_ACTION_ALLOW;
  RulesObject.Add(NewRule);
end;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    ExecName := GetCurrentDir + '' + 'Client.exe';
    AddExceptionToFirewall('SIP Inventory',ExecName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

When I execute the application I get the following error message: EOIeSysError: Coinitialize has not been called, ProgID: “HNetCfg.FwPolicy2” Any idea what I am doing wrong? Could you please point me in the right direction? Thank you so very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use COM - objects you will have to call CoInitialize with corresponding CoUninitialize.

In a usual application this will be already done.
As far as your program is a console program you will have to call it on your own.

.....
CoInitialize(nil);
try
  try
    { TODO -oUser -cConsole Main : Insert code here }
    ExecName := GetCurrentDir + '' + 'Client.exe';
    AddExceptionToFirewall('SIP Inventory',ExecName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
finally
  CoUninitialize;
end;
.....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...