Reputation: 1247
I'm trying to use my C++ COM API (loaded inside a C++ application) from C# (as an addin) without any registration. I follow steps from this tutorials
So what I did is:
The first one is to create COM object inside the application main thread --> This is working
The second is to create COM object and casting COM object inside a separated STA thread --> This is working
The last case is to create COM object and casting COM object inside a separated MTA thread. And here I have a problem. I'm able to create an object but I'm not able to cast it. I received and exception like:
Unable to cast COM object of type 'System.__ComObject' to interface type 'API.MyComObjectX'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{DE35BA2A-0566-40D3-AF1D-AD79D1133B09}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))
So bellow, the code is the one I used for tested
/*
Manifest file loaded by my C++ application
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="ApiX.X" version="1.0.0.0"/>
<file name="ApiX.dll">
<comClass clsid="{76125B7A-E5FC-4362-93F8-3B912EB85D51}" threadingModel="Apartment"/> <!-- This define the MyComObjectX object -->
<typelib tlbid="{4714D4C0-5AA9-47F7-82FF-458B341E7052}" version="1.0" helpdir=""/>
</file>
<comInterfaceExternalProxyStub name="IMyComObjectX" iid="{DE35BA2A-0566-40D3-AF1D-AD79D1133B09}" proxyStubClsid32="{00020424-0000-0000-C000-000000000046}" tlbid="{4714D4C0-5AA9-47F7-82FF-458B341E7052}" baseInterface="{00000000-0000-0000-C000-000000000046}" /> <!-- interface which is based on IDispatch -->
</assembly>
*/
public void testComFreeRegistration(object myComObjectX)
{
try
{
MyComObjectX myComObjectX2 = new MyComObjectX();
MyComObjectX myComObjectX3 = (MyComObjectX)myComObjectX; // Throw the exception
MessageBox.Show("working");
}
catch (Exception e)
{
MessageBox.Show("fail");
e.ToString();
}
}
public void EntryPoint(object myComObjectX) // <-- Sent from my C++ application
{
// The STA test which are working
// var sta = new Thread(() => testComFreeRegistration(myComObjectX));
// sta.SetApartmentState(ApartmentState.STA);
// sta.Start();
// sta.Join();
var mta = new Thread(() => testComFreeRegistration(myComObjectX));
mta.SetApartmentState(ApartmentState.MTA);
mta.Start();
mta.Join();
}
Another strange behavior is if I uncomment my STA test. Both test will work !! So I don't know what happen. It seems I have something not proerly initialized.
Do you have any idea of what happen or what I should check ?
Why the STA <--> MTA mechanism seems to not load the comInterfaceExternalProxyStub
configuration ?
Thanks in advance for your help ;)
Upvotes: 2
Views: 238