Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Free memory allocated by operator new from p/invoke DLL

Tags:

c#

pinvoke

I have a C# application which is using a third party (closed source) native DLL through p/invoke.

During some of these calls, the DLL will allocate memory using operator new / operator new[] and return a pointer to use for reading the results.

This memory is never freed by the DLL after being allocated and returned. How can I perform the equivalent of a native operator delete / operator delete[] in C#?

like image 968
Scorpion Avatar asked Oct 26 '25 11:10

Scorpion


1 Answers

Not possible. The DLL stores the handle returned by HeapCreate() internally. You'd have to know that handle to release the memory, you cannot get it out of the DLL. And you would have to know how many extra bytes were allocated by the DLL's malloc function to adjust the pointer.

You cannot even do this reliably if you write a wrapper for the DLL so that you can call free(). The DLL will have to use the DLL version of the CRT and you have to compile the wrapper with the exact same version of the compiler and the CRT so they'll share the same CRT DLL.

If you are really desperate, you could try to hack through GetProcessHeaps(). Although that's hard to get right, error prone and you really have to know what you're doing. DLLs returning pointers that need to be freed is a really bad practice even in C or C++. Just not in .NET, hail the garbage collector :)

like image 131
Hans Passant Avatar answered Oct 29 '25 02:10

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!