Looking for an afternoon, finally found a solution!!!!
"VC Write DLL return value for char *,c# in how to define, I define a string, to error." ”
A netizen suggested he use unsafe, and later he said he solved, his code is as follows:
[StructLayout (LayoutKind.Sequential, Charset=charset.ansi)]
public struct KEYBUF
{
[MarshalAs (UnmanagedType.ByValTStr, sizeconst=256)]
public string C;
}
He said it would be solved, but then he asked, why do we have to use structure?
I do not know, I hope a friend can point out.
Later, I tried it:
[MarshalAs (UnmanagedType.LPArray)]
Public byte[] C;
But there were some problems, later, with the following:
[MarshalAs (UnmanagedType.LPArray)]
public byte[] c=new byte[256];
Got a buffer for byte and succeeded.
But there is a problem, with conver can not directly convert the number of characters to string, so instead of System.Text.Encoding to solve the problem.
The MSDN data found UnmanagedType enumeration description:
ByValTStr
An inline fixed-length character array that appears in the structure. The type of character used with ByValTStr is applied to the System.Runtime.InteropServices.StructLayoutAttribute of the containing structure. The System.Runtime.InteropServices.CharSet parameter is determined. You should always use the Marshalasattribute.sizeconst field to indicate the size of the array. The ByValTStr type of the. NET Framework behaves like a C-style, fixed-size string in a struct (for example, Char s[ 5]). The behavior in managed code differs from the behavior in Microsoft Visual Basic 6.0, which is not null-terminated (for example, MyString as String * 5).
LPArray
A pointer to the first element of the C-style array. When marshaling from managed to unmanaged, the length of the array is determined by the length of the managed array. When marshaling from unmanaged to managed, the length of the array is determined based on the Marshalasattribute.sizeconst and Marshalasattribute.sizeparamindex fields, and when the string type needs to be distinguished, It can also be followed by the unmanaged type of the elements in the array.
This means that the BYVALSTR is only suitable for fixed-length strings, and LPArray is used for indefinite lengths.
See the foreign useful stringbulider solution, is a string to char * mapping, has not tried to do, can see here
Just encountered a problem with char* on the use of external DLL functions in C #.