I have the following c functions
opaque_struct* create() {}
void free(opaque_struct*) {}
Which I want to call using PInvoke:
[DllImport("test")]
public static extern IntPtr create ();
[DllImport("test")]
public static extern void free (IntPtr);
I guess this would work fine but I’m looking for a way to in the managed code explicitly state that “free” only takes IntPtr returned by “create” and avoid accidentally passing other IntPtr received from other functions.
The struct pointed at is opaque as far as all managed code is concerned.
It is not possible to extend IntPtr even If all I do is give it a new name, no extra properties.
Is there any way to make this typed IntPtr?
When dealing with unmanaged memory, there is always the possibility of an “accident” per definition.
That said, what you could do is wrap your
IntPtrin a class, just like Microsoft did with their SafeHandle class and associatedSafeFileHandle,SafePipeHandle…etc.You could create your own
SafeHandleclass (you can inherit fromSystem.Runtime.InteropServices.SafeHandle), and use it in your P/Invoke declarations:Another benefit of
SafeHandleis that it implementsIDisposableand thus allows the use of theusingstatement to ensure yourfree()method is always called:As you can see, it isn’t even needed to call
free()manually, as it’s done automatically when theSafeHandleis disposed.