[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)
That is laid out as 6 adjacent 16 bit
wchar_t
character elements. So, right off the bat,is wrong. Beyond the fact that you leak a
BSTR
, your struct is not aBSTR
.You can implement it like this:
This is under the assumption that the six characters are the contained the the locations implied by the
Substring
calls.In the opposite direction you write:
Note that the struct definition must be wrong however
The marshaller always adds a null-terminator when using
ByValTStr
. So withSizeConst
of1
, status will always be marshaled as an empty string. Without actually seeing the unmanaged struct definition, I would not care to tell you how to fix this problem.