1

I wanted to know whether sending a locked Bitmap's BitmapData.Scan0 field to unmanaged C++ could be an issue. Here's how I do it:

From C#.NET:

public class BmpTest{
    Bitmap bmp = new Bitmap();
    BitmapData bmpData = new BitmapData();


    public BmpTest()
    {
        fooFillBitmapWithData(bmp);
    }

    public IntPtr getDataPtr()
    {
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
        return bmpData.Scan0;
    }

    public void unlockData()
    {
        bmp.UnlockBits(bmpData);
    }
}

Then, using a C++/CLI Wrapper (not included in this sample):

// This is unmanaged, native c++
int main()
{
    unsigned short * dataPtr = BmpTestCliWrapper.getDataPtr();
    // do something like ... update openGL texture with data 
    BmpTestCliWrapper.unlockData();
}

I am not using GCHandle, as BitmapData will be locked to memory according to this source. I only need to read the Bitmap so that I can update an OpenGL texture. I cannot access the images directly from C++. I probably could from C++/CLI but I don't see a clear advantage.

Sergio Basurco
  • 3,488
  • 2
  • 22
  • 40
  • 3
    Yes, no problem. As long as the native code doesn't store the pointer and uses it after you called UnlockBits() of course. You can't store it in an `unsigned short`, it needs to be a pointer type. Fwiw, this kind of locking doesn't have anything to do with the .NET garbage collector, bitmap data is already stored in native memory. – Hans Passant Nov 10 '14 at 16:56
  • Yep that was a typo, it is an unsigned short *. Editing that now. Thanks for the confirmation. @LucasTrzesniewski, thanks for the heads up. I still don't know if bitmap data is stored in native memory, according to [this](http://stackoverflow.com/q/6782489/2628257) other question the GC will move it given certain conditions. – Sergio Basurco Nov 10 '14 at 22:42
  • 3
    In this other question he's talking about a .NET managed byte array. In your case, you have a `Bitmap` object, which is just a wrapper around a native `HBITMAP`. It doesn't store image data in managed memory ([except for animated GIFs](http://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Image.cs,70)), so you don't need to pin it. – Lucas Trzesniewski Nov 10 '14 at 22:53

0 Answers0