locked
Garbage collection and C++ dlls

    Question

  • Hi,

    I have a C# program and a C++ dll. The C# program calls a function in the C++ dll that adds a byte array to a hash_map. Will .NET's garbage collector eventually free the byte array even though it is used in the C++ dll? The byte array in C# is delcared as a local variable, so normally it would be freed after the method is finished.

    Sunday, December 25, 2011 6:41 PM

Answers

  • Assuming that:

    • the C++ dll is native C++ and not C++/CLI
    • the byte array is a byte[] passed to C++ in a PInvoke call

    then yes, the byte array will be freed by the garbage collector. Of course, that's probably bad news for the C++ code because the hash_map will contain an invalid pointer, if anything tries to use it then memory corruption or a crash can happen.

    • Marked as answer by xqrzd Monday, December 26, 2011 6:50 PM
    Sunday, December 25, 2011 7:28 PM

All replies

  • Assuming that:

    • the C++ dll is native C++ and not C++/CLI
    • the byte array is a byte[] passed to C++ in a PInvoke call

    then yes, the byte array will be freed by the garbage collector. Of course, that's probably bad news for the C++ code because the hash_map will contain an invalid pointer, if anything tries to use it then memory corruption or a crash can happen.

    • Marked as answer by xqrzd Monday, December 26, 2011 6:50 PM
    Sunday, December 25, 2011 7:28 PM
  • Thanks for the info. I solved the problem by allocating some memory in the dll and copying the array into it.
    Monday, December 26, 2011 6:52 PM