Throw an exception from Delphi DLL in C #

The problem I recently encountered is the following.

I have a .DLL written in Delphi, this DLL has a Divide function (which takes two integers as a parameter) and returns its value as it should.

function Divide( aFirstValue, aSecondValue : Integer ) : Double; stdcall;
begin
  result := aFirstValue / aSecondValue;
end;

Now, if I use the following parameters "5, 0", then it throws a DivideByZeroException (which is correct :))

But when I call the same .DLL from C #, it does not detect any exceptions at all.

[DllImport("DelphiDLL.DLL", EntryPoint = "Divide", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern float Divide(Int32 a, Int32 b);

private void Button_Click_2(object sender, System.EventArgs e)
{
    try
    {
       TB.Text += "Divide(a,b) = ";
       float temp;
       temp = Divide(Convert.ToInt32(aTB.Text), Convert.ToInt32(bTB.Text));

       Console.WriteLine(Marshal.GetLastWin32Error());

       TB.Text += Convert.ToString(temp) + "\r\n";
    }
    catch (DivideByZeroException eMsg)
    {

    }
}
+4
source share
1 answer

DLL. , .

- DLL. DLL . , . , .

function CalcQuotient(a, b: Integer; out quotient: Double): Integer; stdcall;
begin
  try
    quotient := a / b;
    Result := 0;// you'd use a constant with a sensible name rather than a magic value
  except
    on E: Exception do begin
      Result := GetErrorCode(E);
      // where GetErrorCode is your function that converts exceptions into error codes
    end;
  end;
end;

p/invoke:

  • CharSet, .
  • SetLastError = true . SetLastError. , Marshal.GetLastWin32Error() .
+10

All Articles