123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- using System;
- using System.Runtime.InteropServices;
- using System.Text;
- using TBL.CSharp.Base;
- namespace TBL.CSharp.Game.Server.Utilities;
- /// <summary>
- /// 字节块
- /// </summary>
- public readonly unsafe struct ByteBlock
- {
- /// <summary>
- /// 空字节块
- /// </summary>
- public static readonly ByteBlock Empty = new ByteBlock((void*) 0, 0);
-
- /// <summary>
- /// 地址
- /// </summary>
- public readonly void* Address;
- /// <summary>
- /// 字节尺寸
- /// </summary>
- public readonly int Size;
- public ByteBlock(void* ptr, int size)
- {
- Address = ptr;
- Size = size;
- }
- /// <summary>
- /// 是否在空指针
- /// </summary>
- public bool IsNullPtr => (void*) 0 == Address;
- /// <summary>
- /// 释放
- /// <para>不要重复进行释放操作</para>
- /// </summary>
- public void Free()
- {
- Marshal.FreeHGlobal(new IntPtr(Address));
- }
- /// <summary>
- /// 分配所需尺寸的字节块
- /// </summary>
- public static ByteBlock Alloc(int size) => new ByteBlock(Marshal.AllocHGlobal(size).ToPointer(), size);
- /// <summary>
- /// 分配所需尺寸的字节块并复制指定内容
- /// </summary>
- public static ByteBlock AllocWithCopy(void* source, int size)
- {
- var block = Alloc(size);
- Buffer.MemoryCopy(source, block.Address, size, size);
- return block;
- }
- /// <summary>
- /// 分配装载一个非托管值的字节块
- /// </summary>
- public static ByteBlock AllocWithValue<T>(T value) where T : unmanaged
- {
- var block = Alloc(sizeof(T));
- *(T*) block.Address = value;
- return block;
- }
- /// <summary>
- /// 分配装载一个字符串的字节块
- /// </summary>
- public static ByteBlock AllocWithString(string str)
- {
- fixed(void* ptr = str)
- {
- return AllocWithCopy(ptr, Encoding.Default.GetByteCount(str));
- }
- }
- /// <summary>
- /// 分配所需尺寸的字节块并初始化内容
- /// </summary>
- public static ByteBlock AllocWithInitialize(int size, Extension.OnBufferUse initializer)
- {
- var block = Alloc(size);
- initializer(block.Address);
- return block;
- }
- }
|