简体   繁体   English

C# StructLayout 和处理

[英]C# StructLayout and dispose

I have designed a StructLayout named ReceiveBuffer, and inside ReceiveBuffer, I have an unmanaged type of array to store data.我设计了一个名为 ReceiveBuffer 的 StructLayout,在 ReceiveBuffer 内部,我有一个非托管类型的数组来存储数据。 The code is shown as below.代码如下所示。

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
    public struct ReceiveBuffer
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
        public char[] Data;
    }

I want to implement IDisposable method inside this struct to dispose ReceiveBuffer properly whenever I don't need it.我想在这个结构中实现 IDisposable 方法,以便在不需要时正确处理 ReceiveBuffer。 I've check MSDN for some examples, but most of cases are used in class instead of struct.我查看了 MSDN 中的一些示例,但大多数情况下都在 class 中使用,而不是在 struct 中使用。 I'm not sure how to manage that in struct.我不确定如何在结构中管理它。 How do I implement IDisposible in such struct?如何在这样的结构中实现 IDisposible?

I have an unmanaged type of array to store data.我有一个非托管类型的数组来存储数据。

No, you do not.你不可以。 It is a managed array with Marshal instructions.它是一个带有 Marshal 指令的托管数组。

I'm not sure how to manage that in struct.我不确定如何在结构中管理它。 How do I implement IDisposible in such struct?如何在这样的结构中实现 IDisposible?

You do not.你不。 First, structs and disposable like this is EXTREMELY problametic due to the tons of copy operations happening on structs.首先,由于结构上发生了大量的复制操作,像这样的结构和一次性使用是非常有问题的。 Second, your whole assumption of having an unmanaged array is wrong.其次,您对拥有非托管数组的整个假设是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM