P/Invoke declarations should not be safe-critical

c#, code-analysis, interop, pinvoke

Solution

This is most likely an occurrence of this bug Bogus CA5122 warning about P/Invoke declarations should not be safe-critical, which manifests itself with pre-NET4 assemblies.

Problem

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 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); ```

Original source