0

I'm calling a COM DLL from a C# application. The DLL is an SDK for an application. When called from the application itself it works correctly, so I'm happy it's installed okay. I'm trying to call it from a C# console application though, and I'm getting the error below when I try to create an object defined in the DLL:

System.Runtime.InteropServices.COMException: CoInitialize has not been called. (Exception from HRESULT: 0x800401F0 (CO_E_NOTINITIALIZED))

How do I call CoInitialize from C#, and should I even do so? From what I've read, this should have been done automatically for a C# app. Also the code I'm running is from the vendor's sample file, so presumably should be valid as is.

Please note, the vendor is no longer available, so the obvious first step isn't an option! I'm really just looking for any general suggestions as to why a COM DLL would raise this error when called from a .Net language.

Kevin O'Donovan
  • 1,620
  • 1
  • 13
  • 24
  • 1
    That isn't really possible, the CLR *always* calls CoInitialize() for any managed thread. There is otherwise no real protection against code calling CoUninitialize(). Which a poorly written COM component might do when it detects the wrong apartment state. A major bug btw, but not entirely uncommon, COM apartments are notoriously poorly understood. You'll have to keep it happy, probably by putting the [STAThread] attribute on your Main() method. Wild guessing, use the telephone to obtain facts. – Hans Passant May 18 '15 at 10:56
  • Yes, that's why I was wondering if I should even try to call it - everything I read implied it was already effectively done. I've already tried using the STAThread attribute, unfortunately, but it didn't help. I'm note sure enough about the internals of COM to know what to try next. – Kevin O'Donovan May 18 '15 at 12:43
  • Everybody knows how to use a telephone, we can't help you dial the number. Be sure to have a small repro project available that demonstrates the problem. You didn't make any effort to show us one, whomever you call is going to insist on one or they'll quickly hang up the phone. – Hans Passant May 18 '15 at 12:44
  • This is effectively a dead product, and calling the vendor isn't an option (else I would have gone their first!) – Kevin O'Donovan May 18 '15 at 13:29
  • 1
    "When called from the application itself it works correctly" - what kind of application, WinForms? Perhaps, you need an STA thread with actual message loop to make this component work. Try `MessageLoopApartment` from [here](http://stackoverflow.com/a/22262976/1768303). – noseratio May 18 '15 at 23:28

1 Answers1

0

This is MSDN explanation, what it is and how to fix it. Essentially, due to some reason CoInitialize is not called in .NET entry point. In order to fix it, mark Windows Forms entry points with STAThread attribute, like this:

[STAThread]
public static void Main()
{
    // code
}
Anton K
  • 4,658
  • 2
  • 47
  • 60