Search code examples
c#.netunmanaged

Freeing up of unmanaged code in C#


I call a piece of an unmanaged C++ code from my C# application to calculate fast fourier transform of a discrete time signal.

I make a call something like this

IntPtr ptr = ComputeFFTW(packetSig, packetSig.Length, (int)samplFrequency,(int)fftPoints);

    unsafe
     {
           double *dPtr = (double*)ptr;

           for(int l = 0; l < fftData.Length; l++)
        {
          fftData[l] = dPtr[l];
            }   

      }

Though this snippet of code works fine and gives me the desired results, i can see that there is sort of performance hit (memory leak) is incurred while calculation is in progress. The CLR fails to reclaim the local (double) variables and my application gobbles up RAM space considerably.

Can anyone of you suggest the places where i might be doing it wrong.

From my side, I ran my application using ANTS Mem Profiler and i can see on the snapshot that the double objects nearly claim >150MB of the mem space. Is this a normal behaviour ??

Class Name  Live Size (bytes)   Live Instances
Double[]    150,994,980         3

Any help is appreciated in this regard Srivatsa


Solution

  • You can use Marshal.Copy(IntPtr, Double[], Int32, Int32) method to copy array of double values from unmanaged ptr to managed ffData array:

    IntPtr ptr = ComputeFFTW(packetSig, packetSig.Length, (int)samplFrequency,(int)fftPoints); 
     
    Marshal.Copy(ptr, fftData, 0, fftData.Length);
    

    If ComputeFFTW returns pointer to dynamically allocated memory, you need to release it after using. Make this in unmanaged code, add function like Release and pass ptr to it.