Accessing Protected C++ Methods using C++/CLR Wrappers

Amernauth 41 Reputation points
2021-02-22T22:43:52.333+00:00

Hello,

Is there a syntax used in C++/CLI to access protected C++ methods from a C# application?

What I have currently in my MFC header file:

class CMFCApplication1Doc : public CDocument
{
protected: // create from serialization only
CMFCApplication1Doc() noexcept;
DECLARE_DYNCREATE(CMFCApplication1Doc)

// Attributes
public:

// Operations
public:
int OnTest();

// Overrides
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);

// Implementation
public:
virtual ~CMFCApplication1Doc();

protected:
int TestFunction();

};

And in my Wrapper.cpp

int CSharpMFCWrapper::CSharpMFCWrapperClass::Test()
{
pCC->TestFunction();

   return 0;

}

Accessing public functions pose no problems. Just the protected ones.

The Test() is declared in my Wrapper.h file and the pCC pointer is pointing to the protected C++ method.

I'm trying to not alter the underlying C++ code I am referencing hence the question.

Developer technologies C++
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jeanine Zhang-MSFT 11,356 Reputation points Microsoft External Staff
    2021-02-23T03:12:34.037+00:00

    Hi,

    For subclasses, protected members are accessible. As far as I'm concerned you could access protected members through subclasses.

    You could create a new class that derives from your existing unmanaged class, and re-exposes the protected members (TestFunction) as public. Then create a managed class to wrap your newly-derived class, and have it expose those originally-protected members as protected in the managed type hierarchy.

    Best Regards,

    Jeanine


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.