C# Proper Disposing of Structure with Char*

吃可爱长大的小学妹 提交于 2020-01-05 04:07:26

问题


I'm quite new to C# and I'm having trouble releasing unmanaged resource. For the function CharPtrToString, is it necessary to release IntPtr? In addition, would it be safe to call List < MyStruct >.clear() without causing a memory leak?

    public string CharPtrToString(MycharArray chararray)
    {
        IntPtr ipp = (IntPtr)chararray;
        string s = Marshal.PtrToStringAnsi(ipp)
        //need to free Ipp?
        return s;
    }

    public struct MyStruct
    {
          public Int int1;
          public MyCharArray charArray;
    }

    public unsafe struct MyCharArray
    {
          public char* charPointer;
    }

回答1:


if possible, when assigning the charPointer variable, you should try to use the "fixed" keyword. this fixes the pointer so the garbage collection does not clean up the pointer. Then you also do not need to release it, it will be automatically released after the fixed block. This depends how your other code is.

https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/fixed-statement

so it would look about like this

 fixed(char* charPointer = ... )
 {
    IntPtr ipp = (IntPtr)charPointer;
    string s = Marshal.PtrToStringAnsi(ipp)
 }


来源:https://stackoverflow.com/questions/50242234/c-sharp-proper-disposing-of-structure-with-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!