对于子类,可以访问受保护的成员。就我而言,您可以通过子类访问受保护的成员。
可以创建一个派生自现有非托管类的新类,并将受保护的成员 (TestFunction) 重新公开为公共成员。然后创建一个托管类来包装新派生的类,并让它在托管类型层次结构中将那些最初受保护的成员公开为受保护的成员。
如果回复有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。
你好
C++/CLI 中是否有用于从 C# 应用程序访问受保护的 C++ 方法的语法?
我目前在 MFC 头文件中的内容:
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;
}
访问公共功能不会造成任何问题。只是受保护的。
Test() 在我的 Wrapper.h 文件中声明,pCC 指针指向受保护的 C++ 方法。
我试图不更改我引用的底层 C++ 代码,因此提出了这个问题。
Note:此问题总结整理于: Accessing Protected C++ Methods using C++/CLR Wrappers
对于子类,可以访问受保护的成员。就我而言,您可以通过子类访问受保护的成员。
可以创建一个派生自现有非托管类的新类,并将受保护的成员 (TestFunction) 重新公开为公共成员。然后创建一个托管类来包装新派生的类,并让它在托管类型层次结构中将那些最初受保护的成员公开为受保护的成员。
如果回复有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。
In C++/CLI, you cannot directly access methods declared as protected in C++. This is because in C++, the protected keyword means that only the class itself and its derived classes can access these methods. C# classes are not derived classes of C++ classes, so they cannot directly access protected methods.
However, you can bypass this limitation by creating a derived class in C++/CLI. This derived class can access the protected method and provide a public method to indirectly access the protected method. Then, the C# code can access the protected method through this public method.
Here is an example:
// Assume CMFCApplication1Doc is your C++ class
class CMFCApplication1Doc {
protected:
int TestFunction();
};
// Create a derived class that can access TestFunction()
class CMFCApplication1DocDerived : public CMFCApplication1Doc {
public:
int TestFunctionPublic() {
return TestFunction();
}
};
// In your C++/CLI wrapper class, use the derived class instead of the original class
public ref class CSharpMFCWrapperClass {
private:
CMFCApplication1DocDerived* pCC;
public:
int Test() {
return pCC->TestFunctionPublic();
}
};
With this approach, the C# code can indirectly access the TestFunction()
method in C++ through the Test()
method.
Please note that this approach may break encapsulation and may have some unexpected side effects. Therefore, you should only use this approach if you fully understand its implications and possible consequences.