Who owns the C++ object instantiated from C#?

It has to be C# because a C++ object instantiated from C# lives inside of a managed C# object, it eventually will be garbage collected by the .NET framework and the memory of the native C++ object will then be released, any native memory or resource allocated by the native C++ object will be released as well. If you want to stop the C++ object from being garbage collected during the time when the C++ DLL still tries to access it, you will need to put a lock on the C# object to prevent it from being garbage collected, and then remember to unlock it when you are sure the native C++ DLL no longer needs to access it. There are surely ways we can implement to let the C# .NET object to dispose itself automatically when the the C++ object gets deleted from the C++ DLL, but it will certainly slow down the P/Invoke procedure and affect the performance of P/Invoke, so we decided we currently do not implement it.


← Faqs
Translate »