ATL to C# newbie question: object lifetime and references.

  • Thread starter Thread starter Ron Bullman
  • Start date Start date
Hello!

I want to control the lifetime of an object with C#.
I need an array of references to some object instances
that does not increment the reference counter of the objects.
I also want the object to remove its reference in the array
when it stops living.

With C#, i'm using an HashTable. My problem is that i don't know how
to assign an object reference to my hashtable without incrementing that
object reference counter.
I'm using a destructor in my object to remove the reference in the array.

With ATL, i do it like this:

std::map<int iToken, IMyObj*> ObjArray;

void CMyObj::FinalRelease()
{
//When the object stops living, erase the reference from the array.
ObjArray.erase(m_iToken);
}

HRESULT CObjectManager::GetObject(int iToken, IMyObj** ppObj)
{
CComPtr<IMyObj> pObject;

if(ObjArray.find(iToken) != ObjArray.end())
{
//Assignment to pObject increments the object reference counter.
pObject = ObjArray[iToken];
//Now we detach pObject in ppObj so it wont decrement the reference
counter
*ppObj = pObject.Detach();
}
else
{
//Creating pObject increments the object reference counter.
pObject.CoCreateInstance(CLSID_MyObj);
pObject->SetToken(iToken);
//Now we detach pObject in ppObj so it wont decrement the reference
counter
*ppObj = pObject.Detach();
//Assignment to ObjArray does not increment the object reference
counter.
ObjArray[iToken] = *ppObj;
}

return S_OK;
}

Any equivalents under C#? i want to learn! It's the only thing i could not
easily port from my C++ projects.
I need to know how to play with pointers with C#... or just an equivalent.


Louis-Pierre Beaumont
VER-MAC inc.
(e-mail address removed)
 
Oddly Outlook reported some server problems with the first post, but it
seems that it managed to send it anyway.
 
Back
Top