Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast a gcroot<Object^> to IMyInterface in C++.net?

I'm having to do some weird things with gcroot, but I get the following error on the dynamic cast line: "cannot use 'dynamic_cast' to convert from 'gcroot' to 'IMyInterface^'. In C#, you could easily cast a generic object to any interface. You may get a runtime error if the object doesn't implement the interface but it would compile.

gcroot<Object^> m_pDataObject;
IMyInterface obj = dynamic_cast<IMyInterface^>(m_pDataObject);
like image 769
bsh152s Avatar asked Oct 14 '10 19:10

bsh152s


2 Answers

This works (compiles) and should do what you want (module replacing IDisposable with your required interface):

gcroot<Object^> m_pDataObject;
Object^ obj = m_pDataObject;     // implicit conversion from gcroot<>
IDisposable^ intf = dynamic_cast<IDisposable^>(obj);    // or safe_cast<>
like image 87
Steve Townsend Avatar answered Nov 09 '22 16:11

Steve Townsend


gcroot<> is a smart pointer. You can cast to get the tracking handle out of it:

IMyInterface^ itf = dynamic_cast<IMyInterface^>((Object^)m_pDataObject);

Steve's answer is fine too btw.

like image 45
Hans Passant Avatar answered Nov 09 '22 15:11

Hans Passant