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;?
}?
轉載于:https://blog.51cto.com/huangchaosuper/887538
總結
以上是生活随笔為你收集整理的c#的Marshal的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Makefile学习(一)[第二版]
- 下一篇: 华为开源框架