编程语言
首页 > 编程语言> > c#-如何解决此“ P / Invoke声明应可移植”的问题?

c#-如何解决此“ P / Invoke声明应可移植”的问题?

作者:互联网

这段代码:

[DllImport("shell32", CharSet=CharSet.Unicode)]
private static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbFileInfo, uint flags);

导致以下代码分析问题:

CA1901 P/Invoke declarations should be portable

As it is declared in your code, the return type of P/Invoke
‘IconUtil.SHGetFileInfo(string, uint, out IconUtil.SHFILEINFO, uint,
uint)’ will be 4 bytes wide on 64-bit platforms. This is not correct,
as the actual native declaration of this API indicates it should be 8
bytes wide on 64-bit platforms. Consult the MSDN Platform SDK
documentation for help determining what data type should be used
instead of ‘int’.

我应该做些什么?我尝试过“咨询MSDN”,但是我不确定这个问题到底意味着什么.

我也在同一行得到这个:

CA1060 Move P/Invokes to NativeMethods class

Because it is a P/Invoke method, ‘IconUtil.SHGetFileInfo(string, uint,
out IconUtil.SHFILEINFO, uint, uint)’ should be defined in a class
named NativeMethods, SafeNativeMethods, or UnsafeNativeMethods.

解决方法:

警告所指的MSDN页面是本机函数SHGetFileInfo的文档.它的签名为:

DWORD_PTR SHGetFileInfo(
  __in     LPCTSTR pszPath,
  DWORD dwFileAttributes,
  __inout  SHFILEINFO *psfi,
  UINT cbFileInfo,
  UINT uFlags
);

因此,第一个警告是指DWORD_PTR是指针大小的无符号整数的事实.这意味着您应该使用UIntPtr.

下一跳是SHFILEINFO结构指示为__inout.这意味着您需要通过引用传递它.

因此,p / invoke声明应为:

[DllImport("shell32", CharSet=CharSet.Unicode)]
private static extern UIntPtr SHGetFileInfo(
    string pszPath, 
    uint dwFileAttributes, 
    ref SHFILEINFO psfi, 
    uint cbFileInfo, 
    uint flags
);

最终警告很容易解决.只需将p / invoke声明放在名为NativeMethods的类中.

标签:c,pinvoke
来源: https://codeday.me/bug/20191101/1983319.html