Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# out of memory after calling a memory-hungry native-code DLL (Delphi)

I have a C# application that does a few bits and pieces, but the main task it performs is done by a Delphi DLL which it calls.

This Delphi DLL is a total memory hog, which needs to cache a lot of DB-information locally for speed. I'm happy that it's not leaky, as FastMM4 isn't reporting any memory leaks when the code is run within Delphi.

I am starting to run into problems, however, when the control is returned to C#. The C# code attempts to do some calculations on the results of the Delphi app (all results marshalled via a DB). These calculations usually involve a million or so doubles so not extreme memory usage, however the code keeps returning me out of memory exceptions.

I assume that FastMM4 in the Delphi code still hasn't returned the freed memory to Windows (and hence available to the C# code), so the process is still using it's maximum 32-bit memory allocation and C# can't obtain more when it needs to.

So, how do I get the memory used (and freed) by Delphi usable again by the C# code? I thought we may want to do one of the following:

  • Force an unload of the Delphi DLL from the C# side (my colleague doesn't think this will work, as he thinks it'll just unload the code rather than the memory used on the heap) - probably LoadLibrary/FreeLibrary?
  • Make a call at the end of the Delphi DLL to release the memory back to Windows (I tried SetWorkingProcessSetSize before, but didn't seem to do anything, should I use a different call?)
  • Wrap the Delphi DLL in a C# DLL and call it in a different AppDomain (I don't like this from a style perspective as we're creating wrappers just to hold wrappers.
  • Anything else I've missed?
like image 774
Matt Allwood Avatar asked Jan 27 '26 17:01

Matt Allwood


1 Answers

Force an unload of the Delphi DLL from the C# side (my colleague doesn't think this will work, as he thinks it'll just unload the code rather than the memory used on the heap) - probably LoadLibrary/FreeLibrary?

This will just work. When the DLL unloads, FastMM will finalize and return the memory that it reserved and committed.

like image 151
David Heffernan Avatar answered Jan 30 '26 07:01

David Heffernan



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!