3

The VS code analyzer throws this warning:

CA2101 Specify marshaling for P/Invoke string arguments To reduce security risk, marshal parameter 'buffer' as Unicode, by setting DllImport.CharSet to CharSet.Unicode, or by explicitly marshaling the parameter as UnmanagedType.LPWStr. If you need to marshal this string as ANSI or system-dependent, specify MarshalAs explicitly, and set BestFitMapping=false; for added security, also set ThrowOnUnmappableChar=true. Reg2Bat CenteredMSGBox.vb 20

Here:

<DllImport("user32.dll")> _
Shared Function GetClassName(hWnd As IntPtr, buffer As System.Text.StringBuilder, buflen As Integer) As Integer
End Function

I need to use the ANSI encoding but I don't understand what I need to do, so how I need to marshall this?

4

1 回答 1

11

这是pinvoke.net的声明。

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(
    IntPtr hWnd, 
    StringBuilder lpClassName,
    int nMaxCount
);

如果您(无论出于何种原因)想要导入 ASCII 版本,那么它看起来像

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
static extern int GetClassNameA(
    IntPtr hWnd, 
    StringBuilder lpClassName,
    int nMaxCount
);

另一种选择是为单个参数指定编组行为,如

[DllImport("user32.dll", SetLastError = true)]
static extern int GetClassNameA(
    IntPtr hWnd, 
    [MarshalAs(UnmanagedType.LPStr)] StringBuilder lpClassName,
    int nMaxCount
);
于 2013-07-26T02:50:15.867 回答