tags:

views:

77

answers:

2

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

+4  A: 

Since the C++ function allocates memory you will have to manually free that chunk in your C# application (free the pointer). A better way to do invoke unmanaged code is to allocate all the variables and memory chunks (Temp parameters too) in your C# application and pass them to your C++ code as parameters. In this way you wont have any memory issues with your unmanaged code.

Gilad
A: 

You can use Marshal.Copy Method (IntPtr, Double[], Int32, Int32) 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.

Alex Farber
Thank you Alex.This helped me to fix it a bit. I think i'll have to debug on the C++ side to check whats going on this side of the code.
this-Me