free memory not clears the memory block

前端 未结 3 804
迷失自我
迷失自我 2021-01-16 06:19

I am using DllImport to call method in c wrapper library from my own .net class. This method in c dll creates a string variable and returns the pointer of the string.

<
3条回答
  •  一整个雨季
    2021-01-16 07:03

    What may be the problem is the underlying C code. You are not adding a NULL terminator to the string which strcat relies on (or checking for a NULL return from malloc). It's easy to get corrupted memory in that scenario. You can fix that by doing the following.

    retval[0] = '\0';
    strcat(retval, "SOMETEXT");
    

    Also part of the problem is that you are playing tricks on the system. It's much better to write it correctly and let the system work on correctly functioning code. The first step is fixing up the native code to properly return the string. One thing you need to consider is that only certain types of memory can be natively freed by the CLR (HGlobal and CoTask allocations). So lets change the function signature to return a char* and use a different allocator.

    _declspec(dllexport) char* ReturnString()
    {
     char* retval = (char *) CoTaskMemAlloc(125);
     retval[0] = '\0';
     strcat(retval, "SOMETEXT");
     strcat(retval, "SOMETEXT MORE");
     return retval;
    }
    

    Then you can use the following C# signature and free the IntPtr with Marshal.FreeCoTaskMem.

    [DllImport("SomeDll.dll")]
    public static extern IntPtr ReturnString();
    

    Even better though. When marshalling, if the CLR ever thinks it needs to free memory it will use FreeCoTaskMem to do so. This is typically relevant for string returns. Since you allocated the memory with CoTaskMemAlloc you can save yourself the marshalling + freeing steps and do the following

    [DllImport("SomeDll.dll", CharSet=Ansi)]
    public static extern String ReturnString();
    

提交回复
热议问题