• Advertisement
Sign in to follow this  

C++/CLI Interop Cast Operator

This topic is 3005 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If i have the following native classes:
class A
{
};

class B : public A
{
};
and in order to use them in a C# application i have the following C++/CLI wrappers.
public ref class AWrapper
{
  private:
  A* m_pNativePointer;
};

public ref class BWrapper : AWrapper
{
};
... where I have essentially mirrored the derrivation of B from A. In my C# application, how can I determine that an instance of AWrapper is actually a BWrapper. I want to improve upon my current method in which BWrapper has a contructor that takes an AWrapper and casts the internal pointer to B*. If the internal pointer is not a pointer to derrived class B you end up with a managed BWrapper instance that has a NULL m_pNativePointer member. From the C# code you would need to call some kind of IsValid() member on the C++/CLI object to determine if the contained pointer is NULL or not. I am presently trying to get the C++/CLI cast operator to work, like this:
B^ operator() ( A^ Base)
{
	if ( Base == nullptr )
	{
		return nullptr;
        }

	B* pPossibleB( dynamic_cast<B*>( Base->GetInternalPointer() ) );

	if ( pPossibleB == NULL )
	{
		return nullptr;
	}

	return gcnew B( pPossibleB);
}
I also tried an operator declared with:
	static operator B^( A^ AInstance)
and the same implementation, based on this article. The above code compiles, but in the C# code when i do:
BWrapper MyB = (BWrapper)MyA;
... the operator i have provided is not called. I might be overcomplicating this, but the cause for me needing to do this is because the MyA object is always given to me as a AWrapper. Any ideas? [Edited by - Dave on December 4, 2009 6:16:51 AM]

Share this post


Link to post
Share on other sites
Advertisement

class A { ... };
class B : public A { ... };

public ref class AWrapper {
public:
AWrapper() : ptr(new A()) { }
internal:
A* ptr;
AWrapper(A* ptr) : ptr(ptr) {}
};

public ref class BWrapper : AWrapper {
BWrapper() : AWrapper(new B()) { }
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement