7

If I use C# to P/Invoke a certain DLL, will the actual C++ DLL be run for the duration of the call and then be shut down, destroying all used memory? Or will .NET take charge of the memory used by the C++ DLL in an unmanaged "heap" and give pointers to those objects to the C++ DLL everytime I call a static function?

When I need a certain C++ project to have its memory persistant, should I be creating an ActiveX/COM Server to have its memory persist, and yet be able to call it from C#?

Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

2 Answers2

5

If I use C# to P/Invoke a certain DLL, will the actual C++ DLL be run for the duration of the call and then be shut down, destroying all used memory?

No. Once the DLL is loaded it will stay loaded. The DLL's lifetime is not tied to a function call. This means that variables in the DLL that have static storage persist beyond the initial p/invoke call.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Where is the memory stored? Can you elaborate on that? – Robin Rodricks Mar 24 '13 at 13:24
  • Unmanaged DLLs are loaded into the address space of the managed program's Application Domain. Note that you can dyamically load and unload Application Domains, which removes the unmanaged DLLs from memory when the app domain is unloaded. – Matthew Watson Mar 24 '13 at 13:41
  • Where is what memory stored? Be precise about the question. – David Heffernan Mar 24 '13 at 13:41
  • I meant where is the memory of the C++ DLL stored... when run by a .NET app? ... "will .NET take charge of the memory used by the C++ DLL in an unmanaged "heap" and give pointers to those objects to the C++ DLL everytime I call a static function?" – Robin Rodricks Mar 24 '13 at 16:12
  • It's handled by the system. What you have is a native, unmanaged DLL. It's loaded with a call to `LoadLibrary`. Just like the .net runtime itself. .net doesn't "take charge" of anything. It just uses the standard platform mechanisms to load DLLs. – David Heffernan Mar 24 '13 at 16:13
2

If you are creating an object from a C++-DLL, it will actually persist until you delete it or rather dispose it. As you need to manually remove unmanaged objects, it will stay.

bash.d
  • 13,029
  • 3
  • 29
  • 42
  • So is it therefore possible to have a fully functional C++ project running as a DLL, and have simple static function P/Invoke'd from .NET with nothing breaking on the C++ side? Even if the C++ project uses objects and DirectX and complex things? – Robin Rodricks Mar 24 '13 at 12:53
  • It depends on what you understand by fully functional? Consider for example `COM`, where you are creating unmanaged components which you can then use in a managed environment. SO it should be possible. – bash.d Mar 24 '13 at 12:54