How to get the main thread of a console app to be MTA?

2

With Delphi, how can I create a (Windows) console application that has a main thread that is initialized as COINIT_MULTITHREADED?

If I call CoInitializeEx(nil, COINIT_MULTITHREADED) in the very first statement, I get a HRESULT 0x80010106 (Cannot change thread mode after it is set), so obviously some previously running code already called CoInitialize/Ex.

How can I get the main thread to be COINIT_MULTITHREADED?

delphi
com
apartments
apartment-state
asked on Stack Overflow Aug 2, 2019 by Martin

1 Answer

5

One of the units included in your program as a result of your uses clause has already initialized COM in its unit initialization section.

You need to identify that unit, and remove it from your program.

Consider this program:

{$APPTYPE CONSOLE}

uses
  ActiveX,
  ComObj;

begin
  Writeln(CoInitializeEx(nil, COINIT_MULTITHREADED));
end.

The output is 0 which demonstrates that an empty console application does not initialize COM.

answered on Stack Overflow Aug 2, 2019 by David Heffernan

User contributions licensed under CC BY-SA 3.0