P/Invoke declarations should not be safe-critical

Posted by Bobrovsky on Stack Overflow See other posts from Stack Overflow or by Bobrovsky
Published on 2012-11-21T17:45:45Z Indexed on 2012/11/22 17:00 UTC
Read the original article Hit count: 215

Filed under:
|
|
|

My code imports following native methods:

  • DeleteObject, GetFontData and SelectObject from gdi32.dll
  • GetDC and ReleaseDC from user32.dll

I want to run the code in full trust and medium trust environments (I am fine with exceptions being thrown when these imported methods are indirectly used in medium trust environments).

When I run Code Analysis on the code I get warnings like:

CA5122
P/Invoke declarations should not be safe-critical.

P/Invoke method 'GdiFont.DeleteObject(IntPtr)' is marked safe-critical.
Since P/Invokes may only be called by critical code, this declaration should
either be marked as security critical, or have its annotation removed entirely
to avoid being misleading.

Could someone explain me (in layman terms) what does this warning really mean?

I tried putting these imports in static SafeNativeMethods class as internal static methods but this doesn't make the warnings go away.

I didn't try to put them in NativeMethods because after reading this article I am unsure that it's the right way to go because I don't want my code to be completely unusable in medium trust environments (I think this will be the consequence of moving imports to NativeMethods).

Honestly, I am pretty much confused about the real meaning of the warning and consequences of different options to suppressing it.

Could someone shed some light on all this?

EDIT:

My code target .NET 2.0 framework.

Assembly is marked with

[assembly: AllowPartiallyTrustedCallers]

Methods are declared like this:

[DllImport("gdi32")]
internal static extern int DeleteObject(HANDLE hObject);

© Stack Overflow or respective owner

Related posts about c#

Related posts about interop