Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Memory leaks when using a C# COM interop class from C++?

$
0
0

I am trying to use a COM object written in C# from C++ and I don't understand why the memory becomes greater and greater.

In C#, we have a very simple COM interface :

    public enum COMObjectErrorCodes
    {
        OK,
        Error,
    }

	public interface IInterface
    {
        /// <summary>
        /// This interface has only one method which does nothing
        /// </summary>
        /// <returns></returns>
        COMObjectErrorCodes Func();
    }

    public class InterfaceImpl : IInterface
    {
        public COMObjectErrorCodes Func()
        { return COMObjectErrorCodes.OK; }
    }

    public interface ICOMObject
    {
        /// <summary>
        /// This simple methods permits to get another interface
        /// </summary>
        /// <param name="oInt">The returned interface</param>
        /// <returns></returns>
        COMObjectErrorCodes GetInterface(out IInterface oInt);
    }

	public class COMObjectImpl : ICOMObject
    {
        public COMObjectErrorCodes GetInterface(out IInterface oInt)
        {
            oInt = new InterfaceImpl();
            return COMObjectErrorCodes.OK;
        }
    }


And the C++ client which is using this COM interop class:

// 0. Initialize COM
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

if (hr == S_OK || hr == S_FALSE || hr == RPC_E_CHANGED_MODE)
{
// 1. Creates an instance of the COM object
ICOMObjectPtr pFactory(__uuidof(COMObjectImpl));

// 2. Use it in a loop
COMObjectErrorCodes err;
for (int i = 0; i < 1000000; i++)
{
// 1. Get the interface
IInterface* pI = NULL;
gPtr->GetInterface(&pI, &err);
// 2. Do the call
pI->Func(&err);
// 3. Release the interface (don't worry, it returns 0, I verified !)
pI->Release();
}

// 4. Release the COM object
pFactory->Release();
}

// 5. Uninitialize COM
CoUninitialize();


And my problem is if you display the memory before step 0, and after step 5, it has increased :

- with 1 000 000 loops : 25 Mo 25 Mo (25 bytes lost per loop), 

- with 1 000 loops... 553 ko (500 bytes lost per loop)

Does somebody know what could cause this?


Viewing all articles
Browse latest Browse all 1710

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>