Question

I ran Code Analysis on a utility I'm maintaining, and it advised me to change this:

private static extern int ReadMenu1File(string Menu1Path);

...to this:

private static extern int ReadMenu1File(UnmanagedType.LPWStr Menu1Path);

...with this verbiage: "Specify marshaling for P/Invoke string arguments To reduce security risk, marshal parameter 'Menu1Path' 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."

...but when I did, it says, "The type name 'LPWStr' does not exist in the type 'System.Runtime.InteropServices.UnmanagedType'" and "'System.Runtime.InteropServices.UnmanagedType.LPWStr' is a 'field' but is used like a 'type'"

Code completion is not helping (no suggestions after typing "UnmanagedType.") nor is there a context menu option to add a missing using.

Was it helpful?

Solution 2

I suspect you've misinterpreted the advice. I suspect it was actually suggesting:

private static extern int ReadMenu1File([MarshalAs(UnmanagedType.LPWStr)]
                                        string Menu1Path);

EDIT: This fits in with the advice:

or by explicitly marshaling the parameter as UnmanagedType.LPWStr

That's not the same as saying "Change the parameter type to UnmanagedType.LPWStr" - it's just telling you that's how you ought to marshal the parameter.

The other recommendations are to be set on the [DllImport] instead.

OTHER TIPS

Are you sure it didn't want you to decorate the parameter with the [MarshalAs(UnmanagedType.LPWStr)] attribute? For example:

private static extern int ReadMenu1File(
                            [MarshalAs(UnmanagedType.LPWStr)] string Menu1Path);

UnmanagedType is an enum, so you're trying to use one of its members as a type, which is why the compiler is complaining.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top