I am writing my first C# application, but as luck would have it I must use void pointers (working with a DLL which returns handles). From what I read there are a few options:
Unsafe code, for example see http://www.c-sharpcorner.com/UploadFile/gregory_popek/WritingUnsafeCode11102005040251AM/WritingUnsafeCode.aspx
In the C# program writing in my function declerations IntPtr instead of void*. e.g.: public static extern char SupportsWhatever(IntPtr h);
Using ref, e.g.: public static extern char SupportsWhatever(ref h);
It should also be noted that I need to marshal information back and forth between the DLL and C# application.
The unsafe option was the first that popped up on Google, but for some reason writing the keyword unsafe before all my functions just doesn't feel right.
Any recommendations?
Typically, for marshaling situations, using IntPtr would be the preferred approach here. It is allowed in safe code, and makes it very clear that your intention is marshaling a pointer back and forth.
This is how much of the BCL represents handles. For example, you can construct a Cursor from an IntPtr representing the native handle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With