c# 结构体 能不能直接封送检测

cs 复制代码
    #region Blittable 缓存检测器
    public static class BlittableChecker
    {
        private static class Cache<T> where T : struct
        {
            public static readonly bool IsBlittable = CheckInternal();

            /// <summary>
            /// 可直接封送类型
            /// </summary>
            /// <returns></returns>
            private static bool CheckInternal()
            {
                T dummy = default;
                GCHandle handle;
                try
                {
                    handle = GCHandle.Alloc(dummy, GCHandleType.Pinned);
                }
                catch (ArgumentException)
                {
                    return false;
                }
                handle.Free();
                return true;
            }
        }

        /// <summary>
        /// 判断值类型是否 Blittable,每种 T 只校验一次,全局缓存
        /// </summary>
        public static bool IsBlittable<T>() where T : struct
        {
            return Cache<T>.IsBlittable;
        }
    }
    #endregion

    #region 泛型数组锁定工具类
    public static unsafe class BufferLockHelper
    {
        /// <summary>
        /// 锁定结构体数组,回调内瞬时获取指针(fixed,同步使用,不可缓存指针)
        /// </summary>
        /// <typeparam name="T">blittable struct</typeparam>
        /// <param name="imgData">目标数组</param>
        /// <param name="act">回调:指针,元素个数,总字节大小</param>
        public static void LockStructArray<T>(T[] imgData, Action<IntPtr, int, int> act)
            where T : struct
        {
            if (imgData == null)
                throw new ArgumentNullException(nameof(imgData));

            if (imgData.Length == 0)
                return;

            if (!BlittableChecker.IsBlittable<T>())
            {
                throw new NotSupportedException(
                    $"结构体 {typeof(T).FullName} 不是 Blittable,禁止将 fixed 裸指针传递给非托管代码!");
            }

            int elemSize = Marshal.SizeOf(typeof(T));
            int totalBytes = elemSize * imgData.Length;

            fixed (void* ptr = imgData)
            {
                act(new IntPtr(ptr), imgData.Length, totalBytes);
            }
        }
    }
    #endregion

不能封送

cs 复制代码
public struct BadStructWithBool
{
public int X;
public bool Valid;
}

第一次改造,可以封送,但是不能Pinned

cs 复制代码
// 这样改【无效】,仍然不能Pinned、不能通过 BlittableChecker
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct StillBad
{
    public int X;
    [MarshalAs(UnmanagedType.U1)]
    public bool Valid; // 字段本质仍是 bool,CLR判定为non-blittable
}

第二次改造后 ,可以封送

cs 复制代码
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct GoodStructWithBool
{
    public int X;
    private byte _valid; // 底层用 byte(blittable)

    // 对外 bool 访问器,不影响内存布局
    public bool Valid
    {
        get => _valid != 0;
        set => _valid = (byte)(value ? 1 : 0);
    }
}
相关推荐
全速向光32 分钟前
用 Three.js 从零打造一棵会发光的 3D 圣诞树
开发语言·javascript·3d
codeejun39 分钟前
每日一Go·MySQL-28、账户转账事务设计
开发语言·mysql·golang
ShineWinsu1 小时前
对于Qt:QSS样式属性的解析
开发语言·c++·qt·面试·盒子模型·客户端·qss
reasonsummer1 小时前
【办公类-178-01】20261204医保需要“幼儿园园通学籍证明截图”(Python页面截图+转PDF)
开发语言·c#
夜雪轻寒1 小时前
AI 工具踩坑录:Prompt 我越写越长,模型反而越来越笨,删到第三版才明白它在装
java·开发语言·人工智能·语言模型·自然语言处理·prompt
吴名氏.2 小时前
全栈跃迁:Java 后端 27 讲【7】MyBatisPlus进阶与慢SQL治理
java·开发语言·数据库·sql·大模型·sql调优
『 时光荏苒 』2 小时前
SQL 中常用的查询条件分类汇总,每个都配有“大白话注释”和示例,方便你对照学习
android·java·开发语言
yuzhiboyouye2 小时前
我做web前端八年多了,转C#怎么样,而且我现在的java是初级水平,问的通义
c#
王者鳜錸2 小时前
【中英】-Android离线语音听写-讯飞 AIKit源码实现
开发语言·python·智能手机·安卓·离线中英识别
nice_lcj5202 小时前
Jakarta Validation:从注解到自定义约束的完整实践
java·开发语言·spring boot