C#中的Marshal
Const.MaxLengthOfBufferd的长度固定为0x2000 也就是8192
private bool SendMessage(int messageType, string ip, string port, int length, byte[] messageBytes) { bool result = false; try { if (windowHandle != 0) { var bytes = new byte[Const.MaxLengthOfBuffer]; Array.Copy(messageBytes, bytes, messageBytes.Length); int sizeOfType = Marshal.SizeOf(typeof(StClientData)); //Step1 把数据封装到结构体中 StClientData stData = new StClientData { Ip = GlobalConvert.IpAddressToUInt32(IPAddress.Parse(ip))//客户端ip ,Port = Convert.ToInt16(port)//客户端端口 ,Length = Convert.ToUInt32(length) ,Buffer = bytes }; //Step2 给结构体实例分配空间 //public static int SizeOf(Object structure) //函数说明:Returns the unmanaged size of an object in bytes. //structure:The object whose size is to be returned. //Return Value:The size of the specified object in unmanaged code. int sizeOfStData = Marshal.SizeOf(stData); //public static IntPtr AllocHGlobal(int cb) //函数说明:Allocates memory from the unmanaged memory of the process by using the specified number of bytes. //cb:The required number of bytes in memory. //Return Value:A pointer to the newly allocated memory. This memory must be released using the Marshal.FreeHGlobal method. IntPtr pointer = Marshal.AllocHGlobal(sizeOfStData); //把结构体实例赋值到非托管内存中 //public static void StructureToPtr(Object structure,IntPtr ptr,bool fDeleteOld) //函数说明:Marshals data from a managed object to an unmanaged block of memory. //structure:A managed object that holds the data to be marshaled. This object must be a structure or an instance of a formatted class. //ptr:A pointer to an unmanaged block of memory, which must be allocated before this method is called. //fDeleteOld:true to call the Marshal.DestroyStructure method on the ptr parameter before this method copies the data. // The block must contain valid data. // Note that passing false when the memory block already contains data can lead to a memory leak. Marshal.StructureToPtr(stData, pointer, true); CopyData copyData = new CopyData { DwData = (IntPtr) messageType, CbData = Marshal.SizeOf(sizeOfType), LpData = pointer }; SendMessage(windowHandle, WmCopydata, 0, ref copyData); Marshal.FreeHGlobal(pointer); string data = GlobalConvert.ByteArrayToHexString(messageBytes); CommunicationManager.Instance.SendDebugInfo(new DataSendEventArgs() {Data = data}); result = true; } } catch (Exception ex) { ExceptionLog.Instance.WriteLog(ex, LogType.UI); } return result; }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了