访问C++结构在C#
问题描述:
我有喜欢访问C++结构在C#
struct VideoInputV20 {
int m_nBrightness;
int m_nSharpness;
int m_nSaturation;
int m_nContrast;
int m_nInputState;
CString m_sObjref;
};
在这里,在C#中的VC++ stucture我会收到此stucture中的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();
}
+0
什么是GCHandle我如何声明.net2003 – 2009-11-06 14:01:01
+0
您需要添加System.Runtime.InteropServices命名空间,它应该可用。它是.NET Framework 1.1的一部分 – ParmesanCodice 2009-11-07 07:59:28
答
不好。 Ints相对容易恢复,但CString的对象序列化依赖于平台和编译器。尝试在C++中将其转换为其他表示形式。
答
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);
}
我不知道你问的......可你改说这个? – 2009-11-06 12:39:23