C#正确处理带有Char *的结构 [英] C# Proper Disposing of Structure with Char*

查看:442
本文介绍了C#正确处理带有Char *的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#还是很陌生,但是在释放非托管资源时遇到了麻烦.对于功能CharPtrToString,是否有必要释放IntPtr?另外,调用List<是安全的吗? MyStruct> .clear()而不会导致内存泄漏?

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;
    }

推荐答案

如果可能,在分配charPointer变量时,应尝试使用固定"关键字.这可以修复指针,以便垃圾回收不会清理指针.然后您也不需要释放它,它将在固定块后自动释放.这取决于您的其他代码的方式.

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/zh-CN/dotnet/csharp/language-reference/keywords/fixed-statement

所以它看起来像这样

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

这篇关于C#正确处理带有Char *的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆