Question

I have not found this scenario yet and am having difficulties finding a solution. I have a .Net app attempting to dynamically load a managed C++ dll to perform a task that should return an array of Data.Model.Viper objects. I also have that exact object defined in my .Net code. So when I call the managed C++ method I get back the data I want but when I try to use it I cannot call it a Data.Model.Viper list. Since it is dynamically loaded I cannot find a way to alias it and even if I do I am not sure I can convert the C++ Data.Model.Viper list into the .Net Data.Model.Viper list.

Anyone worked through something like this? Alternative ideas?

Was it helpful?

Solution

This cannot work, type identity in .NET prevents this. A strong DLL Hell countermeasure. Type identity of a type isn't just its namespace name and type name but also the assembly it came from. So you have two distinctive Data.Model.Viper types and they have no relationship with each other at all. Trying to cast just produces an InvalidCastException.

You must use a common type, one that's declared in a separate assembly that is referenced both by your main code and your C++/CLI assembly.

OTHER TIPS

Of course, Hans Passant is right. A class is not only defined by its namespace. You could use the adapter design pattern. In the .NET dll, you could create an adapter class to wrap both of the referenced classes. Then you could use the adapter class where you would use each one of the two previous classes. As an example, you would create the ViperAdapter class which would replace both the .NET and the C++ Viper classes.

Hope I helped!

So this is not the "right" answer and Hans Passant's answer is the better one. However, here is what I did because we are so close to release and it would take a lot more effort to get all components using the same model. I simply xml serialized the result I got from the managed C++ dll and then deserialized it as a Data.Model.Viper list. This took less than 1 second and the method will not be called heavily so I think the risk of performance issues should be minimal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top