简体   繁体   中英

Memory Leaks while calling C++ dll from C#

I have a C++ dll that I am calling from C# code. the dll takes in couple params and returns an int..

C++ code.

extern "C" __declspec(dllexport) int DoSomething(char* input1, char* buffer)
{
    gss_buffer_desc token;
    std::string encodedTokenStr = base64_encode((unsigned char *)token.value, token.length).c_str();

    std::copy(encodedTokenStr.begin(), encodedTokenStr.end(), buffer);
    return value;
}

C#

public sealed class MyClass
{    
     public int DoSomething(string input1, out StringBuilder buffer)
     {
         buffer = new StringBuilder(10000);
         return DoSomething(input1, buffer)
     }

    [DllImport("mycppcode.dll")]
    private static extern int DoSomething(string input1, StringBuilder buffer)
}

sometimes I see that a lot of memory is being used by this application and my first thought was about memory leaks. Does garbage collector takes care of all the objects that are initialized in the C++ code? does C++ code initialize some memory for the string builder ("buffer") even if it is initialized in C#. I cannot dispose this in the C++ because i need to collect the data from the string builder.

I have never worked on C++ but I see that few objects that were declared in C++ dll are being cleared.

I might be doing something wrong in the way that I am calling the C++ code. can this string builder cause memory leaks??

C# doesn't free any memory allocated by C++ (with some small exceptions if you use COM allocators/BSTR).

In your specific case

I don't see any problem in your case. There is no memory allocation in C++ code, and the StringBuilder is "built" C#-side, and being 10000 characters big, I do hope it is enough (note that normally you would pass to C++ the size of the buffer, or you would first ask to another C++ method the size of the needed buffer).

On a tangential note, I would suggest using wchar_t in C++, to maintain full compatibility with C# string s/ char s/...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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