10

https://msdn.microsoft.com/en-us/library/ms182161.aspx

Are the three classes described on this paged handled specially in the .NET Framework? (NativeMethods, SafeNativeMethods and UnsafeNativeMethods)

The reason I'm asking is I'm wondering if it is alright to create categories of NativeMethods classes. For example:

ComNativeMethods
User32NativeMethods
OleStorageNativeMethods
Ola M
  • 1,298
  • 3
  • 12
  • 27
Bryan
  • 2,775
  • 3
  • 28
  • 40

4 Answers4

8

It's a convention, not a requirement. If you reflect into the CLR and take a look at code in there, you'll often see P/Invoke code inside a NativeMethods class. I believe that FxCop will recommend putting your P/Invoke code in a class like this if it encounters it.

Pete OHanlon
  • 9,086
  • 2
  • 29
  • 28
3

It's just a convention that says you should place p/invoke methods in classes named *NativeMethods, but there is no technical constraint to prevent you from doing it your own way...

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
2

You can name your classes that way, but you will continue to get the code analysis warning CA1060. This warning indicates you are not following the convention. So to prevent this warning, you need to follow the convention when naming classes that have P/Invoke methods. If you want to categorize your P/Invoke methods, you can use namespaces. For example:

  • MyProject.Com.NativeMethods
  • MyProject.User32.NativeMethods
  • MyProject.OleStorage.NativeMethods
Ed Greaves
  • 4,807
  • 2
  • 22
  • 19
  • My interpretation of that link is that it is a convention, not that the runtime does anything different. The developer is responsible for putting the appropriate security attributes on the classes. For example: "NativeMethods - This class does not suppress stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute must not be applied to this class.)" – Mark Sowul Mar 02 '16 at 22:04
  • Also relevant: "These classes resemble the NativeMethods class; however, they are marked by using a special attribute called SuppressUnmanagedCodeSecurityAttribute. When this attribute is applied, the runtime does not perform a full stack walk to make sure that all callers have the UnmanagedCode permission. The runtime ordinarily checks for this permission at startup. ... However, you should use this attribute with great care. It can have serious security implications if it is implemented incorrectly.." – Mark Sowul Mar 02 '16 at 22:05
  • Thank you, I stand corrected. I've updated my answer. – Ed Greaves Mar 08 '16 at 22:45
1

They aren't handled specially by the CLR. It's simply recommended practice to have your P/Invokes inside a class named NativeMethods, SafeNativeMethods, or UnsafeNativeMethods.

You'll see this recommendation come into play if you run FxCop on your assemblies.

Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212