Search code examples
c#pointersreferencewrapperintptr

How can I avoid creating new wrapper objects all over the place?


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?


Solution

  • The biggest problem I can see is who is responsible for deleting the objects referred to by the pointer?

    Reusing the same object is not necessarily a threading issue, although if you are responsible for calling delete on the unmanaged objects you'll need to implement some sort of reference counting in your objects.

    Using multiple objects with the same pointer might be easier if your objects are read-only. If they have state that can be changed then you'll need to understand the impact of making a change if multiple objects hold a pointer to that state.

    You might also want to look at C++/CLI (managed C++) to provide a layer between the C# and unmanaged library and do the hard work of translation/manipulation in there and provide a simpler API for the C# to work with.