【问题标题】:Inheritance between managed and unmanaged classes托管类和非托管类之间的继承
【发布时间】:2015-11-03 05:27:27
【问题描述】:

您好,我有一个关于混合 C++ 和 C# 项目中的继承的问题。所以我有一个 C++/CLI 层来做中间的事情。 在 C++ 中,我有 2 个结构:

public Class A : 
{
public :
 A(){*a = new int(); *a = 0;}
 void f1(){*a = 10};
 int geta(){return *a};
private :
 int *a;
}

public Class B : public A
{
public :
 B(){*b = new int(); *b = 0;}
 void f2(){*b = 5; *a = 10};
 int getb(){return *b};
 int getinheriteda(){return *a;};
private : 
 int *b
}

然后在 C++/CLI 中,我在其托管版本中有 2 个相同的类。每个人都拥有一个指向非托管 C++ 类的指针。

public ref Class ANet : 
{
public :
 ANet(){ un_a = new A();}
 ~ANet(){ this->!ANet();}
 !ANet(){ delete un_a;}
 void f1Net(){ un_a->f1();}
 int getanet(){return un_a->geta();}
private:
 A *un_a; //Pointer to the unmanaged A
}

版本 1:

public ref Class BNet : public Class ANet:
{
public :
 BNet(){ un_b= new B();}
 ~BNet(){ this->!BNet();}
 !BNet(){ delete un_b;}
 void f2Net(){ ((B*)un_a)->f2();}
 int getbnet(){return un_b->getb();}
 int getinheriteda(){return un_b->getinheriteda();};
private:
 B *un_b; //Pointer to the unmanaged B
}

版本 2:

public ref Class BNet : public Class ANet:
{
 BNet(){ un_a = new B();}
 ~BNet(){ this->!BNet();}
 !BNet(){ delete un_a;}
 void f2Net(){ ((B*)un_a)->f2();}
 int getbnet(){return((B*)un_a)->getb();}
 int getinheriteda(){return ((B*)un_a)->getinheriteda();};
private:
 //No pointer, use inherited un_a;
}

问题:

版本 1:如果我得到 B 的实例,那么我有两个指针(un_b 和继承的 un_a),所以每个指针都得到它的非托管类,导致不一致。

版本 2:如果我得到 B 的实例,那么我有一个指针,但创建了两次导致不一致

如何实现可以包装这 2 个非托管类的托管 C++/CLI 结构。有什么想法吗?

【问题讨论】:

    标签: .net pointers inheritance c++-cli mixed-mode


    【解决方案1】:

    C++ 的方式是在ANet 中有单独的构造函数,它接受非托管指针:

    public ref class ANet
    {
    ...
    protected:
        ANet(A* a) : un_a(a) { ... }
    ...
    
    public ref class BNet : public ANet
    {
    public:
       BNet() : ANet(new B()) { ... }
    ...
    

    在 .Net 中,您还可以在 ANet 构造函数中调用虚方法来创建非托管实例并在需要时覆盖它:

    public ref class ANet
    {
    public:
        ANet() { un_a = CreateUnmanagedInstance(); }
    ...
    protected:
       virtual A* CreateUnmanagedInstance() { return new A(); }
    
    public ref class BNet : public ANet
    {
    ...
    protected:
       virtual A* CreateUnmanagedInstance() override { return new B(); }
    ...
    

    但由于这种方法不适用于本机 C++ 类,因此可能会被认为过于棘手和有害。

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 2019-07-14
      • 2018-03-19
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多