4

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

1 回答 1

4

这很可能是这个错误的发生Bogus CA5122 关于 P/Invoke 声明的警告不应该是安全关键的,这在 NET4 之前的程序集中表现出来。

于 2012-11-22T16:58:32.953 回答