How to transfer a bitmap in dll written by Delphi in C #?

I have a Delphi function in a dll written as follows:

       function LensFlare(Bitmap: TBitmap; X, Y: Int32; Brightness: Real): TBitmap; StdCall;
       Begin
         // ...
         Result := Bitmap;
       End;

I want to use it in C #, I tried this, but I did not succeed:

    [DllImport("ImageProcessor")]
    static extern Bitmap LensFlare(Bitmap bitmap, int x, int y, double Brightness);

    private void button1_Click(object sender, EventArgs e)
    {
        Bitmap b = new Bitmap(@"d:\a.bmp");
        pictureBox1.Image = LensFlare(b, 100, 100, 50); // Error!
    }

Error: "Attempted to read or write protected memory. This often indicates that another memory is corrupt."

How can i do this?

+4
source share
2 answers

The Delphi class is TBitmapvery different from the .NET class Bitmap. They are incompatible with each other, and none of them is safe for interoperability.

Instead, you will have to use a raw Win32 handle HBITMAP.

function LensFlare(Bitmap: HBITMAP; X, Y: Int32; Brightness: Real): HBITMAP; StdCall;
Begin
  // ...
  Result := Bitmap;
End;

[DllImport("ImageProcessor")]
static extern IntPtr LensFlare(PtrInt bitmap, int x, int y, double Brightness);

[DllImport("gdi32.dll")]
static extern bool DeleteObject(IntPtr hObject);

private void button1_Click(object sender, EventArgs e)
{
    Bitmap b = new Bitmap(@"d:\a.bmp");
    IntPtr hbmp = LensFlare(b.GetHbitmap(), 100, 100, 50);
    try {
        pictureBox1.Image = Image.FromHbitmap(hbmp);
    }
    finally {
        DeleteObject(hbmp);
    }
}
+3

. Delphi, . Delphi .

. HBITMAP. Delphi. , .

+5

Source: https://habr.com/ru/post/1685247/


All Articles