我有一个 VC++结构如
struct VideoInputV20 {
int m_nBrightness;
int m_nSharpness;
int m_nSaturation;
int m_nContrast;
int m_nInputState;
CString m_sObjref;
};
在 C# 中,我将在 byte[] 中接收该结构。这里我需要将byte[]转换为stuct。
我怎样才能实现这个目标?如果可能,请提供示例代码。
最佳答案
在 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;
}
然后是从 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();
}
关于c# - 在 C# 中访问 C++ 结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1687294/