randy ling
randy ling

Reputation: 62

Call C# unmanaged exports dll with serialPort class from Delphi application

I am using Robert Giesecke's Unmanaged Exports to put open method of SerialPort class from a C# class into a DLL. For now, the code is:

[DllExport]
public static void OpenPort(string portName, int baudRate, int dataBits)
{
    SerialPort serialPort = new SerialPort
    {
        StopBits = StopBits.One,
        Parity = Parity.None,
        ReadTimeout = 100,
        WriteTimeout = -1,
        PortName = portName,
        BaudRate = baudRate,
        DataBits = dataBits,
    };

    try
    {
        serialPort.Open();
    }
    catch (Exception)
    {
        throw new Exception("aaaaaaaaa");
    }

}

When I invoke it in Delphi, the code is:

 procedure OpenPort(portName: string; baudRate: integer; dataBits: integer); stdcall;
   external 'TestDll';

procedure TForm3.Button11Click(Sender: TObject);
begin
  OpenPort('COM2', 19200, 8);
end;

But Delphi shows an error:

External exception E0434352.

What should I do?

Upvotes: 1

Views: 1318

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

Two mistakes that can be seen.

  1. The first argument in the Delphi import should be declared as PAnsiChar to match your DLL. Default marshaling of C# string is as a pointer to null terminated array of ANSI characters.
  2. Your DLL must not throw an exception. The Delphi code cannot catch it. If you wish to indicate error do so using a boolean or integer return value.

The exception code that you see E0434352 identifies a .net exception so it is clear that your DLL is indeed throwing an exception which it must not do.

Serial ports are readily accessed with native Delphi code. If this is the only reason for including .net then I think you would be better off dropping it and sticking to Delphi.

Upvotes: 2

Related Questions