Skip to content

Gendarme.Rules.Interoperability.MarshalStringsInPInvokeDeclarationsRule(2.10)

Sebastien Pouliot edited this page Feb 9, 2011 · 3 revisions

MarshalStringsInPInvokeDeclarationsRule

Assembly: Gendarme.Rules.Interoperability
Version: 2.10

Description

This rule will fire if a P/Invoke method has System.String or System.Text.StringBuilder arguments, and the DllImportAttribute does not specify the CharSet, and the string arguments are not decorated with MarshalAs. This is important because the defaults are different on the various platforms. On Mono the default is to always use utf-8. On .NET the default is to use the ANSI CharSet which is the native encoding and will typically be some variant of ASCII or something like Shift-JIS. On Compact .NET the default is utf-16.

Examples

Bad example:

[DllImport ("coredll")]
static extern int SHCreateShortcut (StringBuilder szShortcut, StringBuilder szTarget);

Good examples:

[DllImport ("coredll", CharSet = CharSet.Auto)]
static extern int SHCreateShortcut (StringBuilder szShortcut, StringBuilder szTarget);
[DllImport ("coredll")]
static extern int SHCreateShortcut ([MarshalAs (UnmanagedType.LPTStr)] StringBuilder szShortcut,
[MarshalAs (UnmanagedType.LPTStr)] StringBuilder szTarget);
Clone this wiki locally