c#的Marshal
? 補(bǔ)充過程中~
感覺應(yīng)該是C#調(diào)用非托管的比較專門的class
例1、
public struct ImageDataMsg?
{?
public char DataType;?
public int Srv_index;?
public char ConvertType;?
//這個個地方要指定長度,這樣就可以的德奧結(jié)構(gòu)體的正確長度了?
[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;?
}?
//使用這個方法將你的結(jié)構(gòu)體轉(zhuǎn)化為bytes數(shù)組?
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數(shù)組轉(zhuǎn)化為結(jié)構(gòu)體?
public static object BytesToStuct2(byte[] bytes, ImageDataMsg type)?
{?
//得到結(jié)構(gòu)體的大小?
int size = Marshal.SizeOf(type);?
//byte數(shù)組長度小于結(jié)構(gòu)體的大小?
if (size > bytes.Length)?
{?
//返回空?
return null;?
}?
//分配結(jié)構(gòu)體大小的內(nèi)存空間?
IntPtr structPtr = Marshal.AllocHGlobal(size);?
//將byte數(shù)組拷到分配好的內(nèi)存空間?
Marshal.Copy(bytes, 0, structPtr, size);?
//將內(nèi)存空間轉(zhuǎn)換為目標(biāo)結(jié)構(gòu)體?
object obj = Marshal.PtrToStructure(structPtr, typeof(ImageDataMsg));?
//釋放內(nèi)存空間?
Marshal.FreeHGlobal(structPtr);?
//返回結(jié)構(gòu)體?
return obj;?
}?
轉(zhuǎn)載于:https://blog.51cto.com/huangchaosuper/887538
總結(jié)
以上是生活随笔為你收集整理的c#的Marshal的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Makefile学习(一)[第二版]
- 下一篇: C#中的方法(上):