[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class Comarea
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)]
public string status;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
public string operationName;
}
public static void StringToObject(string buffer, out Comarea comarea)
{
IntPtr pBuf = Marshal.StringToBSTR(buffer);
comarea = (Comarea)Marshal.PtrToStructure(pBuf, typeof(Comarea));
}
I can create object from single line of string but I can not do opposite of that.
How can I do that operation?
public static void ObjectToString(out string buffer, Comarea comarea)
{
???
}
It throws exception "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
int size = Marshal.SizeOf(comarea);
IntPtr pBuf = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(comarea, pBuf, false);
buffer = Marshal.PtrToStringBSTR(pBuf); //Error
That is how I solved my problem: I used char array and
Marshal.PtrToStringAuto(pBuf, size)It is so useful for IBM CICS communication(For Commarea)