C ++ / CLI Inheriting from a native C ++ class with abstract methods and mapping it to C #

I spun around trying to find a complete example of this, but to no avail.

I have a C ++ API that presents several classes that contain pure virtual methods for the developer. What I'm trying to do is provide this C # interface through C ++ / CLI.

I managed to get the API compiled into the C ++ / CLI library, and I reached the key point since I am new to this.

I know that I need to create a wrapper to open an unmanaged C ++ / CLI class for a .net managed class, but I have not found a convincing example or discussion that shows how to do this with an abstract C ++ class.

Can someone point me in the right direction with a complete example, including a C # test application that shows the end and end of creating a wrapper for an abstract class. It seems like it is β€œOh, you just make X”, but I can’t understand what X is :). I saw a few examples here, but they are not very clear. About 3 years have passed since I started any C #.

Hope someone can help!

Sammich

+6
source share
1 answer

Using the code in the link posted by Hans Passant as a base, the following is what I think you're looking for. It will not compile this way because I wrote this example "inline" - put all the method implementations in a .cpp file, and you should be on the right track.

#pragma managed(push, off) #include "oldskool.h" #pragma comment(lib, "oldskool.lib") #pragma managed(pop) using namespace System; ref class Wrapper; // You need a predeclaration to use this class in the // constructor of OldSkoolRedirector. // Overrides virtual method is native class and passes to wrapper class class OldSkoolRedirector : public COldSkool { public: OldSkoolRedirector(Wrapper ^owner) : m_owner(owner) { } protected: virtual void sampleVirtualMethod() { // override your pure virtual method m_owner->callSampleVirtualMethod(); // body of method needs to be in .cpp file } private: gcroot<Wrapper^> m_owner; } public ref class Wrapper abstract { private: COldSkool* pUnmanaged; public: Wrapper() { pUnmanaged = new OldSkoolRedirector(this); } ~Wrapper() { this->!Wrapper(); } !Wrapper() { if (pUnmanaged) { delete pUnmanaged; pUnmanaged = 0; } } protected: virtual void sampleVirtualMethod() = 0; // Override this one in C# internal: void callSampleVirtualMethod(){ if (!pUnmanaged) throw gcnew ObjectDisposedException("Wrapper"); sampleVirtualMethod(); } }; 
+7
source

All Articles