Hi,
I have a COM object implemented in ATL. The CoClass implements two
interface. The default interface IInterface1 is a dispatch interface. The
non-default interface IInterface2 is an IUnknown interface.
Using dotnet interop I can create object instances, I can also be able to
cast the instance to IInterface2. dotnet interop sounds perfect.
However when I wrap this small piece of code in a separate thread, I get a
cast invalid exception. Let me descibe it in more detail using pseudo-code.
public static void TestInterop()
{
MyCom c = new MyCom();
IInterface1 i1 = (IInterface1)c;
IInterface2 i2 = (IInterface2)c;
}
when I directly call this function from the main thread, everything works
perfectly. However when I call the this function using the following code:
public static void Main()
{
Thread t = new Thread(new ThreadStart(TestInterop)));
t.Start();
t.Join();
}
I got the disgusting cast invalid exception. Although I run the code in a
thread, I create the object in the thread, I run the code in the same
thread. I never try to call the function from other threads. I just do not
understand it really matters to run it from the main thread or from a
separate thread.
To make sure it is not a problem from my COM component. I then program in
VC++. With CreateThread, it works OK. So anybody have the same experience?
Do I miss something here? Or it is interop bug?
Christian Fröschlin - 18 Sep 2003 10:43 GMT
> public static void Main()
> {
> Thread t = new Thread(new ThreadStart(TestInterop)));
> t.Start();
> t.Join();
> }
Does it help to set t.ApartmentState to STA before calling t.Start() ?