0

When I try to call a extern method from a non-main thread, I get COM CoInitialize error from the DLL written in C++ thread.

Just for slight more details, I have define an alias to call the c++ method in my C# console project.

e.g. [DllImport("WRITTENINC++.dll", CharSet = CharSet.Ansi)] public static extern Int32 DOTHIS(string s1, string s2, ref double d1, ref double d2);

And I put [STAThread] on top of Program.Main method.

When I call the method in the main thread, I get the correct result. However, if I run the same lines of codes in a different thread (using System.Threading and thread.Start()), I get the error regarding COM initialization.

Assuming that I cannot modify the DLL, the only way right now is to restrict my program to single-thread, which is not exciting.

Is there any solution to this?

Thanks!

GHB
  • 1
  • Add the exact error. Either your thread hasn't been initialized for COM or it's in the wrong apartment state. – Collin Dauphinee Feb 24 '15 at 21:45
  • It looks like that DLL uses some STA COM objects stored in global variables, a bad design which would force you calling `DOTHIS` on the same thread the DLL was initialized. – noseratio Feb 25 '15 at 00:22
  • It is a pretty gross bug for code in a DLL to call CoInitializeEx(). Especially asking for STA, a DLL can never make that promise. Do strongly consider not using this DLL, it probably isn't the only bug. Use code [like this](http://stackoverflow.com/a/21684059/17034) if you have to. – Hans Passant Feb 25 '15 at 09:39

1 Answers1

0

You have to call CoInitialize() on every thread where you use COM.

Joseph Willcoxson
  • 5,853
  • 1
  • 15
  • 29