Get size of a buffer in C#
<p>I have a C++/CLI dll and one of the methods requires a pointer and its buffer size as its parameters.</p>

<h2><strong>C++/CLI</strong></h2>

<ul>
<li><strong>Param1:BufferPtr</strong> = Pointer to the beginning of the buffer.</li>
<li><strong>Param2:BufferSize</strong> = Size of the buffer.</li>
</ul>

<hr>

<pre><code>// Example..
uint LoadImageFromMemory(const unsigned char * const  BufferPtr, const int BufferSize);
</code></pre>

<hr>

<h1><strong>C#</strong></h1>

<pre><code>Bitmap Img = Bitmap.FromFile(@"C:/my.jpg") as Bitmap;
.
.
// Convert the 'Img' to byte* pointer.
byte[] TempByte = new byte[TempStorage.Height * TempStorage.Width * 3];
byte[] ActualByte = null;

System.Drawing.Imaging.BitmapData m_pImageData = null;

// Converting Bitmap to Byte array...
try
{
     m_pImageData = TempStorage.LockBits(new Rectangle(0, 0, TempStorage.Width, TempStorage.Height),
                                             System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                             System.Drawing.Imaging.PixelFormat.Format24bppRgb);

     System.IntPtr pScan = m_pImageData.Scan0; // 5
     int nStride = m_pImageData.Stride;// 6
     ActualByte = new byte[m_pImageData.Height * m_pImageData.Width * 3];

     unsafe
     {
          byte* pBuffer = (byte*)(void*)pScan;// 7

          int noffset = nStride - TempStorage.Width * 3;

          int count = 0;
          for (int nY = 0; nY &lt; TempStorage.Height; nY++)
          {
               for (int nX = 0; nX &lt; TempStorage.Width; nX++)
               {

                    ActualByte[count] = pBuffer[0];
                    ActualByte[count + 1] = pBuffer[1];
                    ActualByte[count + 2] = pBuffer[2];
                    count += 3;
                    pBuffer += 3;
               }
               pBuffer += noffset;
            }
        }
    }
finally
{
     if (m_pImageData != null)
     {
         TempStorage.UnlockBits(m_pImageData);
     }
}

.
.
// At the end... 
.
.
fixed (byte* ptrAdd = ActualByte)
{
                  // this second parameter ( below ) is problematic...
    rst = CppAPI.LoadImageFromMemory(ptrAdd, ?????);
}
</code></pre>

<hr>

<p><strong>How can I get the buffer size?</strong></p>

<p>Since I have no idea of what exactly the buffer size means here, I tried to pass these values into the second parameter, wild-guessing.</p>

<ul>
<li>ActualByte length,</li>
<li>Stride of this 'my.jpg' image</li>
<li>The address value as an int ( <em>A stupid wild guess !</em> )</li>
</ul>

<p>Unfortunately, none of them worked. </p>

<p>I have the image, its bitmap object and its pointer in C#. Aren't these sufficient to get the buffer size?</p>