B
Born Bugler
What I'm actually talking about is, when you put the same class in different
assemblies, you get two different types. This is reasonable (if you would
call it) in most cases as it avoids possible misuse. However, what about if
I do want to consider classes with exactly the same definition in different
assemblies to be the same? I tried interpret_cast, but it works only for
trivial scenarios like below:
ref class ClassA
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassA" ); }
};
ref class ClassB
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassB" ); }
};
int main()
{
ClassA^ ca = gcnew ClassA();
ClassB^ cb = reinterpret_cast<ClassB^>(ca);
cb->DoSomething(); // OK, output "From ClassA"
}
However, if you make the scenario more complex by adding some base classes
to ClassA and ClassB, reinterpret_cast fails, as shown below:
interface class InfA
{
DoSomething();
};
interface class InfB
{
DoSomething();
};
ref class ClassA : public InfA
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassA" ); }
};
ref class ClassB : public InfB
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassB" ); }
};
int main()
{
InfA^ ca = gcnew ClassA();
InfB^ cb = reinterpret_cast<InfB^>(ca);
cb->DoSomething(); // Oh, an exception "Entry point not found" is thrown
here.
}
In standard C++, I don't think there will be any problem with the above
attempt. However, in C++/CLI, well, I'm waiting for your reply...
Born
assemblies, you get two different types. This is reasonable (if you would
call it) in most cases as it avoids possible misuse. However, what about if
I do want to consider classes with exactly the same definition in different
assemblies to be the same? I tried interpret_cast, but it works only for
trivial scenarios like below:
ref class ClassA
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassA" ); }
};
ref class ClassB
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassB" ); }
};
int main()
{
ClassA^ ca = gcnew ClassA();
ClassB^ cb = reinterpret_cast<ClassB^>(ca);
cb->DoSomething(); // OK, output "From ClassA"
}
However, if you make the scenario more complex by adding some base classes
to ClassA and ClassB, reinterpret_cast fails, as shown below:
interface class InfA
{
DoSomething();
};
interface class InfB
{
DoSomething();
};
ref class ClassA : public InfA
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassA" ); }
};
ref class ClassB : public InfB
{
public:
virtual DoSomething(){ Console::WriteLine( "From ClassB" ); }
};
int main()
{
InfA^ ca = gcnew ClassA();
InfB^ cb = reinterpret_cast<InfB^>(ca);
cb->DoSomething(); // Oh, an exception "Entry point not found" is thrown
here.
}
In standard C++, I don't think there will be any problem with the above
attempt. However, in C++/CLI, well, I'm waiting for your reply...
Born