开发者

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.


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


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.



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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜