我正在尝试使用c ++ / cli包装非托管c ++代码。在C ++ / cli中,如果一个类具有所有纯虚拟函数,则必须将其声明为 abstract 。现在假设我在C ++中有以下代码:
class A{
public:
virtual ~A();
virtual void foo() = 0;
virtual void boo() = 0;
virtual void goo() = 0;
};
inline
A::~A()
{
}
class B
{
public:
B();
A* getA() const;
};
inline A* B::getA() const
{
//do something
return (A *) //of something;
}
如上所述,我可以毫无错误地返回 A * 。现在假设我将上面的代码包装如下:
public ref class manA abstract
{
public:
manA(A*);
virtual ~manA();
virtual void Foo() = 0;
virtual void Boo() = 0;
virtual void Goo() = 0;
private:
A* m_A;
};
inline
manA::~manA()
{
}
inline
manA::manA(A*)
{
//data marshalling to convert A* to manA
}
public ref class manB
{
public:
manB();
manA ^ GetA();
private:
B * m_B;
};
inline manB::manB()
{
m_B = new B;
}
inline manA ^ manB::GetA()
{
A *value = m_B->getA();
return gcnew manA(value);
}
现在,如果我执行上述操作,我会得到一个声明为'abstract'的类无法实例化错误。
有没有解决方案?
注意: A类定义了所有可能实现的接口。那么也许有一种方法可以定义manA,使其不是抽象的,因此可以实例化?
我找到了问题的解决方案:
从 manA 中删除构造函数并使用属性
public:
property A* UnmanagedObject
{
void set(A* unmanagedObjPtr)
{
//Or other data marshalling
m_A = (A *)(unmanagedObjPtr);
}
}
在manB里面做:
inline manA ^ manB::GetA()
{
A *value = m_B->getA();
manA ^ final;
final->UnmanagedObject = value;
return final;
}
答案 0 :(得分:1)
编写包装器并不意味着编写相同的本机类。不要将manA
作为抽象类,问题就不复存在了。
public ref class manA abstract
{
public:
manA(A*);
virtual ~manA();
virtual Foo() { m_A->foo(); }
virtual Boo() { m_A->boo(); }
virtual Goo() { m_A->goo(); }
//Also there should be an error like "Hey, What is the return type of those functions?"
//"virtual void Foo()" or "virtual int Foo()" or something else
private:
A* m_A;
};
答案 1 :(得分:0)
inline manB::manB()
{
m_B = new B;
}
我认为错误发生在这一行,因为B是从抽象类A派生而来的,并没有实现在类A中定义的纯函数。所以B也是一个抽象类。您永远不能创建抽象类B的实例。
答案 2 :(得分:0)
我认为问题是这个
return gcnew manA(value)
您正在实例化您声明为抽象类的manA ...
答案 3 :(得分:0)
利用泛型。
public ref class manB
{
public:
manB()
{
m_B = new B();
}
generic<T> where T : manA
manA ^ GetA()
{
A *value = m_B->getA();
T ^ final = Activator::CreateInstance<T>();
final->UnmanagedObject = value;
return final;
}
/* or
generic<T> where T : manA
T ^ GetA()
{
A *value = m_B->getA();
T ^ final = Activator::CreateInstance<T>(); //this requires T has a public default contructor.
final->UnmanagedObject = value;
return final;
}
*/
!manB()
{
delete m_B; //don't forget to release the native resource
}
private:
B * m_B;
};