- Your first example doesn't compile. You can't assign
char[]
tostring
. - The call to
PadRight
in the first example does nothing, because you passedvalue.Length
as the argument (obviously no padding is needed to make a string as long as it already is). - The
[MarshalAs]
attribute is ignored unless you are passing the instance to unmanaged code, and there is no indication that you are doing so. - The
UnmanagedType
enumeration does not have a memberByValStr
. It does have a memberByValTStr
.
My guess is you did not specify the correct character set, and the unmanaged code is expecting a single-byte encoding but receiving a 2-byte UTF-16 encoded string. According to the documentation of ByValTStr
:
Used for in-line, fixed-length character arrays that appear within a structure. The character type used with
ByValTStr
is determined by theSystem.Runtime.InteropServices.CharSet
argument of theSystem.Runtime.InteropServices.StructLayoutAttribute
applied to the containing structure.
So you probably forgot to add the following to the containing structure:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]