How to Retrieve the Native Handle of a TSQLConnection

Let’s say you want to share a connection to InterBase between IBX and dbExpress. For that you’ll need to retrieve the handle used by dbExpress and then use TIBDatabase.SetHandle to tell IBX to use that connection. But how to get the handle from dbExpress? Martijn Tonies pointed me in the right direction, and I wrote the following sample code:

procedure TForm1.Button1Click(Sender: TObject);
var
  SR: SQLResult;
  iHandle: Longint;
  iLen: SmallInt;
begin
  SQLConnection1.Connected := True;
  try
    SR := SQLConnection1.SQLConnection.GetOption(eConnNativeHandle, @iHandle, SizeOf(iHandle), iLen);
    if SR = DBXERR_NONE then begin
      ShowMessage('Handle: ' + IntToStr(iHandle));
    end else begin
      ShowMessage('Couldn''t retrieve native handle; error ' + IntToStr(SR));
    end; // if
  finally
    SQLConnection1.Connected := False;
  end; // if
end;