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

自古美人都是妖i 提交于 2019-12-03 14:07:14

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<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(); 
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!