P / Invoke statements should not be safe

My code imports the 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 the exceptions that occur when these imported methods are indirectly used in medium trust environments).

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

CA5122 P / Invoke ads should not be safe.

P / Invoke method ' GdiFont.DeleteObject(IntPtr) ' marked safe critical. Since P / Invokes can only be called with a critical code, this declaration should be marked as security critical or its annotation should be completely removed so as not to be misleading.

Can someone explain to me (in unprofessional terms) what this warning really means?

I tried putting these inserts in the static SafeNativeMethods class as internal static methods, but this does not make the warning go away.

I didnโ€™t try to put them in NativeMethods because after reading this article Iโ€™m not sure if this is the right way, because I donโ€™t want my code to be completely used in the medium of medium trust (I think this will be a consequence of moving the import to NativeMethods ).

Honestly, I'm pretty much confused by the real meaning of the warning and the consequences of the various options for suppressing it.

Can someone shed light on all this?

EDIT:

My target code is .NET 2.0 for my code.

Assembly marked

 [assembly: AllowPartiallyTrustedCallers] 

The methods are declared as follows:

 [DllImport("gdi32")] internal static extern int DeleteObject(HANDLE hObject); 
+4
source share
1 answer

This is most likely the occurrence of this error Warning that P / Invoke declarations from Bogus CA5122 should not be safe , which is pre-NET4 manifesting.

+4
source

Source: https://habr.com/ru/post/1447560/


All Articles