RV.
RV.

Reputation: 2842

Access a C++ struct in C#

I am having a VC++ stucture like

struct VideoInputV20 {
   int m_nBrightness;
   int m_nSharpness;
   int m_nSaturation;
   int m_nContrast;
   int m_nInputState;
   CString m_sObjref;
};

Here in C# I'll receive this stucture in byte[]. Here I need to convert byte[] to stuct.

How can I achive this? Please provide sample code, if possible.

Upvotes: 2

Views: 1234

Answers (3)

nothrow
nothrow

Reputation: 16168

Badly. Ints are relatively easy to recover, but that CString's object serialization is platform and compiler dependent. Try converting this in C++ to some other representation.

Upvotes: 1

ParmesanCodice
ParmesanCodice

Reputation: 5035

Declare your struct in C#:

[StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)]  
struct VideoInputV20
{
    int m_nBrightness;
    int m_nSharpness;
    int m_nSaturation;
    int m_nContrast;
    int m_nInputState;
    [MarshalAs(UnmanagedType.LPWStr)]
    string m_sObjref;
}

Then the code to get it out of a byte[]

GCHandle handle = new GCHandle();
try
{
    // Pin the byte[]
    handle = GCHandle.Alloc(yourByteArray, GCHandleType.Pinned);
    IntPtr ptr = handle.AddrOfPinnedObject();

    // Marshal byte[] into struct instance
    VideoInputV20 myVideoInputV20 = (VideoInputV20 )Marshal.PtrToStructure(ptr, typeof(VideoInputV20 ));
}
// Clean up memory
finally
{
    if (handle.IsAllocated) handle.Free();
}

Upvotes: 4

Tror
Tror

Reputation: 452


byte[] data = GetData();
int structSize = Marshal.SizeOf(VideoInputV20);

if(structSize <= data.Length)
{
   IntPtr buffer = Marshal.AllocHGlobal(structSize);
   Marshal.Copy(data, 0, buffer, structSize);
   VideoInputV20 vi = (VideoInputV20)Marshal.PtrToStructure(buffer, VideoInputV20);
   Marshal.FreeHGlobal( buffer );
}

Upvotes: 0

Related Questions