2

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.

1
  • I have no idea what you are asking... can you rephrase this? Commented Nov 6, 2009 at 12:39

3 Answers 3

4

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

what is GCHandle how i declare in .net2003
You need to add the System.Runtime.InteropServices namespace, it should then be available. It is part of the .NET framework 1.1
1

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.

Comments

0

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 );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.