小编Bri*_*anB的帖子

从内存位置复制字节时是否需要固定结构?

我在C#中定义了一个结构来镜像本机数据结构并使用了Sequential的StructLayout.要将结构转换为Socket IOControl方法所需的12个字节(3x4​​个字节),我使用Marshal.Copy将字节复制到数组.

由于结构只包含值类型,在执行复制之前是否需要固定结构?我知道GC会压缩堆,因此在GC期间引用类型的mem地址可能会发生变化.堆栈分配值类型的情况是否相同?

包含引脚操作的当前版本如下所示:

[StructLayout(LayoutKind.Sequential, Pack = 1)]  
struct TcpKeepAliveConfiguration
{
        public uint DoUseTcpKeepAlives;
        public uint IdleTimeMilliseconds;
        public uint KeepAlivePacketInterval;

        public byte[] ToByteArray()
        {
            byte[] bytes = new byte[Marshal.SizeOf(typeof(TcpKeepAliveConfiguration))];
            GCHandle pinStructure = GCHandle.Alloc(this, GCHandleType.Pinned);
            try
            {
                Marshal.Copy(pinStructure.AddrOfPinnedObject(), bytes, 0, bytes.Length);
                return bytes;
            }
            finally
            {
                pinStructure.Free();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

.net c# garbage-collection

10
推荐指数
2
解决办法
1210
查看次数

标签 统计

.net ×1

c# ×1

garbage-collection ×1