简体   繁体   English

从C#调用C ++ dll时出现内存泄漏

[英]Memory Leaks while calling C++ dll from C#

I have a C++ dll that I am calling from C# code. 我有一个从C#代码调用的C ++ dll。 the dll takes in couple params and returns an int.. dll接受几个参数并返回一个int。

C++ code. C ++代码。

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# 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? 垃圾收集器是否照顾在C ++代码中初始化的所有对象? does C++ code initialize some memory for the string builder ("buffer") even if it is initialized in C#. C ++代码是否为字符串生成器(“缓冲区”)初始化了一些内存,即使它是在C#中初始化的也是如此。 I cannot dispose this in the C++ because i need to collect the data from the string builder. 我不能在C ++中处理它,因为我需要从字符串生成器中收集数据。

I have never worked on C++ but I see that few objects that were declared in C++ dll are being cleared. 我从未使用过C ++,但是我看到在C ++ dll中声明的对象很少被清除。

I might be doing something wrong in the way that I am calling the C++ code. 我在调用C ++代码的方式上可能做错了。 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). C#不会释放C ++分配的任何内存(如果使用COM分配器/ 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). C ++代码中没有内存分配,并且StringBuilder是在C#端“构建”的,并且有10000个字符大,我希望这样就足够了(请注意,通常您会将缓冲区的大小传递给C ++,否则您将首先请问另一个C ++方法所需缓冲区的大小)。

On a tangential note, I would suggest using wchar_t in C++, to maintain full compatibility with C# string s/ char s/... 切记,我建议在C ++中使用wchar_t来保持与C# string s / char s /的完全兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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