问题
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