I am marshaling a native win 32 code to c#, because of mixture of value-type
members and reference-type
members in structures inside unions, I converted all my reference types to byte and addressed the size of them by using fielOffset
..now I want to access the value of one of these members and I do not know how to do it. the below codes are samples.
here is the c++ structure
typedef struct
{
int Port;
char SubsId[FIELD_SIZE_SUBS_ID+1];
char Options[FIELD_SIZE_OPTIONS+1];
} MMTPRcnxReq;
here is the c# equivalent
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct MMTPRcnxReq
{
[FieldOffset(0)]
public Int32 Port;
[FieldOffset(4)]
public byte SubsId;
[FieldOffset(4 + FIELD_SIZE_SUBS_ID + 1)]
public byte Options;
}
now I want to access the value of SubId which is actually an array of chars and for exmaple compare it to a string in my managed code, like below
if(mMTPRcnxReq.SubsId == "12345") // WRONG
how can I do that?
You are probably going to need to use unsafe
with fixed size buffers here.
unsafe struct MMTPRcnxReq
{
public int Port;
public fixed byte SubsId[FIELD_SIZE_SUBS_ID+1];
public fixed byte Options[FIELD_SIZE_OPTIONS+1];
}
The fixed size buffer is a value type, and that will allow you to put one of these structs inside a FieldOffset(0)
C# union.
Read the strings like this:
string SubsId;
unsafe
{
fixed (byte* ptr = req.SubsId)
{
// I presume that req.SubsId is null-terminated
SubsId = Marshal.PtrToStringAnsi((IntPtr)ptr);
}
}
You would probably write helper getter and setter methods of the struct, perhaps as properties, to manage the fixed size buffers.