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

后端 未结 1 1926
迷失自我
迷失自我 2021-02-15 11:26

I\'ve been googling around in circles trying to find an fully fledged example to this but to no avail.

I have a C++ API that presents a number of classes that contain pu

1条回答
  •  终归单人心
    2021-02-15 11:57

    Using the code in the link posted by Hans Passant as a base, the following is what I think you are looking for. It won't compile like this because I have written this example 'inline' - put all the method implementations in the .cpp file and you should then 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 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(); 
        }
    };
    

    0 讨论(0)
提交回复
热议问题