日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > C# >内容正文

C#

c#的Marshal

發(fā)布時間:2025/3/17 C# 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c#的Marshal 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

? 補(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。