I have a native C++ COM object implementing an interface called ILogger
. It uses the threading model "Both" and a free threaded marshaller is aggregated.
Using this from .NET all is well unless I use the .NET reference to an ILogger
from a different apartment. This leads to the dreaded Unable to cast COM object of type 'System.__ComObject' to interface type ...ILogger
exception.
I understand one is not meant to use COM objects from different apartments without marshaling, however, it does seem to work in other cases. In my instance for example there is an Application
object that does not use any custom marshaler. I can access it "just fine" from non-STA threads (it's created in the STA). Further, making my logger use NTA rather than MTA (and the default neutral apartment marshaler, so no stubs etc) no exceptions are thrown (that is not entirely accurate, this worked on my machine, however, not once deployed elsewhere).
My question is mainly why can I access objects such as Application
from different apartments but I am seeing failures with my free-threaded logger. If .NET marshals in the first instance, why not the second. Furthermore, is there a way to use my logger in another apartment in .NET without creating a new instance that attempts to keep apartment-affinity?
CoMarshal*
family of APIs to marshal your object between COM apartments, be it a COM or a .NET object. Refer to INFO: Descriptions and Workings of OLE Threading Models and follow every single rules it talks about. – noseratio