Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and void pointers

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:

  1. Unsafe code, for example see http://www.c-sharpcorner.com/UploadFile/gregory_popek/WritingUnsafeCode11102005040251AM/WritingUnsafeCode.aspx

  2. In the C# program writing in my function declerations IntPtr instead of void*. e.g.: public static extern char SupportsWhatever(IntPtr h);

  3. 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?

like image 660
Digital Da Avatar asked Nov 20 '11 06:11

Digital Da


1 Answers

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.

like image 99
Reed Copsey Avatar answered Sep 23 '22 14:09

Reed Copsey