c#的Marshal

时间:2023-03-09 12:49:09
c#的Marshal
补充过程中~
感觉应该是C#调用非托管的比较专门的class 例1、
public struct ImageDataMsg
{
public char DataType;
public int Srv_index;
public char ConvertType;
//这个个地方要指定长度,这样就可以的德奥结构体的正确长度了
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public int[] VecLayer;//需要那几个图层。
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public int[] GridLayer;//需要那几个栅格图层
public int Scale_index;//需要的是那个比例尺的图像
public int x_pos;
public int y_pos;
public int ClientArea_x;
public int ClientArea_y;
}
//使用这个方法将你的结构体转化为bytes数组
public static byte[] Struct2Bytes(ImageDataMsg obj)
{
int size = Marshal.SizeOf(obj);
byte[] bytes = new byte[size];
try
{
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, false);
Marshal.Copy(ptr, bytes, 0, size);
Marshal.FreeHGlobal(ptr);
return bytes;
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
return bytes;
}
} //使用这个方法将byte数组转化为结构体
public static object BytesToStuct2(byte[] bytes, ImageDataMsg type)
{
//得到结构体的大小
int size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
//返回空
return null;
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, typeof(ImageDataMsg));
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return obj;
}