简体   繁体   中英

C++ dynamic_cast with a C# com visible object

I have an old COM component in C++/ATL (Active Template Library) which uses a dynamic_cast to convert a COM interface into the C++ class which implementes the interface.

If the conversion is not possible, the dynamic_cast returns a NULL pointer.

I now have a new implementation of the same COM interface in a com-visible C# component.

When the dynamic_cast operator is applied to the COM object from C#, I would expect it to return NULL, but in fact it throws an exception (I have no idea what exception).

I can certainly wrap the dynamic_cast in a try/catch block, but is this normal behavior?

I think MGetz has given the correct information.

dynamic_cast relies on Run-Time Type Information (RTTI). This implies that it can only work in a homogeneous project where all code is compiled with the same compiler (using the same compiler options).

If I disable RTTI, I get

warning C4541: 'dynamic_cast' used on polymorphic type 'IMyInterfaceName' with /GR-; 
unpredictable behavior may result

Effectively, we can extend this to say that dynamic_cast on the COM callable wrapper (CCW) of a C# object also results in unpredictable behavior.

Better to avoid dynamic_cast altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM