我见过的大部分代码都删除了终结器/析构函数中的指针:
public ref class CPPObjectWrapper
{
private:
CPPObject *_cppObject;
public:
CPPObjectWrapper()
{
_cppObject = new CPPObject();
}
CPPObjectWrapper(IntPtr ^ptr)
{
_cppObject = ptr->ToPointer();
}
~CPPObjectWrapper()
{
delete _cppObject;
_cppObject = 0;
}
!CPPObjectWrapper()
{
if (_cppObject != 0) delete _cppObject;
}
IntPtr^ GetPointer()
{
return gcnew IntPtr(_cppObject);
}
}
我的问题是,如果您包装的库执行以下操作,那么标准做法是什么:
void AddObject(CPPObject *cppObject)
{
// adds to a std::list
}
CPPObject* FindObject(/* criteria */)
{
// return reference to std::list item based on criteria
}
如果您的 c# 包装器这样做:
void AddObject(CPPObjectWrapper ^cppObject)
{
_internal->addObject(cppObject->GetPointer()->ToPointer());
}
CPPObjectWrapper^ FindObject(/* criteria */)
{
CPPObject *cppObject = _internal->findObject(/* criteria */);
return gcnew CPPObjectWrapper(gcnew IntPtr(cppObjet));
}
您遇到了内存问题,因为您的托管对象不应该删除指针,因为它在另一个对象中引用。返回时也是如此。您是否会简单地添加功能来告诉您的托管包装器在所有权转移时不要释放内存?