【发布时间】:2011-04-19 23:52:19
【问题描述】:
我在 C# 中定义了一个结构来镜像本机数据结构,并使用了 Sequential 的 StructLayout。要将结构转换为 Socket IOControl 方法所需的 12 字节(3x 4 字节),我使用 Marshal.Copy 将字节复制到数组中。
由于结构只包含值类型,我是否需要在执行复制之前固定结构?我知道 GC 会压缩堆,因此引用类型的内存地址可以在 GC 期间更改。堆栈分配的值类型也一样吗?
包含pin操作的当前版本如下:
[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();
}
}
}
有什么想法吗?
【问题讨论】:
标签: c# .net garbage-collection