Search code examples
c#cpinvokesafehandle

How to properly dispose of pinvoke/unmanaged code


I have code that needs to pinvoke a c dll, it seems to me that this code should implement idisposible since it touches unmanaged code. I could be wrong so please correct me if this is not true.

Reading up on the stuff it seems like I should use safehandles. Great. Except my dll doesn't return any handles, or intptr. So now what?

The signatures are mostly like the following:

HRESULT _XYZFN XYZNewTrip (Trip *pTripID); 

Argument Values:

pTripID: pointer to a 4 byte integer in which the new Trip handle will be placed

Can I some how shoehorn a safehandle in there? It seems like maybe the hard case from this article.


Solution

  • If it doesn't return an handle, then clearly you can't deallocate anything, so the IDisposable pattern would be useless.

    Only thing:

    pTripID: pointer to a 4 byte integer in which the new Trip handle will be placed
    

    These pTripID how will you deallocate them? Probably there is a

    void XYZFreeTrip(Trip tripID);
    

    In this case, you'll have to collect all the tripID you get and free them in the IDisposable.

    Now if Trip is an handle, then you have two options:

    • Your code is x86 only (because for example the PInvoke DLL is x86 only): sizeof(int) == sizeof(int*) == IntPtr.Size, so you can use the Wrapping Unmanaged Resources - Defining Level 0 Types for Pointers (The Intermediate Case)

    • Your code is x86 and x64: the Wrapping Unmanaged Resources - Defining Level 0 Types for Non-Pointer Data (The Hard Case) :-( (instead of ushort you have a int)