简体   繁体   English

在C#中释放C分配的内存

[英]Free C allocated memory in C#

I have tons of C code that I need to use in C#. 我有大量的C代码需要在C#中使用。 Example: 例:

long foo(char** mystring);
void free_string(char* mystring);

foo() is using malloc() to allocate memory for mystring . foo()使用malloc()mystring分配内存。 I have tried several ways of calling this function from C#, but I am failing to free mystring . 我尝试了几种从C#调用此函数的方法,但是无法释放mystring Can you please give me some guidelines on how to call foo() so that I can later free mystring ? 您能否给我一些有关如何调用foo()指导,以便以后可以释放mystring

For example, if char** is represented by StringBuilder[] , then how can I use it to be freed in free_string() ? 例如,如果char**StringBuilder[]表示,那么如何在free_string()释放它?

Allocating memory in native to be freed in managed puts quite an overhead on ensuring the caller knows exactly what they are doing, You might want to consider other techniques for allocating the memory in managed code. 在本机中分配要在托管中释放的内存在确保调用方确切知道他们在做什么方面有相当大的开销。您可能需要考虑其他技术,以便在托管代码中分配内存。

One example might be to make a callback into the managed code to get a string buffer 一个示例可能是对托管代码进行回调以获取字符串缓冲区

extern "C" __declspec void GetString( char* buffer, int bufferSize );

Matching C# would be the following: 匹配的C#将如下所示:

void GetString( StringBuilder buffer, int bufferSize );

If you allocate memory using LocalAlloc in kernel32.dll then you could free it using Marshal.FreeHGlobal(IntPtr) . 如果您在kernel32.dll使用LocalAlloc分配内存,则可以使用Marshal.FreeHGlobal(IntPtr)释放它。 Though you can't free malloc'ed memory with it. 虽然您不能用它释放malloc的内存。

As another solution consider passing C# StringBuilder reference and fill it with C code. 作为另一个解决方案,请考虑传递C#StringBuilder引用,并用C代码填充它。

Also take a look at MSDN article on memory models . 另请参阅有关内存模型的MSDN文章

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

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