CA2101 Warning when making extern calls

陌路散爱 提交于 2019-12-19 09:08:22

问题


I'm using the WinPcap libraries and have set up all my native method calls. Upon building I get the CA2101: Specify marshaling for P/Invoke string arguments Code Analysis warning. My extern function is defined like this:

[DllImport("wpcap", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
internal static extern int pcap_compile(IntPtr /* pcap_t* */ adaptHandle,
                                        IntPtr /*bpf_program **/fp,
                                        string /*char * */str,
                                        int optimize,
                                        uint netmask);

If I change the CharSet to CharSet.Unicode, I resolve the Code Analysis warning but my function no longer works. How can I resolve the warning and keep my code working?


回答1:


This warning occurs because truncating Unicode text to an ASCII string can cause security issues.

If you cannot use Unicode strings, set BestFitMapping = false, ThrowOnUnmappableChar = true on the attribute to prevent this security issue. For more information, see the documentation.



来源:https://stackoverflow.com/questions/13369883/ca2101-warning-when-making-extern-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!