I have various classes that wrap an IntPtr
. They don't store their own data (other than the pointer), but instead use properties and methods to expose the data at the pointer using an unmanaged library. It works well, but I've gotten to the point where I need to be able to refer to these wrapper objects from other wrapper objects. For example:
public class Node {
private IntPtr _ptr;
public Node Parent {
get { return new Node(UnmanagedApi.GetParent(_ptr)); }
}
internal Node(IntPtr ptr) {
_ptr = ptr;
}
}
Now, I can simply return a new Node(parentPtr)
(as above), but there is the potential for having tens of thousands of nodes. Wouldn't this be a bad idea, since multiple wrapper objects could end up referring to the same IntPtr
?
What can I do to fix this? I thought about using a static KeyedCollection
class that uses each IntPtr
as the key. So, instead of returning a new Node
each time, I can just look it up. But that would bring up threading issues, right?
Is there a better way?