M Ahmadzadeh
M Ahmadzadeh

Reputation: 121

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

I have a Delphi function in a dll written like this:

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

I want to use it in C#, I have tried this but I was not successful:

    [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 is often an indication that other memory is corrupt."

How can I do this?

Upvotes: 4

Views: 1131

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597941

Delphi's TBitmap class is very different than .NET's Bitmap class. They are not compatible with each other, and neither is safe for interoperability purposes.

You will have to use a raw Win32 HBITMAP handle instead.

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);
    }
}

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 613451

You can't use this function. It's not even safe to use between two Delphi modules unless you use packages. You cannot pass native Delphi classes across a module boundary like that.

You'll need to switch to an interop friendly type. The obvious option is to use an HBITMAP. You will need to modify the Delphi library. If you don't have the source you will need to contact the original developer.

Upvotes: 5

Related Questions